Example usage for java.lang String join

List of usage examples for java.lang String join

Introduction

In this page you can find the example usage for java.lang String join.

Prototype

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) 

Source Link

Document

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter .

Usage

From source file:net.sf.jabref.importer.fileformat.RepecNepImporter.java

/**
 * Implements grammar rule "Authors"/*from w w  w.  j a  v a 2 s .c o m*/
 *
 * @param be
 * @throws IOException
 */
private void parseAuthors(BibEntry be, BufferedReader in) throws IOException {
    // read authors and institutions
    List<String> authors = new ArrayList<>();
    StringBuilder institutions = new StringBuilder();
    while ((this.lastLine != null) && !"".equals(this.lastLine)
            && !startsWithKeyword(RepecNepImporter.RECOGNIZED_FIELDS)) {

        // read single author
        String author;
        StringBuilder institution = new StringBuilder();
        boolean institutionDone;
        if (this.lastLine.indexOf('(') >= 0) {
            author = this.lastLine.substring(0, this.lastLine.indexOf('(')).trim();
            institutionDone = this.lastLine.indexOf(')') >= 1;
            institution.append(this.lastLine.substring(this.lastLine.indexOf('(') + 1,
                    institutionDone && (this.lastLine.indexOf(')') > (this.lastLine.indexOf('(') + 1))
                            ? this.lastLine.indexOf(')')
                            : this.lastLine.length())
                    .trim());
        } else {
            author = this.lastLine.substring(0, this.lastLine.length()).trim();
            institutionDone = true;
        }

        readLine(in);
        while (!institutionDone && (this.lastLine != null)) {
            institutionDone = this.lastLine.indexOf(')') >= 1;
            institution.append(this.lastLine
                    .substring(0, institutionDone ? this.lastLine.indexOf(')') : this.lastLine.length())
                    .trim());
            readLine(in);
        }

        authors.add(author);

        if (institution.length() > 0) {
            institutions.append(
                    (institutions.length() == 0) ? institution.toString() : " and " + institution.toString());
        }
    }

    if (!authors.isEmpty()) {
        be.setField(FieldName.AUTHOR, String.join(" and ", authors));
    }
    if (institutions.length() > 0) {
        be.setField("institution", institutions.toString());
    }
}

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java

public List<Map<String, Object>> query(String filter, String indices) throws Exception {
    if (filter == null || filter.isEmpty()) {
        throw new IllegalArgumentException("filter must be not null");
    }/*from  w  w  w. j  av a2  s .  co m*/
    List<Map<String, Object>> results = new ArrayList<>();
    String json = rawQuery(filter);

    List<String> index = indices == null ? EMPTY_LIST : new ArrayList<>(Arrays.asList(indices.split(",")));
    Response response = null;
    //  Using a loop in case results are greater than default results size
    Map<String, String> params = new HashMap<>();
    params.put(PREFERENCE, UUID.randomUUID().toString());
    String jsonQuery = "{" + "\"from\":0," + "\"size\":" + SIZE_DEFAULT + "," + "\"query\":" + json + "}";
    HttpEntity entity = new NStringEntity(jsonQuery, ContentType.APPLICATION_JSON);
    boolean retry = false;
    String endpoint = null;
    do {
        try {
            endpoint = "/" + String.join(",", index) + "/_search";
            response = headers == null ? client.performRequest(GET, endpoint, params, entity)
                    : client.performRequest(GET, endpoint, params, entity, headers);
            retry = false;
        } catch (ResponseException e) {
            log.warn(e.toString());
            Map<String, Object> exception = JsonUtil.getMapper()
                    .readValue(e.getResponse().getEntity().getContent(), Map.class);
            Map<String, Object> error = (Map<String, Object>) exception.get(ERROR);
            if (error != null) {
                String type = (String) error.get(TYPE);
                String badIndex = (String) error.get(RESOURCE_ID);
                if (type != null && type.equals(INDEX_NOT_FOUND)) {
                    retry = true;
                    index.remove(badIndex);
                    if (index.isEmpty()) {
                        return results;
                    }
                }
            }
        }
    } while (retry);
    Map<String, Object> responseMap = JsonUtil.getMapper().readValue(response.getEntity().getContent(),
            Map.class);
    Map<String, Object> allHits = (Map<String, Object>) responseMap.get(HITS);
    List<Map<String, Object>> hits = (List<Map<String, Object>>) allHits.get(HITS);
    results.addAll(hits);
    long totalHits = new Long((Integer) allHits.get(TOTAL));
    long currentHits = hits.size();
    while (currentHits < totalHits) {
        long pageSize = SIZE_DEFAULT;
        if ((currentHits + SIZE_DEFAULT) > totalHits) {
            pageSize = totalHits - currentHits;
        }
        jsonQuery = "{" + "\"from\":" + currentHits + "," + "\"size\":" + pageSize + "," + "\"query\":" + json
                + "}";
        entity = new NStringEntity(jsonQuery, ContentType.APPLICATION_JSON);
        response = headers == null ? client.performRequest(GET, endpoint, params, entity)
                : client.performRequest(GET, endpoint, params, entity, headers);
        responseMap = JsonUtil.getMapper().readValue(response.getEntity().getContent(), Map.class);
        allHits = (Map<String, Object>) responseMap.get(HITS);
        hits = (List<Map<String, Object>>) allHits.get(HITS);
        currentHits += hits.size();
        log.debugf("currentHits [%s] totalHits [%s]", currentHits, totalHits);
        results.addAll(hits);
    }
    log.debugf("Results %s", results.size());
    return results;
}

