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:adams.data.image.ImageMetaDataHelper.java

/**
 * Reads the meta-data from the file (Commons Imaging).
 *
 * @param file   the file to read the meta-data from
 * @return      the meta-data/*from  w ww  .j  a  va2 s. c o m*/
 * @throws Exception   if failed to read meta-data
 */
public static SpreadSheet commons(File file) throws Exception {
    SpreadSheet sheet;
    Row row;
    org.apache.commons.imaging.common.ImageMetadata meta;
    String[] parts;
    String key;
    String value;
    org.apache.commons.imaging.ImageInfo info;
    String infoStr;
    String[] lines;
    HashSet<String> keys;

    sheet = new DefaultSpreadSheet();

    // header
    row = sheet.getHeaderRow();
    row.addCell("K").setContent("Key");
    row.addCell("V").setContent("Value");

    keys = new HashSet<String>();

    // meta-data
    meta = Imaging.getMetadata(file.getAbsoluteFile());
    if (meta != null) {
        for (Object item : meta.getItems()) {
            key = null;
            value = null;
            if (item instanceof ImageMetadata.Item) {
                key = ((ImageMetadata.Item) item).getKeyword().trim();
                value = ((ImageMetadata.Item) item).getText().trim();
            } else {
                parts = item.toString().split(": ");
                if (parts.length == 2) {
                    key = parts[0].trim();
                    value = parts[1].trim();
                }
            }
            if (key != null) {
                if (!keys.contains(key)) {
                    keys.add(key);
                    row = sheet.addRow();
                    row.addCell("K").setContent(key);
                    row.addCell("V").setContent(fixDateTime(Utils.unquote(value)));
                }
            }
        }
    }

    // image info
    info = Imaging.getImageInfo(file.getAbsoluteFile());
    if (info != null) {
        infoStr = info.toString();
        lines = infoStr.split(System.lineSeparator());
        for (String line : lines) {
            parts = line.split(": ");
            if (parts.length == 2) {
                key = parts[0].trim();
                value = parts[1].trim();
                if (!keys.contains(key)) {
                    row = sheet.addRow();
                    row.addCell("K").setContent(key);
                    row.addCell("V").setContent(Utils.unquote(value));
                    keys.add(key);
                }
            }
        }
    }

    return sheet;
}

From source file:com.rapidminer.gui.flow.processrendering.annotations.AnnotationDrawUtils.java

/**
 * Returns plain text from the editor.//from www .j av a2  s  .  co  m
 *
 * @param editor
 *            the editor from which to take the text.
 * @param onlySelected
 *            if {@code true} will only return the selected text
 * @return the text of the editor converted to plain text
 * @throws BadLocationException
 * @throws IOException
 */
public static String getPlaintextFromEditor(final JEditorPane editor, final boolean onlySelected)
        throws IOException, BadLocationException {
    if (editor == null) {
        throw new IllegalArgumentException("editor must not be null!");
    }
    HTMLDocument document = (HTMLDocument) editor.getDocument();
    StringWriter writer = new StringWriter();
    int start = 0;
    int length = document.getLength();
    if (onlySelected) {
        start = editor.getSelectionStart();
        length = editor.getSelectionEnd() - start;
    }
    editor.getEditorKit().write(writer, document, start, length);
    String text = writer.toString();
    text = AnnotationDrawUtils.removeStyleFromComment(text);
    // switch <br> and <br/> to actual newline (current system)
    text = text.replaceAll("<br.*?>", System.lineSeparator());
    // kill all other html tags
    text = text.replaceAll("\\<.*?>", "");
    text = StringEscapeUtils.unescapeHtml(text);
    return text;
}

From source file:com.stratio.crossdata.sh.Shell.java

/**
 * Print a message on the console.//from w  w  w .  j ava  2s  .c  o  m
 *
 * @param msg The message.
 */
public void println(String msg) {
    try {
        console.getOutput().write(msg + System.lineSeparator());
    } catch (IOException e) {
        LOG.error("Cannot print to console.", e);
    }
}

