org.jooq.lambda.Unchecked Java Examples

The following examples show how to use org.jooq.lambda.Unchecked. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChangeLogService.java    From waltz with Apache License 2.0 6 votes vote down vote up
private List<ChangeLog> findByParentReferenceForPhysicalFlow(EntityReference ref,
                                                             Optional<Integer> limit) {
    checkNotNull(ref, "ref must not be null");
    checkTrue(ref.kind() == EntityKind.PHYSICAL_FLOW, "ref should refer to a Physical Flow");

    Future<List<ChangeLog>> flowLogsFuture = dbExecutorPool.submit(() -> changeLogDao.findByParentReference(ref, limit));

    Future<List<ChangeLog>> specLogsFuture = dbExecutorPool.submit(() -> {
        PhysicalFlow flow = physicalFlowDao.getById(ref.id());
        return changeLogDao.findByParentReference(mkRef(EntityKind.PHYSICAL_SPECIFICATION, flow.specificationId()), limit);
    });

    return Unchecked.supplier(() -> {
        List<ChangeLog> flowLogs = flowLogsFuture.get();
        List<ChangeLog> specLogs = specLogsFuture.get();
        List<ChangeLog> all = new ArrayList<>();
        all.addAll(flowLogs);
        all.addAll(specLogs);
        return (List<ChangeLog>) CollectionUtilities.sort(all, Comparator.comparing(ChangeLog::createdAt).reversed());
    }).get();
}
 
Example #2
Source File: HigherEducationTaxonomyImport.java    From waltz with Apache License 2.0 6 votes vote down vote up
/**
 * Capabilities are recorded as model elements with a type of 'Capability'
 *
 * Each capability has an identifier, a name
 *
 * @param doc  xml document
 * @return tuple(id, name, documentation)
 * @throws XPathExpressionException
 */
private Set<Tuple3<String, String, String>> parseCapabilities(Document doc) throws XPathExpressionException {
    XPathExpression capabilitiesXPath = xpathFactory
            .newXPath()
            .compile("/model/elements/element[@type='Capability']");

    XPathExpression nameXPath = xpathFactory.newXPath().compile("name");
    XPathExpression documentationXPath = xpathFactory.newXPath().compile("documentation");

    Function<Node, String> readNameFn = Unchecked.function(nameXPath::evaluate);
    Function<Node, String> readDocFn = Unchecked.function(documentationXPath::evaluate);

    return XmlUtilities
            .stream((NodeList) capabilitiesXPath.evaluate(doc, XPathConstants.NODESET))
            .map(node -> tuple(
                    node.getAttributes().getNamedItem("identifier").getTextContent(),
                    readNameFn.apply(node),
                    readDocFn.apply(node)))
            .collect(toSet());
}
 
Example #3
Source File: EntityStatisticSummaryDao.java    From waltz with Apache License 2.0 6 votes vote down vote up
private <T> List<TallyPack<String>> generateSummaries(Collection<Long> statisticIds,
                                                      Select<Record1<Long>> appIdSelector,
                                                      Field<T> aggregateField,
                                                      Function<T, Double> toTally) {

    checkNotNull(statisticIds, "statisticIds cannot be null");
    checkNotNull(appIdSelector, "appIdSelector cannot be null");
    checkNotNull(aggregateField, "aggregateField cannot be null");
    checkNotNull(toTally, "toTally function cannot be null");

    if (statisticIds.isEmpty()) {
        return Collections.emptyList();
    }

    List<Future<TallyPack<String>>> summaryFutures = statisticIds.stream()
            .map(statId -> dbExecutorPool.submit(() ->
                    generateSummary(statId, appIdSelector, aggregateField, toTally)))
            .collect(toList());

    return summaryFutures.stream()
            .map(f -> Unchecked.supplier(f::get)
                    .get())
            .collect(toList());
}
 
Example #4
Source File: EntityStatisticSummaryDao.java    From waltz with Apache License 2.0 6 votes vote down vote up
public List<TallyPack<String>> generateWithNoRollup(Collection<Long> statisticIds,
                                                    EntityReference entityReference) {

    checkNotNull(statisticIds, "statisticIds cannot be null");
    checkNotNull(entityReference, "entityReference cannot be null");

    if (statisticIds.isEmpty()) {
        return Collections.emptyList();
    }

    List<Future<TallyPack<String>>> summaryFutures = statisticIds.stream()
            .map(statId -> dbExecutorPool.submit(() ->
                    generateWithNoRollup(statId, entityReference)))
            .collect(toList());

    return summaryFutures.stream()
            .map(f -> Unchecked.supplier(f::get)
                    .get())
            .collect(toList());
}
 