From source file:com.thoughtworks.go.domain.builder.FetchPluggableArtifactBuilderTest.java

@Test
public void shouldUpdateEnvironmentVariableContextAfterFetchingArtifact() {
    final FetchPluggableArtifactBuilder builder = new FetchPluggableArtifactBuilder(new RunIfConfigs(),
            new NullBuilder(), "", jobIdentifier, artifactStore, fetchPluggableArtifactTask.getConfiguration(),
            fetchPluggableArtifactTask.getArtifactId(), sourceOnServer, metadataDest, checksumFileHandler);

    EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext();
    environmentVariableContext.setProperty("VAR1", "old-value1", false);
    environmentVariableContext.setProperty("VAR2", "old-value2", true);
    environmentVariableContext.setProperty("VAR3", "old-value3", true);
    environmentVariableContext.setProperty("VAR4", "old-value4", true);

    when(artifactExtension.fetchArtifact(eq(PLUGIN_ID), eq(artifactStore), any(), anyMap(),
            eq(metadataDest.getParent()))).thenReturn(
                    Arrays.asList(new FetchArtifactEnvironmentVariable("VAR1", "value1-is-now-secure", true),
                            new FetchArtifactEnvironmentVariable("VAR2", "value2-is-now-insecure", false),
                            new FetchArtifactEnvironmentVariable("VAR3", "value3-but-secure-is-unchanged",
                                    true),
                            new FetchArtifactEnvironmentVariable("VAR5", "new-value5-insecure", false),
                            new FetchArtifactEnvironmentVariable("VAR6", "new-value6-secure", true)));

    builder.build(publisher, environmentVariableContext, null, artifactExtension, registry, "utf-8");

    Map<String, String> newVariablesAfterFetchArtifact = environmentVariableContext.getProperties();

    assertThat(newVariablesAfterFetchArtifact.size(), is(6));

    assertVariable(environmentVariableContext, "VAR1", "value1-is-now-secure", true);
    assertVariable(environmentVariableContext, "VAR2", "value2-is-now-insecure", false);
    assertVariable(environmentVariableContext, "VAR3", "value3-but-secure-is-unchanged", true);
    assertVariable(environmentVariableContext, "VAR4", "old-value4", true);
    assertVariable(environmentVariableContext, "VAR5", "new-value5-insecure", false);
    assertVariable(environmentVariableContext, "VAR6", "new-value6-secure", true);

    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(publisher, atLeastOnce()).taggedConsumeLine(eq(OUT), captor.capture());

    assertThat(captor.getAllValues(), hasItems(
            "WARNING: Replacing environment variable: VAR1 = ******** (previously: old-value1)",
            "WARNING: Replacing environment variable: VAR2 = value2-is-now-insecure (previously: ********)",
            "WARNING: Replacing environment variable: VAR3 = ******** (previously: ********)",
            " NOTE: Setting new environment variable: VAR5 = new-value5-insecure",
            " NOTE: Setting new environment variable: VAR6 = ********"));

    String consoleOutput = String.join(" -- ", captor.getAllValues());
    assertThat(consoleOutput, not(containsString("value1-is-now-secure")));
    assertThat(consoleOutput, not(containsString("value3-but-secure-is-unchanged")));
    assertThat(consoleOutput, not(containsString("new-value6-secure")));
}