From source file:de.tu_dortmund.ub.hb_ng.middleware.MiddlewareHbNgEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    // CORS ORIGIN RESPONSE HEADER
    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER));

    String authorization = "";
    String contenttype = "";

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }/* w w  w. j  a v a2 s .  c  o m*/
        if (headerNameKey.equals("Content-Type")) {
            contenttype = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.info("contenttype = " + contenttype);

    try {

        // TODO validate Content-Type

        String data = httpServletRequest.getReader().lines()
                .collect(Collectors.joining(System.lineSeparator()));

        if (data == null || data.equals("")) {

            this.logger.error(HttpServletResponse.SC_NO_CONTENT + " - No Content");
            httpServletResponse.sendError(HttpServletResponse.SC_NO_CONTENT, "No Content");
        } else {

            String postableData = null;

            // TODO bind interface Preprocessing
            if (Lookup.lookupAll(PreprocessingInterface.class).size() > 0) {

                PreprocessingInterface preprocessingInterface = Lookup.lookup(PreprocessingInterface.class);
                // init Authorization Service
                preprocessingInterface.init(this.config);

                postableData = preprocessingInterface.process(data);
            } else {

                // TODO correct error handling
                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }

            if (postableData != null) {

                // TODO if successful then POST as application/sparql-update to LinkedDataPlatform
                String sparql_url = this.config.getProperty("ldp.sparql-endpoint");

                // HTTP Request
                int timeout = Integer.parseInt(this.config.getProperty("ldp.timeout"));

                RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                        .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

                CloseableHttpClient httpclient = HttpClients.custom()
                        .setDefaultRequestConfig(defaultRequestConfig).build();

                try {

                    HttpPost httpPost = new HttpPost(sparql_url);
                    httpPost.addHeader("Content-Type", "application/sparql-update");
                    httpPost.addHeader("Authorization", this.config.getProperty("ldp.authorization"));
                    httpPost.setEntity(new StringEntity(postableData));

                    CloseableHttpResponse httpResponse = null;

                    long start = System.nanoTime();
                    try {

                        httpResponse = httpclient.execute(httpPost);
                    } catch (ConnectTimeoutException | SocketTimeoutException e) {

                        this.logger.info("[" + this.getClass().getName() + "] " + e.getClass().getName() + ": "
                                + e.getMessage());
                        httpResponse = httpclient.execute(httpPost);
                    }
                    long elapsed = System.nanoTime() - start;
                    this.logger.info("[" + this.getClass().getName() + "] LDP request - "
                            + (elapsed / 1000.0 / 1000.0 / 1000.0) + " s");

                    try {

                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        HttpEntity httpEntity = httpResponse.getEntity();

                        // TODO
                        httpServletResponse.setStatus(statusCode);
                        httpServletResponse.getWriter().println(httpResponse.getStatusLine().getReasonPhrase());

                        EntityUtils.consume(httpEntity);

                    } finally {
                        httpResponse.close();
                    }
                } finally {

                    httpclient.close();
                }
            }
        }
    } catch (Exception e) {

        this.logger.error("something went wrong", e);
        httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "something went wrong");
    }
}

From source file:com.bc.fiduceo.ingest.IngestionTool.java

void printUsageTo(OutputStream outputStream) {
    final String ls = System.lineSeparator();
    final PrintWriter writer = new PrintWriter(outputStream);
    writer.write("ingestion-tool version " + VERSION_NUMBER);
    writer.write(ls + ls);/*from ww  w.  j av  a 2s  . co  m*/

    final HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.printHelp(writer, 120, "ingestion-tool <options>", "Valid options are:", getOptions(), 3, 3,
            "");

    writer.flush();
}

From source file:net.bitjump.launchme.utils.FileConfig.java