Example #5
Source File: CompressibleBinaryPreferencesFormat.java    From RankSys with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Saves a PreferenceData instance in two files for user and item preferences, respectively. The format of the user preferences stream consists on one list per line, starting with the identifier of the user followed by the identifiers of the items related to that. The item preferences stream follows the same format by swapping the roles of users and items.
 *
 * @param prefData preferences
 * @param uo stream of user preferences
 * @param io stream of user preferences
 */
public void write(FastPreferenceData<?, ?> prefData, OutputStream uo, OutputStream io) {
    BiConsumer<FastPreferenceData<?, ?>, OutputStream> saver = Unchecked.biConsumer((prefs, os) -> {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os))) {
            prefs.getUidxWithPreferences().forEach(Unchecked.intConsumer(uidx -> {
                String a = prefs.getUidxPreferences(uidx)
                        .mapToInt(IdxPref::v1)
                        .sorted()
                        .mapToObj(Integer::toString)
                        .collect(joining("\t"));

                writer.write(uidx + "\t" + a);
                writer.newLine();
            }));
        }
    });

    saver.accept(prefData, uo);
    saver.accept(new TransposedPreferenceData<>(prefData), io);
}
 
Example #6
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public User updateUser(User inputUser) {
    HttpUrl route = HttpUrl.parse(host + "/users");
    Request request = new Request.Builder()
            .url(route)
            .put(RequestBodies.jsonObj(inputUser))
            .build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef());
                return user;
            }

            if (response.code() == StatusCodes.NOT_FOUND) {
                return null;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #7
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public User createUser(User inputUser) {
    HttpUrl route = HttpUrl.parse(host + "/users");
    Request request = new Request.Builder()
        .url(route)
        .post(RequestBodies.jsonObj(inputUser))
        .build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.code() == StatusCodes.CREATED) {
                User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef());
                return user;
            }

            if (response.code() == StatusCodes.BAD_REQUEST) {
                return null;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #8
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public boolean deleteUserByEmail(String email) {
    HttpUrl route = HttpUrl.parse(host + "/users")
                           .newBuilder()
                           .addPathSegment(email)
                           .build();
    Request request = new Request.Builder().url(route).delete().build();
    return Unchecked.booleanSupplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.code() == StatusCodes.NO_CONTENT) {
                return true;
            }

            // Maybe you would throw an exception here? We don't feel the need to.
            if (response.code() == StatusCodes.NOT_FOUND) {
                return false;
            }
            throw HttpClient.unknownException(response);
        }
    }).getAsBoolean();
}
 
Example #9
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public User getUserByEmail(String email) {
    HttpUrl route = HttpUrl.parse(host + "/users")
                           .newBuilder()
                           .addPathSegment(email)
                           .build();
    Request request = new Request.Builder().url(route).get().build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            // The user exists
            if (response.isSuccessful()) {
                User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef());
                return user;
            }

            /*
             *  404 Not Found - Either return null or throw your own exception.
             *  We prefer nulls.
             */
            if (response.code() == StatusCodes.NOT_FOUND) {
                return null;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #10
Source File: CompressibleRatingPreferencesFormat.java    From RankSys with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Saves a PreferenceData instance in two files for user and item preferences, respectively. The format of the user preferences stream consists on one list per line, starting with the identifier of the user followed by the identifier-rating pairs of the items related to that. The item preferences stream follows the same format by swapping the roles of users and items.
 *
 * @param prefData preferences
 * @param uo stream of user preferences
 * @param io stream of user preferences
 */
public void write(FastPreferenceData<?, ?> prefData, OutputStream uo, OutputStream io) {
    BiConsumer<FastPreferenceData<?, ?>, OutputStream> saver = Unchecked.biConsumer((prefs, os) -> {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os))) {
            prefs.getUidxWithPreferences().forEach(Unchecked.intConsumer(uidx -> {
                String a = prefs.getUidxPreferences(uidx)
                        .sorted((p1, p2) -> Integer.compare(p1.v1, p2.v1))
                        .map(p -> p.v1 + "\t" + (int) p.v2)
                        .collect(joining("\t"));

                writer.write(uidx + "\t" + a);
                writer.newLine();
            }));
        }
    });

    saver.accept(prefData, uo);
    saver.accept(new TransposedPreferenceData<>(prefData), io);
}
 