From source file:com.ggvaidya.scinames.ui.BulkChangeEditorController.java

private void setupChangesTableView() {
    changesTableView.setEditable(true);//w  w  w.ja  v a 2 s  .  co  m
    changesTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    changesTableView.getColumns().clear();

    TableColumn<PotentialChange, ChangeType> colChangeType = new TableColumn<>("Type");
    colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(),
            ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT,
            ChangeType.ERROR));
    colChangeType.setCellValueFactory(new PropertyValueFactory<>("type"));
    colChangeType.setPrefWidth(100.0);
    colChangeType.setEditable(true);
    changesTableView.getColumns().add(colChangeType);

    TableColumn<PotentialChange, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From");
    colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from"));
    colChangeFrom.setPrefWidth(200.0);
    colChangeFrom.setEditable(true);
    changesTableView.getColumns().add(colChangeFrom);

    TableColumn<PotentialChange, ObservableSet<Name>> colChangeTo = new TableColumn<>("To");
    colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to"));
    colChangeTo.setPrefWidth(200.0);
    colChangeTo.setEditable(true);
    changesTableView.getColumns().add(colChangeTo);

    TableColumn<PotentialChange, String> colChangeDataset = new TableColumn<>("Dataset");
    colChangeDataset.setCellValueFactory(new PropertyValueFactory<>("dataset"));
    colChangeDataset.setPrefWidth(100.0);
    changesTableView.getColumns().add(colChangeDataset);

    ChangeFilter cf = project.getChangeFilter();
    TableColumn<PotentialChange, String> colFiltered = new TableColumn<>("Eliminated by filter?");
    colFiltered.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    cf.test(features.getValue()) ? "Allowed" : "Eliminated"));
    changesTableView.getColumns().add(colFiltered);

    TableColumn<PotentialChange, String> colNote = new TableColumn<>("Note");
    colNote.setCellFactory(TextFieldTableCell.forTableColumn());
    colNote.setCellValueFactory(new PropertyValueFactory<>("note"));
    colNote.setPrefWidth(100.0);
    colNote.setEditable(true);
    changesTableView.getColumns().add(colNote);

    TableColumn<PotentialChange, String> colProperties = new TableColumn<>("Properties");
    colProperties.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getProperties().entrySet().stream()
                            .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted()
                            .collect(Collectors.joining("; "))));
    changesTableView.getColumns().add(colProperties);

    TableColumn<PotentialChange, String> colCitations = new TableColumn<>("Citations");
    colCitations.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted()
                            .collect(Collectors.joining("; "))));
    changesTableView.getColumns().add(colCitations);

    TableColumn<PotentialChange, String> colGenera = new TableColumn<>("Genera");
    colGenera.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus())
                            .distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colGenera);

    TableColumn<PotentialChange, String> colSpecificEpithet = new TableColumn<>("Specific epithet");
    colSpecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(String
                    .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet())
                            .filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colSpecificEpithet);

    // TODO: if we can get an ObservableList over tp.getAllChanges(), then this table
    // will update dynamically as changes are made. Won't that be something.
    // Yes, we want to getAllChanges() so we can see which ones are filtered out.
    changesTableView.setItems(foundChanges);
    changesTableView.getSortOrder().add(colChangeType);
}

From source file:com.caricah.iotracah.core.worker.DumbWorker.java