private String replace(String line, YamlConfiguration newFile, YamlConfiguration oldFile) {
    String resul = line;/*w  w w . j a v a2 s .c  om*/

    for (String value : newFile.getKeys(true)) {
        if (value.equals("version")) // Este parametro no se toca
        {
            continue;
        }

        String cValue = value;
        String spaces = ""; // Estilo

        if (value.contains(".")) {
            String[] vals = value.split("\\.");
            cValue = vals[vals.length - 1];

            int i = 0;
            while (i < StringUtils.countMatches(value, ".")) {
                spaces += "    "; // Style format
                i++;
            }
        }

        if (line.contains(cValue + ":")) {
            Object v = null;
            // Previous structure
            if (oldFile.contains(before + "." + cValue)) {
                v = oldFile.get(before + "." + cValue);
            } else if (newFile.contains(before + "." + cValue)) {
                v = newFile.get(before + "." + cValue);
                // New structure
            } else if (oldFile.contains(value)) {
                v = oldFile.get(value);
            } else {
                v = newFile.get(value);
            }

            resul = spaces + cValue + ":";

            if (v instanceof List) {
                List<Object> vs = (List<Object>) v;
                for (Object v1 : vs) {
                    String val = getFilteredString(v1.toString());
                    resul += System.lineSeparator() + spaces + "- " + val;
                }
            } else if (!(v instanceof MemorySection)) {
                resul += " " + getFilteredString(v.toString());
            } else if (v instanceof MemorySection) {
                before = value;
            }

            resul += System.lineSeparator();
            break;
        }
    }

    return (resul.equals(line) ? resul + System.lineSeparator() : resul);
}

From source file:net.di2e.ecdr.search.transform.atom.AtomTransformerWithPayload.java

/**
 * Method responsible for getting the metadata XML String that is associated
 * with the Metacard. The metadata is retrieved by calling the
 * MetadataTransformer that is registered with the id that matches the
 * format String that is passed into the method. If a MetacardTransformer
 * doesn't exist, or the result of the Transform is not XML, or if there is
 * an error while transforming, the Metacard.METADATA will be returned
 * //from w ww  .j a  v a  2s  .  c o m
 * @param metacard
 *            the Metacard to get the Metacard from
 * @param format
 *            the format of the MetacardTransformer to use (which is looked
 *            up by MetacardTransformer id)
 * @return the XML String
 */