Example #11
Source File: UncheckedAndLambdas.java    From training with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	File dir = new File(".");
	Arrays.stream(dir.listFiles()).forEach(file -> {
		try {
			System.out.println(file.getCanonicalPath());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	
		// Ouch, my fingers hurt! All this typing!
	});
	
	
	// TODO use Unchecked.consumer from JOOL library
	// SOLUTION(
	Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> {
		System.out.println(file.getCanonicalPath());
	}));
	// SOLUTION)
}
 
Example #12
Source File: XmlEncoder.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeGuid(String field, UUID value) {
    if (value != null) {
        write(field, Unchecked.consumer(w -> {
            w.writeStartElement("String");
            w.writeCharacters(value.toString());
            w.writeEndElement();
        }));
    } else {
        if (field != null) {
            try {
                streamWriter.writeEmptyElement(field);
            } catch (XMLStreamException e) {
                throw new UaSerializationException(StatusCodes.Bad_EncodingError, e);
            }
        }
    }
}
 
Example #13
Source File: XmlEncoder.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeNodeId(String field, NodeId value) {
    if (value != null) {
        write(field, Unchecked.consumer(w -> {
            w.writeStartElement("Identifier");
            w.writeCharacters(value.toParseableString());
            w.writeEndElement();
        }));
    } else {
        if (field != null) {
            try {
                streamWriter.writeEmptyElement(field);
            } catch (XMLStreamException e) {
                throw new UaSerializationException(StatusCodes.Bad_EncodingError, e);
            }
        }
    }
}
 
Example #14
Source File: XmlEncoder.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeExpandedNodeId(String field, ExpandedNodeId value) {
    if (value != null) {
        write(field, Unchecked.consumer(w -> {
            w.writeStartElement("Identifier");
            w.writeCharacters(value.toParseableString());
            w.writeEndElement();
        }));
    } else {
        if (field != null) {
            try {
                streamWriter.writeEmptyElement(field);
            } catch (XMLStreamException e) {
                throw new UaSerializationException(StatusCodes.Bad_EncodingError, e);
            }
        }
    }
}
 
Example #15
Source File: LogicalFlowService.java    From waltz with Apache License 2.0 6 votes vote down vote up
private LogicalFlowStatistics calculateStatsForAppIdSelector(IdSelectionOptions options) {
    checkNotNull(options, "options cannot be null");

    Select<Record1<Long>> appIdSelector = appIdSelectorFactory.apply(options);

    Future<List<TallyPack<String>>> dataTypeCounts = dbExecutorPool.submit(() ->
            FunctionUtilities.time("DFS.dataTypes",
                () -> logicalFlowStatsDao.tallyDataTypesByAppIdSelector(appIdSelector)));

    Future<LogicalFlowMeasures> appCounts = dbExecutorPool.submit(() ->
            FunctionUtilities.time("DFS.appCounts",
                () -> logicalFlowStatsDao.countDistinctAppInvolvementByAppIdSelector(appIdSelector)));

    Future<LogicalFlowMeasures> flowCounts = dbExecutorPool.submit(() ->
            FunctionUtilities.time("DFS.flowCounts",
                () -> logicalFlowStatsDao.countDistinctFlowInvolvementByAppIdSelector(appIdSelector)));

    Supplier<ImmutableLogicalFlowStatistics> statSupplier = Unchecked.supplier(() -> ImmutableLogicalFlowStatistics.builder()
            .dataTypeCounts(dataTypeCounts.get())
            .appCounts(appCounts.get())
            .flowCounts(flowCounts.get())
            .build());

    return statSupplier.get();
}
 
Example #16
Source File: XmlEncoder.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeQualifiedName(String field, QualifiedName value) {
    if (value != null) {
        write(field, Unchecked.consumer(w -> {
            encodeUInt16("NamespaceIndex", value.getNamespaceIndex());
            encodeString("Name", value.getName());
        }));
    } else {
        if (field != null) {
            try {
                streamWriter.writeEmptyElement(field);
            } catch (XMLStreamException e) {
                throw new UaSerializationException(StatusCodes.Bad_EncodingError, e);
            }
        }
    }
}
 
Example #17
Source File: XmlEncoder.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeLocalizedText(String field, LocalizedText value) {
    if (value != null) {
        write(field, Unchecked.consumer(w -> {
            encodeString("Locale", value.getLocale());
            encodeString("Text", value.getText());
        }));
    } else {
        if (field != null) {
            try {
                streamWriter.writeEmptyElement(field);
            } catch (XMLStreamException e) {
                throw new UaSerializationException(StatusCodes.Bad_EncodingError, e);
            }
        }
    }
}
 