private static String quickCheckIdKey(String partition, List<String> nameParts) {

    return getPartitionAsInitialParentId(partition) + ":" + String.join(":", nameParts);
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testEventIdformulaformfields02()./*from www. j a va2 s  .  c  o m*/
 * with variables
 * @throws Exception Exception
 */
@Test
public void testEventIdformulaformfields02() throws Exception {
    // given
    String formUUID = UUID.randomUUID().toString();
    String param81 = "Test[" + formUUID + "]";
    FormJSON testform = TestDataBuilder.createStoreReceipt();

    // when
    expect(this.flow.getData()).andReturn(this.mockarchive);
    expect(this.request.getParameter("83")).andReturn(param81);
    expect(this.mockarchive.getForm(formUUID)).andReturn(testform);

    replayAll();
    FormJSONField field = this.ws.eventIdformulaformfields(this.flow, this.request);

    // verify
    verifyAll();

    assertEquals("$subtotal,$tax,$delivery,$total", String.join(",", field.getOptions()));
}

From source file:com.github.lindenb.mscheduler.MScheduler.java

private int build(final String argv[]) {
    Transaction txn = null;/*w ww  .j ava2  s .com*/
    BufferedReader in = null;
    String makeExecutable = "make";
    try {
        this.options
                .addOption(Option.builder(OPTION_MAKE_EXECUTABLE).hasArg(true).longOpt(OPTION_MAKE_EXECUTABLE)
                        .argName("MAKE").desc("make executable. Default: " + makeExecutable).build());

        this.options.addOption(Option.builder(OPTION_MAKEFILEIN).hasArg(true).longOpt("makefile").argName("DIR")
                .desc("debug Makefile").build());

        final CommandLineParser parser = new DefaultParser();
        this.cmdLine = parser.parse(this.options, argv);
        final List<String> args = this.cmdLine.getArgList();

        if (cmdLine.hasOption(OPTION_MAKE_EXECUTABLE)) {
            makeExecutable = cmdLine.getOptionValue(OPTION_MAKE_EXECUTABLE);
        }

        if (cmdLine.hasOption(OPTION_HELP)) {
            return printHelp("build");
        }

        if (parseWorkingDirectory() != 0)
            return -1;

        if (!cmdLine.hasOption(OPTION_MAKEFILEIN)) {
            LOG.error("option -" + OPTION_MAKEFILEIN + " undefined");
            return -1;
        }
        final File makefileIn = new File(cmdLine.getOptionValue(OPTION_MAKEFILEIN));
        if (!makefileIn.exists()) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " file doesn't exists: " + makefileIn);
            return -1;
        }

        if (!makefileIn.isFile()) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " this is not a file : " + makefileIn);
            return -1;
        }
        if (!makefileIn.isAbsolute() || makefileIn.getParentFile() == null) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " path is not absolute : " + makefileIn);
            return -1;
        }

        if (openEnvironement(txn, true, false) != 0) {
            return -1;
        }

        final List<String> cmdargs = new ArrayList<>();
        cmdargs.add(makeExecutable);
        cmdargs.add("-ndr");
        cmdargs.add("-C");
        cmdargs.add(makefileIn.getParentFile().getPath());
        cmdargs.add("-f");
        cmdargs.add(makefileIn.getName());
        for (final String arg : args)
            cmdargs.add(arg);

        LOG.info("invoking make :" + String.join(" ", cmdargs));
        final ProcessBuilder procbuilder = new ProcessBuilder(cmdargs);
        procbuilder.directory(makefileIn.getParentFile());

        final Process proc = procbuilder.start();
        final StreamBoozer sb = new StreamBoozer(proc.getErrorStream(), System.err, "[make]");
        sb.start();

        LOG.info("Reading graph");
        in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        final Graph graph = Graph.parse(in);
        IoUtils.close(in);
        in = null;
        final Task.Binding taskBinding = new Task.Binding();
        int nTargets = 0;
        LOG.info("inserting targets");
        final DatabaseEntry key = new DatabaseEntry();
        final DatabaseEntry data = new DatabaseEntry();
        for (final Target t : graph.getTargets()) {
            if (nTargets++ % 100 == 0)
                LOG.info("inserting " + t.getName() + " " + nTargets);
            final Task task = new Task(t);

            //skip those targets, eg. "Makefile"
            if (task.shellScriptLines.isEmpty() && task.getPrerequisites().isEmpty()) {
                task.targetStatus = TaskStatus.COMPLETED;
            }

            StringBinding.stringToEntry(t.getName(), key);
            taskBinding.objectToEntry(task, data);
            if (this.targetsDatabase.put(txn, key, data) != OperationStatus.SUCCESS) {
                LOG.error("Cannot insert " + task);
                return -1;
            }
        }

        LOG.info("inserting metadata");
        StringBinding.stringToEntry(BASEDIRKEY, key);
        StringBinding.stringToEntry(makefileIn.getParentFile().getPath(), data);
        if (this.metaDatabase.put(txn, key, data) != OperationStatus.SUCCESS) {
            LOG.error("Cannot insert " + BASEDIRKEY);
            return -1;
        }

        return 0;
    } catch (Exception err) {
        LOG.error("Boum", err);
        return -1;
    } finally {
        close();
    }
}

