Example usage for java.lang System lineSeparator

List of usage examples for java.lang System lineSeparator

Introduction

In this page you can find the example usage for java.lang System lineSeparator.

Prototype

String lineSeparator

To view the source code for java.lang System lineSeparator.

Click Source Link

Usage

From source file:es.upm.dit.xsdinferencer.XSDInferencer.java

/**
 * Method that, given an args array, does the whole inference process by calling the appropriate submodules.
 * @param args the args array, as provided by {@link XSDInferencer#main(String[])}
 * @return a {@link Results} object with the inference results (both statistics and XSDs)
 * @throws XSDConfigurationException if there is a problem with the configuration
 * @throws IOException if there is an I/O problem while reading the input XML files or writing the output files
 * @throws JDOMException if there is any problem while parsing the input XML files 
 *//* w w  w  .j ava  2s. c  o  m*/
public Results inferSchema(String[] args) throws XSDInferencerException {
    try {
        XSDInferenceConfiguration configuration = new XSDInferenceConfiguration(args);
        FilenameFilter filenameFilter;
        if (configuration.getWorkingFormat().equals("xml")) {
            filenameFilter = FILE_NAME_FILTER_XML_EXTENSION;
            List<File> xmlFiles = getInstanceFileNames(args, filenameFilter);
            List<Document> xmlDocuments = new ArrayList<>(xmlFiles.size());
            SAXBuilder saxBuilder = new SAXBuilder();
            for (int i = 0; i < xmlFiles.size(); i++) {
                File xmlFile = xmlFiles.get(i);
                System.out.print("Reading input file " + xmlFile.getName() + "...");
                FileInputStream fis = new FileInputStream(xmlFile);
                //BufferedReader reader = new BufferedReader(new InputStreamReader(fis, Charsets.UTF_8));
                Document xmlDocument = saxBuilder.build(fis);
                xmlDocuments.add(xmlDocument);
                System.out.println("OK");
            }
            return inferSchema(xmlDocuments, configuration);
        } else if (configuration.getWorkingFormat().equals("json")) {
            filenameFilter = FILE_NAME_FILTER_JSON_EXTENSION;
            List<File> jsonFiles = getInstanceFileNames(args, filenameFilter);
            List<JSONObject> jsonDocumentWithRootObjects = new ArrayList<>(jsonFiles.size());
            List<JSONArray> jsonDocumentWithRootArrays = new ArrayList<>(jsonFiles.size());
            for (int i = 0; i < jsonFiles.size(); i++) {
                File jsonFile = jsonFiles.get(i);
                String jsonString = Joiner.on(System.lineSeparator())
                        .join(Files.readAllLines(jsonFile.toPath()));
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(jsonString);
                } catch (JSONException e) {
                }

                if (jsonObject != null) {
                    jsonDocumentWithRootObjects.add(jsonObject);
                } else {
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = new JSONArray(jsonString);
                    } catch (JSONException e) {
                    }
                    if (jsonArray != null) {
                        jsonDocumentWithRootArrays.add(jsonArray);
                    } else {
                        throw new JSONException("Invalid JSON Document " + jsonFile);
                    }

                }
            }
            return inferSchema(jsonDocumentWithRootObjects, jsonDocumentWithRootArrays, configuration);
        } else {
            throw new InvalidXSDConfigurationParameterException(
                    "Unknown working format. Impossible to load files");
        }
    } catch (IOException | JDOMException | RuntimeException e) {
        throw new XSDInferencerException(e);
    }

}

From source file:com.opengamma.integration.copier.portfolio.writer.MasterPortfolioWriter.java