Example #18
Source File: XmlEncoder.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeExtensionObject(String field, ExtensionObject value) {
    if (value != null) {
        write(field, Unchecked.consumer(w -> {
            encodeNodeId("TypeId", value.getEncodingTypeId());

            Object object = value.getEncoded();

            if (object instanceof UaSerializable) {
                UaSerializable serializable = (UaSerializable) object;

                encodeSerializable("Body", serializable);
            } else if (object instanceof ByteString) {
                ByteString byteString = (ByteString) object;

                streamWriter.writeStartElement("Body");
                encodeByteString("ByteString", byteString);
                streamWriter.writeEndElement();
            } else if (object instanceof XmlElement) {
                XmlElement xmlElement = (XmlElement) object;

                encodeXmlElement("Body", xmlElement);
            }
        }));
    }
}
 
Example #19
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public User updateUser(User inputUser) {
    HttpUrl route = HttpUrl.parse(host + "/users");
    Request request = new Request.Builder()
            .url(route)
            .put(RequestBodies.jsonObj(inputUser))
            .build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef());
                return user;
            }

            if (response.code() == StatusCodes.NOT_FOUND) {
                return null;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #20
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public User createUser(User inputUser) {
    HttpUrl route = HttpUrl.parse(host + "/users");
    Request request = new Request.Builder()
        .url(route)
        .post(RequestBodies.jsonObj(inputUser))
        .build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.code() == StatusCodes.CREATED) {
                User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef());
                return user;
            }

            if (response.code() == StatusCodes.BAD_REQUEST) {
                return null;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #21
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public boolean deleteUserByEmail(String email) {
    HttpUrl route = HttpUrl.parse(host + "/users")
                           .newBuilder()
                           .addPathSegment(email)
                           .build();
    Request request = new Request.Builder().url(route).delete().build();
    return Unchecked.booleanSupplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.code() == StatusCodes.NO_CONTENT) {
                return true;
            }

            // Maybe you would throw an exception here? We don't feel the need to.
            if (response.code() == StatusCodes.NOT_FOUND) {
                return false;
            }
            throw HttpClient.unknownException(response);
        }
    }).getAsBoolean();
}
 