From source file:business.services.MailService.java

public void notifyHubuser(User hubUser, List<LabRequestRepresentation> labRequests) {
    if (!hubUser.isHubUser()) {
        log.warn("The user is no hub user: " + hubUser.getUsername());
        return;/*from   w  w w. ja v  a2s . c  o m*/
    }
    List<String> codes = new ArrayList<>();
    List<String> snippets = new ArrayList<>();
    for (LabRequestRepresentation labRequest : labRequests) {
        codes.add(labRequest.getLabRequestCode());
        String link = getLink("/#/lab-request/view/" + labRequest.getId());
        String snippet = String.format(hubUserNotificationLabSnippet, link, // %1
                labRequest.getLabRequestCode(), // %2
                labRequest.getRequest().getTitle(), // %3
                labRequest.getLab().getNumber(), // %4
                labRequest.getLab().getName(), // %5
                labRequest.getRequesterName(), // %6
                labRequest.getRequest().getPathologistName() == null ? ""
                        : labRequest.getRequest().getPathologistName(), // %7
                labRequest.getRequesterLab().getNumber(), // %8
                labRequest.getRequesterLab().getName() // %9
        );
        snippets.add(snippet);
    }
    String labRequestCodes = String.join(", ", codes);
    String labRequestSnippets = String.join("\n", snippets);

    log.info("Notify hub user " + hubUser.getUsername() + " for lab requests " + labRequestCodes + ".");

    if (hubUser.getContactData() == null || hubUser.getContactData().getEmail() == null
            || hubUser.getContactData().getEmail().trim().isEmpty()) {
        log.warn("No email address set for hub user " + hubUser.getUsername());
        return;
    }
    log.info("Sending notification to " + hubUser.getContactData().getEmail());
    try {
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        message.setTo(hubUser.getContactData().getEmail());
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(
                String.format("PALGA-verzoek aan laboratoria, aanvraagnummers: %s", labRequestCodes));
        String body = String.format(hubUserNotificationTemplate, labRequestSnippets /* %1 */);
        message.setText(body);
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}

From source file:net.sf.jabref.exporter.ExportFormat.java

/**
 * Perform the export of {@code database}.
 *
 * @param databaseContext the database to export from.
 * @param file       the file to write the resulting export to
 * @param encoding   The encoding of the database
 * @param entries    Contains all entries that should be exported.
 * @throws IOException if a problem occurred while trying to write to {@code writer}
 *                     or read from required resources.
 * @throws Exception   if any other error occurred during export.
 * @see net.sf.jabref.exporter.IExportFormat#performExport(BibDatabaseContext, String, Charset, List)
 *///from  w w w  .  j  a  va2 s  .co  m
@Override
public void performExport(final BibDatabaseContext databaseContext, final String file, final Charset encoding,
        List<BibEntry> entries) throws Exception {
    Objects.requireNonNull(databaseContext);
    Objects.requireNonNull(entries);
    if (entries.isEmpty()) { // Do not export if no entries to export -- avoids exports with only template text
        return;
    }
    File outFile = new File(file);
    SaveSession ss = null;
    if (this.encoding != null) {
        try {
            ss = new SaveSession(this.encoding, false);
        } catch (IOException ex) {
            // Perhaps the overriding encoding doesn't work?
            // We will fall back on the default encoding.
            LOGGER.warn("Can not get save session.", ex);
        }
    }
    if (ss == null) {
        ss = new SaveSession(encoding, false);
    }

    try (VerifyingWriter ps = ss.getWriter()) {

        Layout beginLayout = null;

        // Check if this export filter has bundled name formatters:
        // Set a global field, so all layouts have access to the custom name formatters:
        Globals.prefs.customExportNameFormatters = readFormatterFile(lfFileName);

        List<String> missingFormatters = new ArrayList<>(1);

        // Print header
        try (Reader reader = getReader(lfFileName + ".begin.layout")) {
            LayoutHelper layoutHelper = new LayoutHelper(reader,
                    Globals.journalAbbreviationLoader.getRepository());
            beginLayout = layoutHelper.getLayoutFromText();
        } catch (IOException ex) {
            // If an exception was cast, export filter doesn't have a begin
            // file.
        }
        // Write the header
        if (beginLayout != null) {
            ps.write(beginLayout.doLayout(databaseContext, encoding));
            missingFormatters.addAll(beginLayout.getMissingFormatters());
        }

        /*
         * Write database entries; entries will be sorted as they appear on the
         * screen, or sorted by author, depending on Preferences. We also supply
         * the Set entries - if we are to export only certain entries, it will
         * be non-null, and be used to choose entries. Otherwise, it will be
         * null, and be ignored.
         */
        SavePreferences savePrefs = SavePreferences.loadForExportFromPreferences(Globals.prefs);
        List<BibEntry> sorted = BibDatabaseWriter.getSortedEntries(databaseContext, entries, savePrefs);

        // Load default layout
        Layout defLayout;
        LayoutHelper layoutHelper;
        try (Reader reader = getReader(lfFileName + ".layout")) {
            layoutHelper = new LayoutHelper(reader, Globals.journalAbbreviationLoader.getRepository());
            defLayout = layoutHelper.getLayoutFromText();
        }
        if (defLayout != null) {
            missingFormatters.addAll(defLayout.getMissingFormatters());
            if (!missingFormatters.isEmpty()) {
                LOGGER.warn(missingFormatters);
            }
        }
        Map<String, Layout> layouts = new HashMap<>();
        Layout layout;

        ExportFormats.entryNumber = 0;
        for (BibEntry entry : sorted) {
            ExportFormats.entryNumber++; // Increment entry counter.
            // Get the layout
            String type = entry.getType();
            if (layouts.containsKey(type)) {
                layout = layouts.get(type);
            } else {
                try (Reader reader = getReader(lfFileName + '.' + type + ".layout")) {
                    // We try to get a type-specific layout for this entry.
                    layoutHelper = new LayoutHelper(reader, Globals.journalAbbreviationLoader.getRepository());
                    layout = layoutHelper.getLayoutFromText();
                    layouts.put(type, layout);
                    if (layout != null) {
                        missingFormatters.addAll(layout.getMissingFormatters());
                    }

                } catch (IOException ex) {
                    // The exception indicates that no type-specific layout
                    // exists, so we
                    // go with the default one.
                    layout = defLayout;
                }
            }

            // Write the entry
            ps.write(layout.doLayout(entry, databaseContext.getDatabase()));
        }

        // Print footer

        // changed section - begin (arudert)
        Layout endLayout = null;
        try (Reader reader = getReader(lfFileName + ".end.layout")) {
            layoutHelper = new LayoutHelper(reader, Globals.journalAbbreviationLoader.getRepository());
            endLayout = layoutHelper.getLayoutFromText();
        } catch (IOException ex) {
            // If an exception was thrown, export filter doesn't have an end
            // file.
        }

        // Write footer
        if ((endLayout != null) && (this.encoding != null)) {
            ps.write(endLayout.doLayout(databaseContext, this.encoding));
            missingFormatters.addAll(endLayout.getMissingFormatters());
        }

        // Clear custom name formatters:
        Globals.prefs.customExportNameFormatters = null;

        if (!missingFormatters.isEmpty()) {
            StringBuilder sb = new StringBuilder("The following formatters could not be found: ");
            sb.append(String.join(", ", missingFormatters));
            LOGGER.warn(sb);
        }
        finalizeSaveSession(ss, outFile);
    }

}

From source file:org.ligoj.app.plugin.prov.aws.ProvAwsTerraformServiceTest.java

private ProvAwsTerraformService newProvAwsTerraformService() {
    final ProvAwsTerraformService resource = new ProvAwsTerraformService();
    applicationContext.getAutowireCapableBeanFactory().autowireBean(resource);
    resource.utils = new TerraformUtils() {

        @Override//from  www. j  a  va  2 s  .c o m
        public File toFile(final Subscription subscription, final String... fragments) throws IOException {
            final File file = fragments.length == 0 ? MOCK_PATH
                    : new File(MOCK_PATH, String.join("/", fragments));
            FileUtils.forceMkdirParent(file);
            return file;
        }
    };
    return resource;
}