@Override
public void setPath(String[] newPath) {
    ArgumentChecker.noNulls(newPath, "newPath");

    if (!Arrays.equals(newPath, _currentPath)) {

        // Update positions in position map, concurrently, and wait for their completion
        if (_mergePositions && _multithread) {
            List<Callable<Integer>> tasks = new ArrayList<>();
            for (final ManageablePosition position : _securityIdToPosition.values()) {
                testQuantities(position);
                tasks.add(new Callable<Integer>() {
                    @Override/*from w ww  .j a  v a 2s . co m*/
                    public Integer call() throws Exception {
                        try {
                            // Update the position in the position master
                            PositionDocument addedDoc = _positionMaster.update(new PositionDocument(position));
                            s_logger.debug("Updated position {}", position);
                            // Add the new position to the portfolio node
                            _currentNode.addPosition(addedDoc.getUniqueId());
                        } catch (Exception e) {
                            s_logger.error("Unable to update position " + position.getUniqueId() + ": "
                                    + e.getMessage());
                        }
                        return 0;
                    }
                });
            }
            try {
                List<Future<Integer>> futures = _executorService.invokeAll(tasks);
            } catch (Exception e) {
                s_logger.warn("ExecutorService invokeAll failed: " + e.getMessage());
            }
        }

        // Reset position map
        _securityIdToPosition = new HashMap<>();

        if (_originalRoot != null) {
            _originalNode = findNode(newPath, _originalRoot);
            _currentNode = getOrCreateNode(newPath, _portfolioDocument.getPortfolio().getRootNode());
        } else {
            _currentNode = getOrCreateNode(newPath, _portfolioDocument.getPortfolio().getRootNode());
        }

        // If keeping original portfolio nodes and merging positions, populate position map with existing positions in node
        if (_keepCurrentPositions && _mergePositions && _originalNode != null) {
            s_logger.debug("Storing security associations for positions " + _originalNode.getPositionIds()
                    + " at path " + StringUtils.join(newPath, '/'));
            for (ObjectId positionId : _originalNode.getPositionIds()) {
                ManageablePosition position = null;
                try {
                    position = _positionMaster.get(positionId, VersionCorrection.LATEST).getPosition();
                } catch (Exception e) {
                    // no action
                    s_logger.error("Exception retrieving position " + positionId, e);
                }
                if (position != null) {
                    position.getSecurityLink().resolve(_securitySource);
                    if (position.getSecurity() != null) {
                        if (_securityIdToPosition.containsKey(position.getSecurity())) {
                            ManageablePosition existing = _securityIdToPosition.get(position.getSecurity());
                            s_logger.warn("Merging positions but found existing duplicates under path "
                                    + StringUtils.join(newPath, '/') + ": " + position + " and " + existing
                                    + ".  New trades for security "
                                    + position.getSecurity().getUniqueId().getObjectId()
                                    + " will be added to position " + position.getUniqueId());

                        } else {
                            _securityIdToPosition.put(position.getSecurity().getUniqueId().getObjectId(),
                                    position);
                        }
                    }
                }
            }
            if (s_logger.isDebugEnabled()) {
                StringBuilder sb = new StringBuilder("Cached security to position mappings at path ")
                        .append(StringUtils.join(newPath, '/')).append(":");
                for (Map.Entry<ObjectId, ManageablePosition> entry : _securityIdToPosition.entrySet()) {
                    sb.append(System.lineSeparator()).append("  ").append(entry.getKey()).append(" = ")
                            .append(entry.getValue().getUniqueId());
                }
                s_logger.debug(sb.toString());
            }
        }

        _currentPath = newPath;
    }
}

From source file:org.codice.alliance.nsili.source.NsiliSource.java

@Override
public String getDescription() {
    StringBuilder sb = new StringBuilder();
    sb.append(describableProperties.getProperty(DESCRIPTION)).append(System.getProperty(System.lineSeparator()))
            .append(description);//from   w  ww . ja va 2 s .  co m
    return sb.toString();
}

From source file:org.ballerinalang.langserver.command.CommandExecutor.java

/**
 * Get TextEdit from doc attachment info.
 *
 * @param attachmentInfo    Doc attachment info
 * @param contentComponents file content component
 * @return {@link TextEdit}     Text edit for attachment info
 *///  w  w  w  .j av a2s  .  c o  m
private static TextEdit getTextEdit(CommandUtil.DocAttachmentInfo attachmentInfo, String[] contentComponents) {
    int replaceFrom = attachmentInfo.getReplaceStartFrom();
    int replaceEndCol = contentComponents[attachmentInfo.getReplaceStartFrom()].length();
    Range range = new Range(new Position(replaceFrom, 0), new Position(replaceFrom, replaceEndCol));
    String replaceText = attachmentInfo.getDocAttachment() + System.lineSeparator()
            + contentComponents[replaceFrom];
    return new TextEdit(range, replaceText);
}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

private String getObjectTextForDebugInfo(final DataObject dataObject) {

    final String objectText;
    if (dataObject.isComplex()) {
        if (dataObject.value() instanceof List) {
            final StringBuilder builder = new StringBuilder();
            builder.append("[");
            builder.append(System.lineSeparator());
            this.appendItemValues(dataObject, builder);
            builder.append("]");
            builder.append(System.lineSeparator());
            objectText = builder.toString();
        } else {// w w  w  .  ja v a  2 s  . c om
            objectText = String.valueOf(dataObject.rawValue());
        }
    } else if (dataObject.isByteArray()) {
        objectText = this.getDebugInfoByteArray((byte[]) dataObject.value());
    } else if (dataObject.isBitString()) {
        objectText = this.getDebugInfoBitStringBytes(((BitString) dataObject.value()).bitString());
    } else if (dataObject.isCosemDateFormat() && dataObject.value() instanceof CosemDateTime) {
        objectText = this.getDebugInfoDateTimeBytes(((CosemDateTime) dataObject.value()).encode());
    } else {
        objectText = String.valueOf(dataObject.rawValue());
    }

    return objectText;
}