protected String getMetadataXML(Metacard metacard, String format) {
    String metadata = null;
    LOGGER.debug(
            "Getting metadata to include in atom response in the format [{}] from metacardTransformerMap {}",
            format, metacardTransformerMap.keySet());
    if (StringUtils.isNotBlank(format)) {
        MetacardTransformer metacardTransformer = metacardTransformerMap.get(format);
        if (metacardTransformer != null) {
            try {
                LOGGER.debug(
                        "Calling the MetacardTransformer with id [{}] to transform the Metacard into XML Metadata",
                        format);
                BinaryContent binaryContent = metacardTransformer.transform(metacard, null);
                String mimeValue = binaryContent.getMimeTypeValue();
                if (StringUtils.isNotBlank(mimeValue) && mimeValue.contains("xml")) {
                    try (InputStream inputStream = binaryContent.getInputStream()) {
                        metadata = IOUtils.toString(inputStream);
                    } catch (IOException e) {
                        LOGGER.warn("Error while writing transformed Metacard into a String: " + e.getMessage(),
                                e);
                    }
                }
            } catch (CatalogTransformerException e) {
                LOGGER.warn("Error while transforming metacard using the [{}] MetacardTransformer", format);
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }
    if (metadata == null) {
        LOGGER.debug(
                "A MetacardTransform didn't exist for format [{}] or ran into problems when transforming Metacard, so falling back to using the Metadata in the Metacard",
                format);
        metadata = metacard.getMetadata();

    }
    LOGGER.trace("Atom Transformer setting Metacard.METADATA to:{}{}", System.lineSeparator(), metadata);
    return metadata;
}

From source file:ca.wumbo.doommanager.client.controller.ConsoleController.java

/**
 * Takes whatever is in the text field and submits it.
 *//*  www  . j  a  va  2s  .  c  o m*/
private void submitLineToConsole() {
    // Trim the string before using, also nulls shouldn't happen (but just in case).
    String text = textField.getText().trim().replace('\0', '?');

    // Ignore empty lines.
    if (text.isEmpty())
        return;

    // Remember what we submitted, most recent goes first.
    commandBuffer.add(text);

    // Reset due to submission of text.
    commandBufferIndex = commandBuffer.size();

    // Handle commands.
    switch (text.toLowerCase()) {
    case "clear":
        textArea.clear();
        break;

    case "connect": // Note: Debugging only.
        textArea.appendText("Starting connection to local host..." + System.lineSeparator());
        Optional<SelectionKey> key = clientSelector.openTCPConnection(
                new InetSocketAddress("localhost", Server.DEFAULT_LISTEN_PORT), new NetworkReceiver() {
                    @Override
                    public void signalConnectionTerminated() {
                        System.out.println("Test connection killed.");
                    }

                    @Override
                    public void receiveData(byte[] data) {
                        System.out.println("Got data: " + data.length + " = " + Arrays.toString(data));
                    }
                });
        if (key.isPresent()) {
            SelectionKey k = key.get();
            Platform.runLater(() -> {
                try {
                    Thread.sleep(2000);
                    clientSelector.writeData(k, new byte[] { 1, 2 });
                    System.out.println("Go forth...");
                } catch (Exception e) {
                    System.err.println("UGH");
                    e.printStackTrace();
                }
            });
        }
        textArea.appendText("Connection made = " + key.isPresent() + System.lineSeparator());
        break;

    case "copy":
        try {
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            StringSelection stringSelection = new StringSelection(textArea.getText());
            clipboard.setContents(stringSelection, stringSelection);
            textArea.appendText("Copied to clipboard." + System.lineSeparator());
        } catch (Exception e) {
            textArea.appendText("Error: Unable to get system clipboard." + System.lineSeparator());
        }
        break;

    case "exit":
        coreController.exit();
        break;

    case "getconnections":
        int numKeys = clientSelector.getNumConnections();
        textArea.appendText("There " + (numKeys != 1 ? "are " : "is ") + numKeys + " key"
                + (numKeys != 1 ? "s." : ".") + System.lineSeparator());
        break;

    case "help":
        textArea.appendText("Commands:" + System.lineSeparator());
        textArea.appendText("    clear - Clears the console" + System.lineSeparator());
        textArea.appendText("    copy - Copies all the content to your clipboard" + System.lineSeparator());
        textArea.appendText("    exit - Exits the program" + System.lineSeparator());
        textArea.appendText("    getconnections - Lists the connections available" + System.lineSeparator());
        textArea.appendText("    help - Shows this help" + System.lineSeparator());
        textArea.appendText("    history - Prints command history for " + MAX_COMMANDS_REMEMBERED + " entries"
                + System.lineSeparator());
        textArea.appendText("    memory - Get current memory statistics" + System.lineSeparator());
        textArea.appendText("    version - Gets the version information" + System.lineSeparator());
        break;

    case "history":
        if (commandBuffer.size() <= 1) {
            textArea.appendText("No history to display" + System.lineSeparator());
            break;
        }
        textArea.appendText("History:" + System.lineSeparator());
        for (int i = 0; i < commandBuffer.size() - 1; i++)
            textArea.appendText("    " + commandBuffer.get(i) + System.lineSeparator()); // Print everything but the last command (which was this).
        break;

    case "memory":
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(2);
        long totalMem = Runtime.getRuntime().totalMemory();
        long usedMem = totalMem - Runtime.getRuntime().freeMemory();
        long maxMem = Runtime.getRuntime().maxMemory();
        double megabyte = 1024.0 * 1024.0;
        textArea.appendText("Memory statistics:" + System.lineSeparator());
        textArea.appendText(
                "    Memory used: " + nf.format(Math.abs(((double) usedMem / (double) maxMem)) * 100.0) + "%"
                        + System.lineSeparator());
        textArea.appendText(
                "    " + nf.format(usedMem / megabyte) + " mb (used memory)" + System.lineSeparator());
        textArea.appendText(
                "    " + nf.format(maxMem / megabyte) + " mb (max memory)" + System.lineSeparator());
        break;

    // DEBUG
    case "startserver":
        if (Start.getParsedRuntimeArgs().isClientServer()) {
            if (!serverManager.isInitialized()) {
                try {
                    textArea.appendText("Starting server on port " + Server.DEFAULT_LISTEN_PORT + "."
                            + System.lineSeparator());
                    serverManager.initialize();
                } catch (Exception e) {
                    textArea.appendText("Unable to initialize server." + System.lineSeparator());
                    textArea.appendText("    " + e.getMessage() + System.lineSeparator());
                }
            }

            if (serverManager.isInitialized()) {
                if (!serverManager.isRunning()) {
                    textArea.appendText("Running server on port " + Server.DEFAULT_LISTEN_PORT + "."
                            + System.lineSeparator());
                    try {
                        new Thread(serverManager, "ClientConsoleServer").start();
                        textArea.appendText("Successfully set up server." + System.lineSeparator());
                    } catch (Exception e) {
                        textArea.appendText("Error setting up server:" + System.lineSeparator());
                        textArea.appendText("    " + e.getMessage() + System.lineSeparator());
                    }
                } else {
                    textArea.appendText("Server is already running." + System.lineSeparator());
                }
            } else {
                textArea.appendText("Server not initialized, cannot run." + System.lineSeparator());
            }
        }
        break;

    // DEBUG
    case "stopserver":
        if (Start.getParsedRuntimeArgs().isClientServer()) {
            if (serverManager.isInitialized() && serverManager.isRunning()) {
                serverManager.requestServerTermination();
                textArea.appendText("Requested server termination." + System.lineSeparator());
            } else {
                textArea.appendText(
                        "Cannot stop server, it has not been initialized or started." + System.lineSeparator());
            }
        }
        break;

    case "version":
        textArea.appendText(applicationTitle + " version: " + applicationVersion + System.lineSeparator());
        break;

    default:
        textArea.appendText("Unknown command: " + text + System.lineSeparator());
        textArea.appendText("Type 'help' for commands" + System.lineSeparator());
        break;
    }

    textField.clear();
}

From source file:com.sketchy.hardware.impl.RaspberryPIServoController.java

private synchronized static String buildServoCommand(int pinNumber, int value) {
    if (sbuf.length() > 0)
        sbuf.delete(0, sbuf.length() - 1);
    sbuf.append("s ").append(Integer.toString(pinNumber)).append(" ").append(Integer.toString(value))
            .append(System.lineSeparator());
    return sbuf.toString();
}

From source file:net.resheim.eclipse.timekeeper.ui.views.ExportToClipboard.java

private void append(LocalDate firstDayOfWeek, StringBuilder sb, Object object) {
    if (object instanceof String) {
        sb.append("<tr style=\"background: #eeeeee;\"><td>");
        sb.append(object);/* w ww.j a v a  2s  .  c om*/
        for (int i = 0; i < 7; i++) {
            sb.append("</td><td style=\"text-align: right; border-left: 1px solid #aaa\">");
            LocalDate weekday = firstDayOfWeek.plusDays(i);
            int seconds = getSum(provider.getFiltered(), weekday, (String) object);
            if (seconds > 60) {
                sb.append(DurationFormatUtils.formatDuration(seconds * 1000, "H:mm", true));
            }
        }
        sb.append("</td></tr>");
    }
    if (object instanceof WeeklySummary) {
        sb.append("<tr style=\"background: #dedede; border-top: 1px solid #aaa;\"><td>");
        sb.append("Daily total");
        for (int i = 0; i < 7; i++) {
            sb.append("</td><td style=\"text-align: right; border-left: 1px solid #aaa\">");
            LocalDate weekday = firstDayOfWeek.plusDays(i);
            int seconds = getSum(provider.getFiltered(), weekday);
            if (seconds > 60) {
                sb.append(DurationFormatUtils.formatDuration(seconds * 1000, "H:mm", true));
            }
        }
        sb.append("</td></tr>");
    }
    if (object instanceof ITask) {
        sb.append("<tr><td>&nbsp;&nbsp;");
        AbstractTask task = (AbstractTask) object;
        String taskKey = task.getTaskKey();
        if (taskKey != null) {
            sb.append("<a href=\"" + task.getUrl() + "\">");
            sb.append(taskKey);
            sb.append("</a>");
            sb.append(": ");
        }
        sb.append(task.getSummary());
        for (int i = 0; i < 7; i++) {
            sb.append("</td><td style=\"text-align: right; border-left: 1px solid #aaa\">");
            LocalDate weekday = firstDayOfWeek.plusDays(i);
            int seconds = Activator.getActiveTime(task, weekday);
            if (seconds > 60) {
                sb.append(DurationFormatUtils.formatDuration(seconds * 1000, "H:mm", true));
            }
        }
        sb.append("</td></tr>");
    }
    sb.append(System.lineSeparator());
    if (object instanceof String) {
        Object[] children = provider.getChildren(object);
        for (Object o : children) {
            append(firstDayOfWeek, sb, o);
        }
    }
}