Example #22
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public User getUserByEmail(String email) {
    HttpUrl route = HttpUrl.parse(host + "/users")
                           .newBuilder()
                           .addPathSegment(email)
                           .build();
    Request request = new Request.Builder().url(route).get().build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            // The user exists
            if (response.isSuccessful()) {
                User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef());
                return user;
            }

            /*
             *  404 Not Found - Either return null or throw your own exception.
             *  We prefer nulls.
             */
            if (response.code() == StatusCodes.NOT_FOUND) {
                return null;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #23
Source File: SvgDiagramService.java    From waltz with Apache License 2.0 5 votes vote down vote up
public Collection<SvgDiagram> findByGroups(String... groups) {
    return svgDiagramDao.findByGroups(groups)
            .stream()
            .map(Unchecked.function(diagram -> {
                String updatedSvg = convertProductSpecificSvg(diagram);
                return ImmutableSvgDiagram.copyOf(diagram)
                        .withSvg(updatedSvg);
            }))
            .collect(toList());
}
 
Example #24
Source File: LogicalFlowStatsDao.java    From waltz with Apache License 2.0 5 votes vote down vote up
public LogicalFlowMeasures countDistinctAppInvolvementByAppIdSelector(Select<Record1<Long>> appIdSelector) {

        checkNotNull(appIdSelector, "appIdSelector cannot be null");

        Select<Record1<Integer>> inAppCounter = countDistinctApps(
                    appIdSelector,
                    lf.TARGET_ENTITY_ID,
                    lf.SOURCE_ENTITY_ID
        );

        Select<Record1<Integer>> outAppCounter = countDistinctApps(
                    appIdSelector,
                    lf.SOURCE_ENTITY_ID,
                    lf.TARGET_ENTITY_ID
        );

        Select<Record1<Integer>> intraAppCounter = dsl
                    .select(count())
                    .from(APPLICATION)
                    .where(dsl.renderInlined(APPLICATION.ID.in(appIdSelector)));

        Future<Integer> inAppCount = dbExecutorPool.submit(() -> inAppCounter.fetchOne().value1());
        Future<Integer> outAppCount = dbExecutorPool.submit(() -> outAppCounter.fetchOne().value1());
        Future<Integer> intraAppCount = dbExecutorPool.submit(() -> intraAppCounter.fetchOne().value1());

        Supplier<ImmutableLogicalFlowMeasures> appCountSupplier = Unchecked.supplier(() -> ImmutableLogicalFlowMeasures.builder()
                .inbound(inAppCount.get())
                .outbound(outAppCount.get())
                .intra(intraAppCount.get())
                .build());

        return appCountSupplier.get();
    }
 
Example #25
Source File: NavAidExtractor.java    From waltz with Apache License 2.0 5 votes vote down vote up
private String addHyperLinks(SvgDiagram diagram) {
    Function<String, Optional<String>> keyToUrl = mkKeyToUrl(diagram.group());

    return Unchecked.supplier(() -> SvgUtilities.addWaltzEntityLinks(
                                        diagram.svg(),
                                        diagram.keyProperty(),
                                        keyToUrl))
            .get();
}
 
Example #26
Source File: RestClient.java    From StubbornJava with MIT License 5 votes vote down vote up
public List<User> listUsers() {
    HttpUrl route = HttpUrl.parse(host + "/users");
    Request request = new Request.Builder().url(route).get().build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                List<User> users = Json.serializer().fromInputStream(response.body().byteStream(), User.listTypeRef());
                return users;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #27
Source File: CPLSARerankerExample.java    From RankSys with Mozilla Public License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String userPath = args[0];
    String itemPath = args[1];
    String featurePath = args[2];
    String trainDataPath = args[3];
    String featureDataPath = args[4];
    String recIn = args[5];

    double lambda = 0.5;
    int cutoff = 100;
    int numIter = 100;

    FastUserIndex<Long> userIndex = SimpleFastUserIndex.load(UsersReader.read(userPath, lp));
    FastItemIndex<Long> itemIndex = SimpleFastItemIndex.load(ItemsReader.read(itemPath, lp));
    FastFeatureIndex<String> featureIndex = SimpleFastFeatureIndex.load(FeatsReader.read(featurePath, sp));
    FastPreferenceData<Long, Long> trainData = SimpleFastPreferenceData.load(SimpleRatingPreferencesReader.get().read(trainDataPath, lp, lp), userIndex, itemIndex);
    FastFeatureData<Long, String, Double> featureData = SimpleFastFeatureData.load(SimpleFeaturesReader.get().read(featureDataPath, lp, sp), itemIndex, featureIndex);

    CPLSAIAFactorizationModelFactory<Long, Long, String> cPLSAModel = new CPLSAIAFactorizationModelFactory<>(numIter, trainData,featureData);
    Reranker<Long, Long> reranker = new XQuAD<>(cPLSAModel.getAspectModel(), lambda, cutoff, true);

    RecommendationFormat<Long, Long> format = new SimpleRecommendationFormat<>(lp, lp);

    System.out.println("Running xQuAD with cPLSA aspect model");
    String recOut = String.format("%s_xQuAD_cplsa_%.1f", recIn, lambda);
    try (RecommendationFormat.Writer<Long, Long> writer = format.getWriter(recOut)) {
        format.getReader(recIn).readAll()
                .map(rec -> reranker.rerankRecommendation(rec, cutoff))
                .forEach(Unchecked.consumer(writer::write));
    }
}
 
Example #28
Source File: MahoutRecommendationFormat.java    From RankSys with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Stream<Recommendation<U, I>> readAll() {
    return Stream.of(new File(path).listFiles((dir, name) -> name.startsWith("part-")))
            .map(Unchecked.function(file -> new BufferedReader(new FileReader(file))))
            .map(Unchecked.function(this::loadPart))
            .reduce(Stream.empty(), Stream::concat);
}
 
Example #29
Source File: TuplesRecommendationFormat.java    From RankSys with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public synchronized void write(Recommendation<U, I> recommendation) throws IOException {
    U u = recommendation.getUser();
    seq(recommendation.getItems())
            .zipWithIndex()
            .map(t -> tupleWriter.apply(u, t.v1.v1, t.v1.v2, t.v2))
            .forEach(Unchecked.consumer(line -> {
                writer.write(line);
                writer.newLine();
            }));
}
 
Example #30
Source File: D2__Loan_Pattern.java    From training with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	FileExporter fileExporter = new FileExporter();
	OrderExportWriter orderExportWriter = new OrderExportWriter();
	UserExporterWriter userExporterWriter = new UserExporterWriter();
	
	fileExporter.exportFile("orders.txt", Unchecked.consumer(orderExportWriter::writeContent));
	fileExporter.exportFile("users.txt", Unchecked.consumer(userExporterWriter::writeUsers));
}