From source file:com.unboundid.scim2.common.types.AttributeDefinition.java

/**
 * Called by toString.  This is used to format the output of the object
 * a little to help readability./*  w  w w. ja va2  s.c  o  m*/
 *
 * @param indent the string to use for each indent increment.  For example,
 *               one might use "  " for a 2 space indent.
 * @return a string representation of this attribute.
 */
private String toIndentedString(final String indent) {
    StringBuilder builder = new StringBuilder();
    builder.append(indent);
    builder.append("Name: ");
    builder.append(getName());
    builder.append(" Description: ");
    builder.append(getDescription());
    builder.append(" isReadOnly: ");
    builder.append(" isRequired: ");
    builder.append(isRequired());
    builder.append(" isCaseExact: ");
    builder.append(isCaseExact());
    builder.append(System.lineSeparator());
    if (getSubAttributes() != null) {
        for (AttributeDefinition a : getSubAttributes()) {
            builder.append(a.toIndentedString(indent + "  "));
        }
    }
    return builder.toString();
}

From source file:org.apache.flink.yarn.cli.FlinkYarnSessionCli.java

public int run(String[] args) {
    ///*from   ww  w  .ja va  2  s  .  co  m*/
    //   Command Line Options
    //
    Options options = new Options();
    addGeneralOptions(options);
    addRunOptions(options);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        printUsage();
        return 1;
    }

    // Query cluster for metrics
    if (cmd.hasOption(QUERY.getOpt())) {
        AbstractYarnClusterDescriptor yarnDescriptor = getClusterDescriptor();
        String description;
        try {
            description = yarnDescriptor.getClusterDescription();
        } catch (Exception e) {
            System.err.println(
                    "Error while querying the YARN cluster for available resources: " + e.getMessage());
            e.printStackTrace(System.err);
            return 1;
        }
        System.out.println(description);
        return 0;
    } else if (cmd.hasOption(APPLICATION_ID.getOpt())) {

        AbstractYarnClusterDescriptor yarnDescriptor = getClusterDescriptor();

        //configure ZK namespace depending on the value passed
        String zkNamespace = cmd.hasOption(ZOOKEEPER_NAMESPACE.getOpt())
                ? cmd.getOptionValue(ZOOKEEPER_NAMESPACE.getOpt())
                : yarnDescriptor.getFlinkConfiguration().getString(HA_ZOOKEEPER_NAMESPACE_KEY,
                        cmd.getOptionValue(APPLICATION_ID.getOpt()));
        LOG.info("Going to use the ZK namespace: {}", zkNamespace);
        yarnDescriptor.getFlinkConfiguration().setString(HA_ZOOKEEPER_NAMESPACE_KEY, zkNamespace);

        try {
            yarnCluster = yarnDescriptor.retrieve(cmd.getOptionValue(APPLICATION_ID.getOpt()));
        } catch (Exception e) {
            throw new RuntimeException("Could not retrieve existing Yarn application", e);
        }

        if (detachedMode) {
            LOG.info("The Flink YARN client has been started in detached mode. In order to stop "
                    + "Flink on YARN, use the following command or a YARN web interface to stop it:\n"
                    + "yarn application -kill " + APPLICATION_ID.getOpt());
            yarnCluster.disconnect();
        } else {
            runInteractiveCli(yarnCluster, true);
        }
    } else {

        AbstractYarnClusterDescriptor yarnDescriptor;
        try {
            yarnDescriptor = createDescriptor(null, cmd);
        } catch (Exception e) {
            System.err.println("Error while starting the YARN Client: " + e.getMessage());
            e.printStackTrace(System.err);
            return 1;
        }

        try {
            yarnCluster = yarnDescriptor.deploy();
        } catch (Exception e) {
            System.err.println("Error while deploying YARN cluster: " + e.getMessage());
            e.printStackTrace(System.err);
            return 1;
        }
        //------------------ ClusterClient deployed, handle connection details
        String jobManagerAddress = yarnCluster.getJobManagerAddress().getAddress().getHostName() + ":"
                + yarnCluster.getJobManagerAddress().getPort();

        System.out.println("Flink JobManager is now running on " + jobManagerAddress);
        System.out.println("JobManager Web Interface: " + yarnCluster.getWebInterfaceURL());

        // file that we write into the conf/ dir containing the jobManager address and the dop.
        File yarnPropertiesFile = getYarnPropertiesLocation(yarnCluster.getFlinkConfiguration());

        Properties yarnProps = new Properties();
        yarnProps.setProperty(YARN_APPLICATION_ID_KEY, yarnCluster.getApplicationId().toString());
        if (yarnDescriptor.getTaskManagerSlots() != -1) {
            String parallelism = Integer
                    .toString(yarnDescriptor.getTaskManagerSlots() * yarnDescriptor.getTaskManagerCount());
            yarnProps.setProperty(YARN_PROPERTIES_PARALLELISM, parallelism);
        }
        // add dynamic properties
        if (yarnDescriptor.getDynamicPropertiesEncoded() != null) {
            yarnProps.setProperty(YARN_PROPERTIES_DYNAMIC_PROPERTIES_STRING,
                    yarnDescriptor.getDynamicPropertiesEncoded());
        }
        writeYarnProperties(yarnProps, yarnPropertiesFile);

        //------------------ ClusterClient running, let user control it ------------

        if (detachedMode) {
            // print info and quit:
            LOG.info("The Flink YARN client has been started in detached mode. In order to stop "
                    + "Flink on YARN, use the following command or a YARN web interface to stop it:\n"
                    + "yarn application -kill " + yarnCluster.getApplicationId() + System.lineSeparator()
                    + "Please also note that the temporary files of the YARN session in {} will not be removed.",
                    yarnDescriptor.getSessionFilesDir());
            yarnCluster.waitForClusterToBeReady();
            yarnCluster.disconnect();
        } else {
            runInteractiveCli(yarnCluster, acceptInteractiveInput);
        }
    }
    return 0;
}

From source file:com.liferay.blade.cli.command.CreateCommandTest.java

@Test
public void testCreateWorkspaceCommaDelimitedModulesDirGradleProject() throws Exception {
    File workspace = new File(_rootDir, "workspace");

    _makeWorkspace(workspace);//from  w ww. j  ava2s  . c  o m

    File gradleProperties = new File(workspace, "gradle.properties");

    Assert.assertTrue(gradleProperties.exists());

    String configLine = System.lineSeparator() + "liferay.workspace.modules.dir=modules,foo,bar";

    Files.write(gradleProperties.toPath(), configLine.getBytes(), StandardOpenOption.APPEND);

    String[] args = { "create", "-t", "rest", "--base", workspace.getAbsolutePath(), "resttest" };

    TestUtil.runBlade(workspace, _extensionsDir, args);

    String fooBar = workspace.getAbsolutePath() + "/modules,foo,bar";

    File fooBarDir = new File(fooBar);

    Assert.assertFalse("directory named '" + fooBarDir.getName() + "' should not exist, but it does.",
            fooBarDir.exists());
}

From source file:de.ist.clonto.Ontogui.java

private void runQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runQueryButtonActionPerformed
    List<String> lines = null;
    try {//from  ww  w  .  j  a v a  2  s  .c  o m
        lines = Files.readAllLines(queryPath);
    } catch (IOException ex) {
        Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex);
    }
    String queryString = "";
    for (String line : lines) {
        queryString += line + System.lineSeparator();
    }
    Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
    queryResultArea.setText("Starting query: " + queryPath.toFile().getName() + "\n");
    Thread t = new Thread(
            new QueryProcessor(query, new QueryAreaStream(queryResultArea), dataset, checkbox1.getState()));
    t.start();
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

public X509Certificate getCertFromString(String certificateHeader) {
    CertificateFactory certificateFactory;
    try {//  w w w.ja va 2s.co m
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        log.error("Exception while creating CertificateFactory", e);
        return null;
    }

    // nginx forwards the certificate in a header by replacing new lines with whitespaces
    // (2 or more). Also replace tabs, which nginx sometimes sends instead of whitespaces.
    String certificateContent = certificateHeader.replaceAll("\\s{2,}", System.lineSeparator())
            .replaceAll("\\t+", System.lineSeparator());
    if (certificateContent == null || certificateContent.length() < 10) {
        log.debug("No certificate content found");
        return null;
    }
    X509Certificate userCertificate;
    try {
        userCertificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certificateContent.getBytes("ISO-8859-11")));
    } catch (CertificateException | UnsupportedEncodingException e) {
        log.error("Exception while converting certificate extracted from header", e);
        return null;
    }
    log.debug("Certificate was extracted from the header");
    return userCertificate;
}