Example usage for java.io StringWriter flush

List of usage examples for java.io StringWriter flush

Introduction

In this page you can find the example usage for java.io StringWriter flush.

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:de.tu_dortmund.ub.data.dswarm.Transform.java

/**
 * configuration and processing of the task
 *
 * @param inputDataModelID//from  w w w  .  j a v a 2 s  .  co  m
 * @param projectIDs
 * @param outputDataModelID
 * @return
 */
private String executeTask(final String inputDataModelID, final Collection<String> projectIDs,
        final String outputDataModelID, final String serviceName, final String engineDswarmAPI,
        final Optional<Boolean> optionalDoIngestOnTheFly, final Optional<Boolean> optionalDoExportOnTheFly,
        final Optional<String> optionalExportMimeType, final Optional<String> optionalExportFileExtension)
        throws Exception {

    final JsonArray mappings = getMappingsFromProjects(projectIDs, serviceName, engineDswarmAPI);
    final JsonObject inputDataModel = getDataModel(inputDataModelID, serviceName, engineDswarmAPI);
    final JsonObject outputDataModel = getDataModel(outputDataModelID, serviceName, engineDswarmAPI);
    final Optional<JsonObject> optionalSkipFilter = getSkipFilter(serviceName, engineDswarmAPI);

    // erzeuge Task-JSON
    final String persistString = config.getProperty(TPUStatics.PERSIST_IN_DMP_IDENTIFIER);

    final boolean persist;

    if (persistString != null && !persistString.trim().isEmpty()) {

        persist = Boolean.valueOf(persistString);
    } else {

        // default is false
        persist = false;
    }

    final StringWriter stringWriter = new StringWriter();
    final JsonGenerator jp = Json.createGenerator(stringWriter);

    jp.writeStartObject();
    jp.write(DswarmBackendStatics.PERSIST_IDENTIFIER, persist);
    // default for now: true, i.e., no content will be returned
    jp.write(DswarmBackendStatics.DO_NOT_RETURN_DATA_IDENTIFIER, true);
    // default for now: true, i.e., if a schema is attached it will utilised (instead of being derived from the data resource)
    jp.write(DswarmBackendStatics.UTILISE_EXISTING_INPUT_IDENTIFIER, true);

    if (optionalDoIngestOnTheFly.isPresent()) {

        final Boolean doIngestOnTheFly = optionalDoIngestOnTheFly.get();

        if (doIngestOnTheFly) {

            LOG.info(String.format("[%s][%d] do ingest on-the-fly", serviceName, cnt));
        }

        jp.write(DswarmBackendStatics.DO_INGEST_ON_THE_FLY, doIngestOnTheFly);
    }

    if (optionalDoExportOnTheFly.isPresent()) {

        final Boolean doExportOnTheFly = optionalDoExportOnTheFly.get();

        if (doExportOnTheFly) {

            LOG.info(String.format("[%s][%d] do export on-the-fly", serviceName, cnt));
        }

        jp.write(DswarmBackendStatics.DO_EXPORT_ON_THE_FLY, doExportOnTheFly);
    }

    jp.write(DswarmBackendStatics.DO_VERSIONING_ON_RESULT_IDENTIFIER, false);

    // task
    jp.writeStartObject(DswarmBackendStatics.TASK_IDENTIFIER);
    jp.write(DswarmBackendStatics.NAME_IDENTIFIER, "Task Batch-Prozess 'CrossRef'");
    jp.write(DswarmBackendStatics.DESCRIPTION_IDENTIFIER,
            "Task Batch-Prozess 'CrossRef' zum InputDataModel 'inputDataModelID '");

    // job
    jp.writeStartObject(DswarmBackendStatics.JOB_IDENTIFIER);
    jp.write(DswarmBackendStatics.UUID_IDENTIFIER, UUID.randomUUID().toString());
    jp.write(DswarmBackendStatics.MAPPINGS_IDENTIFIER, mappings);

    if (optionalSkipFilter.isPresent()) {

        jp.write(DswarmBackendStatics.SKIP_FILTER_IDENTIFIER, optionalSkipFilter.get());
    }

    jp.writeEnd();

    jp.write(DswarmBackendStatics.INPUT_DATA_MODEL_IDENTIFIER, inputDataModel);
    jp.write(DswarmBackendStatics.OUTPUT_DATA_MODEL_IDENTIFIER, outputDataModel);

    // end task
    jp.writeEnd();

    // end request
    jp.writeEnd();

    jp.flush();
    jp.close();

    final String task = stringWriter.toString();
    stringWriter.flush();
    stringWriter.close();

    LOG.debug(String.format("[%s][%d] task : %s", serviceName, cnt, task));

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        // POST /dmp/tasks/
        final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.TASKS_ENDPOINT);
        final StringEntity stringEntity = new StringEntity(task, ContentType.APPLICATION_JSON);
        stringEntity.setChunked(true);

        final String mimetype;

        if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) {

            if (optionalExportMimeType.isPresent()) {

                mimetype = optionalExportMimeType.get();
            } else {

                // default export mime type is XML
                mimetype = APIStatics.APPLICATION_XML_MIMETYPE;
            }
        } else {

            mimetype = APIStatics.APPLICATION_JSON_MIMETYPE;
        }

        httpPost.setHeader(HttpHeaders.ACCEPT, mimetype);
        //httpPost.setHeader(HttpHeaders.TRANSFER_ENCODING, CHUNKED_TRANSFER_ENCODING);

        httpPost.setEntity(stringEntity);

        final Header[] requestHeaders = httpPost.getAllHeaders();

        final String printedRequestHeaders = printHeaders(requestHeaders);

        LOG.info(String.format("[%s][%d] request : %s :: request headers : \n'%s' :: body : '%s'", serviceName,
                cnt, httpPost.getRequestLine(), printedRequestHeaders, stringEntity));

        try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) {

            final Header[] responseHeaders = httpResponse.getAllHeaders();

            final String printedResponseHeaders = printHeaders(responseHeaders);

            LOG.info(String.format("[%s][%d]  response headers : \n'%s'", serviceName, cnt,
                    printedResponseHeaders));

            final int statusCode = httpResponse.getStatusLine().getStatusCode();

            switch (statusCode) {

            case 204: {

                LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                        httpResponse.getStatusLine().getReasonPhrase()));

                EntityUtils.consume(httpResponse.getEntity());

                return "success";
            }
            case 200: {

                if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) {

                    LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                            httpResponse.getStatusLine().getReasonPhrase()));

                    final String exportFileExtension;

                    if (optionalExportFileExtension.isPresent()) {

                        exportFileExtension = optionalExportFileExtension.get();
                    } else {

                        // XML as default file ending
                        exportFileExtension = TaskProcessingUnit.XML_FILE_ENDING;
                    }

                    // write result to file
                    final String fileName = TPUUtil.writeResultToFile(httpResponse, config,
                            outputDataModelID + "-" + inputDataModelID + "-" + cnt, exportFileExtension);

                    return "success - exported XML to '" + fileName + "'";
                }
            }
            default: {

                LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                        httpResponse.getStatusLine().getReasonPhrase()));

                final String response = TPUUtil.getResponseMessage(httpResponse);

                throw new Exception("something went wrong at task execution" + response);
            }
            }
        }
    }
}

From source file:com.aurel.track.admin.user.person.PersonBL.java

/**
 * The following method sends a mail to person using mail template.
 * The mail contains: the login name and URL where the client must
 * set a password.//from w  w  w. ja v  a  2  s .  c  om
 * @param personBean
 * @return
 */
public static boolean sendEmailToNewlyCreatedClientUser(TPersonBean personBean) {
    boolean emailSent = false;
    StringWriter w = new StringWriter();
    Template template = null;
    Map<String, String> root = new HashMap<String, String>();
    TMailTemplateDefBean mailTemplateDefBean = MailTemplateBL
            .getSystemMailTemplateDefBean(IEventSubscriber.EVENT_POST_USER_CREATED_BY_EMAIL, personBean);
    String subject;

    if (mailTemplateDefBean != null) {
        String templateStr = mailTemplateDefBean.getMailBody();
        subject = mailTemplateDefBean.getMailSubject();
        try {
            template = new Template("name", new StringReader(templateStr), new Configuration());
        } catch (IOException e) {
            LOGGER.debug("Loading the template ClientCreatedByEmail.xml failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } else {
        LOGGER.error("Can't get mail template ClientCreatedByEmail.xml!");
        return false;
    }

    if (template == null) {
        LOGGER.error(
                "No valid template found for client user created after sent mail. The dafault: ClientCreatedByEmail.xml");
        return false;
    }
    TSiteBean siteBean = ApplicationBean.getInstance().getSiteBean();
    //The path starts with a "/" character but does not end with a "/"
    String contextPath = ApplicationBean.getInstance().getServletContext().getContextPath();
    String siteURL = siteBean.getServerURL();
    if (siteURL == null) {
        siteURL = "";
    } else if (siteURL.endsWith("/")) {
        siteURL = siteURL.substring(0, siteURL.lastIndexOf("/"));
    }
    Date texpDate = new Date(new Date().getTime() + 8 * 3600 * 1000); // The URL is valid 4 hours for setting the mail.
    personBean.setTokenExpDate(texpDate);
    String tokenPasswd = DigestUtils.md5Hex(Long.toString(texpDate.getTime()));
    personBean.setForgotPasswordKey(tokenPasswd);
    ApplicationBean appBean = ApplicationBean.getInstance();
    if (!appBean.getSiteBean().getIsDemoSiteBool() || personBean.getIsSysAdmin()) {
        PersonBL.saveSimple(personBean);
    }
    String confirmURL = siteURL + contextPath + "/resetPassword!confirm.action?ctk="
            + personBean.getForgotPasswordKey();
    root.put("loginname", personBean.getUsername());
    root.put("firstname", personBean.getFirstName());
    root.put("lastname", personBean.getLastName());
    root.put("confirmUrl", confirmURL);

    try {
        template.process(root, w);
    } catch (Exception e) {
        LOGGER.error("Processing create client user from sent mail  " + template.getName() + " failed with "
                + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    w.flush();
    String messageBody = w.toString();

    try {
        // Send mail to newly created client user
        MailSender ms = new MailSender(
                new InternetAddress(siteBean.getTrackEmail(), siteBean.getEmailPersonalName()),
                new InternetAddress(personBean.getEmail(), personBean.getFullName()), subject, messageBody,
                mailTemplateDefBean.isPlainEmail());
        emailSent = ms.send(); // wait for sending email
        LOGGER.debug("emailSend: " + emailSent);
        EventPublisher evp = EventPublisher.getInstance();
        if (evp != null) {
            List<Integer> events = new LinkedList<Integer>();
            events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_USER_CREATED_BY_EMAIL));
            evp.notify(events, personBean);
        }
    } catch (Exception t) {
        LOGGER.error("SendMail newly created client user failed from sent mail: ", t);
    }
    return emailSent;
}

From source file:com.eyeq.pivot4j.ui.html.HtmlRenderer.java

/**
 * @param context//from   w  w w.  java 2s  .  co m
 * @return
 */
protected Map<String, String> getCellAttributes(RenderContext context) {
    String styleClass = null;

    StringWriter writer = new StringWriter();
    CssWriter cssWriter = new CssWriter(writer);

    switch (context.getCellType()) {
    case Header:
        if (context.getAxis() == Axis.COLUMNS) {
            styleClass = columnHeaderStyleClass;
        } else {
            styleClass = rowHeaderStyleClass;

            if (rowHeaderLevelPadding > 0) {
                int padding = rowHeaderLevelPadding * (1 + context.getMember().getDepth());
                cssWriter.writeStyle("padding-left", padding + "px");
            }
        }
        break;
    case Title:
    case Aggregation:
        if (context.getAxis() == Axis.COLUMNS) {
            styleClass = columnTitleStyleClass;
        } else if (context.getAxis() == Axis.ROWS) {
            styleClass = rowTitleStyleClass;
        }
        break;
    case Value:
        styleClass = cellStyleClass;
        break;
    case None:
        styleClass = cornerStyleClass;
        break;
    default:
        assert false;
    }

    Map<String, String> attributes = new TreeMap<String, String>();

    PropertySupport properties = getProperties(context);

    if (properties != null) {
        cssWriter.writeStyle("color", getPropertyValue("fgColor", properties, context));

        String bgColor = getPropertyValue("bgColor", properties, context);
        if (bgColor != null) {
            cssWriter.writeStyle("background-color", bgColor);
            cssWriter.writeStyle("background-image", "none");
        }

        cssWriter.writeStyle("font-family", getPropertyValue("fontFamily", properties, context));
        cssWriter.writeStyle("font-size", getPropertyValue("fontSize", properties, context));

        String fontStyle = getPropertyValue("fontStyle", properties, context);
        if (fontStyle != null) {
            if (fontStyle.contains("bold")) {
                cssWriter.writeStyle("font-weight", "bold");
            }

            if (fontStyle.contains("italic")) {
                cssWriter.writeStyle("font-style", "oblique");
            }
        }

        String styleClassValue = getPropertyValue("styleClass", properties, context);

        if (styleClassValue != null) {
            if (styleClass == null) {
                styleClass = styleClassValue;
            } else {
                styleClass += " " + styleClassValue;
            }
        }
    }

    if (styleClass != null) {
        attributes.put("class", styleClass);
    }

    writer.flush();
    IOUtils.closeQuietly(writer);

    String style = writer.toString();

    if (StringUtils.isNotEmpty(style)) {
        attributes.put("style", style);
    }

    if (context.getColumnSpan() > 1) {
        attributes.put("colspan", Integer.toString(context.getColumnSpan()));
    }

    if (context.getRowSpan() > 1) {
        attributes.put("rowspan", Integer.toString(context.getRowSpan()));
    }

    return attributes;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 *
 * @param context//from   www. j ava 2 s.  c om
 * @param templateBuffer
 */
protected File createProcessedLaTeXFile(Map<String, Object> context, StringBuilder templateBuffer,
        String fileName) {
    Template freemarkerTemplate = null;
    File latexFile = new File(latexTmpDir + File.separator + fileName);

    StringWriter texWriter = new StringWriter();
    StringBuffer debugMessages = new StringBuffer();
    try {
        debugMessages.append("Creating Freemarker template..." + CRLF);
        Configuration freemarkerConfig = new Configuration();
        freemarkerConfig.setTemplateExceptionHandler(new LaTeXFreemarkerExceptionHandler());
        freemarkerTemplate = new Template(fileName, new StringReader(templateBuffer.toString()),
                freemarkerConfig);
        debugMessages.append("Processing the Freemarker LaTeX template..." + CRLF);
        freemarkerTemplate.process(context, texWriter);
        debugMessages.append("Freemmarker LaTeX template processed." + CRLF);
    } catch (Exception e) {
        LOGGER.error("Problem processing template: " + CRLF + debugMessages.toString());
        String st = ExceptionUtils.getStackTrace(e);
        debugTrace.append(debugMessages.toString() + CRLF);
        debugTrace.append(e.getMessage());
        LOGGER.debug("Problem processing template:", e);
        texWriter = new StringWriter();
        String tb = templateBuffer.toString();
        tb.replace("\\end{document}", "Problem processing template: " + CRLF + CRLF + debugMessages.toString()
                + CRLF + CRLF + st + CRLF + CRLF + "\\end{document}");
        texWriter.append(templateBuffer.toString());
    }

    texWriter.append(CRLF + "% The following keys are available for the enclosing document itself:" + CRLF);

    for (String item : context.keySet()) {
        texWriter.append("% " + item + CRLF);
    }
    texWriter.append(CRLF + "% The following keys are available for the document sections:" + CRLF);
    if (!(context.get("meetingTopics") == null)
            && !((ArrayList<Map<String, Object>>) context.get("meetingTopics")).isEmpty()) {
        for (String item : ((ArrayList<Map<String, Object>>) context.get("meetingTopics")).get(0).keySet()) {
            texWriter.append("% meetingTopics." + item + CRLF);
        }
    } else if (!(context.get("items") == null)
            && !((ArrayList<Map<String, Object>>) context.get("items")).isEmpty()) {
        for (String item : ((ArrayList<Map<String, Object>>) context.get("items")).get(0).keySet()) {
            texWriter.append("% items." + item + CRLF);
        }
    }

    texWriter.flush();
    String processedTex = texWriter.toString();

    LOGGER.debug(processedTex);

    try {
        FileUtils.writeStringToFile(latexFile, processedTex.toString(), "UTF-8");
    } catch (Exception e) {
        LOGGER.error("Cannot write file :" + latexFile.getAbsolutePath());
    }
    return latexFile;
}

From source file:org.pivot4j.ui.html.HtmlRenderCallback.java

/**
 * @param context/*from w  ww. jav a  2s . c o m*/
 * @return
 */
protected Map<String, String> getCellAttributes(TableRenderContext context) {
    String styleClass = null;

    StringWriter writer = new StringWriter();
    CssWriter cssWriter = new CssWriter(writer);

    if (LABEL.equals(context.getCellType())) {
        if (context.getAxis() == Axis.COLUMNS) {
            styleClass = columnHeaderStyleClass;
        } else {
            styleClass = rowHeaderStyleClass;

            if (rowHeaderLevelPadding > 0 && context.getMember() != null) {
                int padding = rowHeaderLevelPadding * (1 + context.getMember().getDepth());
                cssWriter.writeStyle("padding-left", padding + "px");
            }
        }
    } else if (TITLE.equals(context.getCellType()) || AGG_VALUE.equals(context.getCellType())) {
        if (context.getAxis() == Axis.COLUMNS) {
            styleClass = columnTitleStyleClass;
        } else if (context.getAxis() == Axis.ROWS) {
            styleClass = rowTitleStyleClass;
        }
    } else if (VALUE.equals(context.getCellType())) {
        styleClass = cellStyleClass;
    } else if (FILL.equals(context.getCellType())) {
        styleClass = cornerStyleClass;
    }

    Map<String, String> attributes = new TreeMap<String, String>();

    String propertyCategory = context.getRenderPropertyCategory();

    RenderPropertyUtils propertyUtils = getRenderPropertyUtils();

    cssWriter.writeStyle("color", propertyUtils.getString("fgColor", propertyCategory, null));

    String bgColor = propertyUtils.getString("bgColor", propertyCategory, null);

    if (bgColor != null) {
        cssWriter.writeStyle("background-color", bgColor);
        cssWriter.writeStyle("background-image", "none");
    }

    cssWriter.writeStyle("font-family", propertyUtils.getString("fontFamily", propertyCategory, null));
    cssWriter.writeStyle("font-size", propertyUtils.getString("fontSize", propertyCategory, null));

    String fontStyle = propertyUtils.getString("fontStyle", propertyCategory, null);

    if (fontStyle != null) {
        if (fontStyle.contains("bold")) {
            cssWriter.writeStyle("font-weight", "bold");
        }

        if (fontStyle.contains("italic")) {
            cssWriter.writeStyle("font-style", "oblique");
        }
    }

    String styleClassValue = getRenderPropertyUtils().getString("styleClass",
            context.getRenderPropertyCategory(), null);

    if (styleClassValue != null) {
        if (styleClass == null) {
            styleClass = styleClassValue;
        } else {
            styleClass += " " + styleClassValue;
        }
    }

    if (styleClass != null) {
        attributes.put("class", styleClass);
    }

    writer.flush();
    IOUtils.closeQuietly(writer);

    String style = writer.toString();

    if (StringUtils.isNotEmpty(style)) {
        attributes.put("style", style);
    }

    if (context.getColumnSpan() > 1) {
        attributes.put("colspan", Integer.toString(context.getColumnSpan()));
    }

    if (context.getRowSpan() > 1) {
        attributes.put("rowspan", Integer.toString(context.getRowSpan()));
    }

    return attributes;
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasourceFactory.java

@Override
public String getExtraStatus(boolean html) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    if (html) {/*from   w w  w  .  j a  v a2  s  .c  o m*/
        if (datasources.size() > 0) {
            pw.println("<h4><font color='#00cc00'>NodeCentric Datasources:</font></h4>");
            for (NodeCentricDatasource ds : datasources.values()) {
                try {
                    pw.println("<li>" + URLDecoder.decode(ds.getName(), "UTF-8") + "</li>");
                } catch (UnsupportedEncodingException e) {
                    log.error(LogUtils.INTERNAL_MARKER,
                            "Should never happen since UTF-8 must be supported by all JVMs on all platforms.",
                            e);
                }
                pw.println("<br/>Configuration Properties: ");
                pw.println("<table border='1'>");
                for (Enumeration<? extends Object> keys = ds.getConfigurationParameters().keys(); keys
                        .hasMoreElements();) {
                    Object key = keys.nextElement();
                    Object value = ds.getConfigurationParameters().get(key);
                    if (key.toString().toLowerCase().contains("password")
                            && value.toString().startsWith("encrypted:")) {
                        value = "********";
                    }
                    pw.println("<tr><td>" + key.toString() + "</td><td>" + value.toString() + "</td></tr>");
                }
                pw.println("</table>");
            }
        }
        if (initializingDatasource.size() > 0) {
            pw.println("<h4><font color='#FFFF00'>NodeCentric Datasources Starting:</font></h4>");
            for (Map.Entry<String, Dictionary<? extends Object, ? extends Object>> entry : initializingDatasource
                    .entrySet()) {
                pw.println("<li>" + entry.getKey() + "</li>");
                pw.println("<br/>Configuration Properties: ");
                pw.println("<table border='1'>");
                for (Enumeration<? extends Object> keys = entry.getValue().keys(); keys.hasMoreElements();) {
                    Object key = keys.nextElement();
                    Object value = entry.getValue().get(key);
                    pw.println("<tr><td>" + key.toString() + "</td><td>" + value.toString() + "</td></tr>");
                }
                pw.println("</table>");
            }

        }
    } else {
        if (datasources.size() > 0) {
            pw.println("NodeCentric Datasources:");
            for (NodeCentricDatasource ds : datasources.values()) {
                try {
                    pw.println(URLDecoder.decode(ds.getName(), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    log.error(LogUtils.INTERNAL_MARKER,
                            "Should never happen since UTF-8 must be supported by all JVMs on all platforms.",
                            e);
                }
            }
        }
        if (initializingDatasource.size() > 0) {
            pw.println("NodeCentric Datasources Starting:");
            for (Map.Entry<String, Dictionary<? extends Object, ? extends Object>> entry : initializingDatasource
                    .entrySet()) {
                pw.println(entry.getKey());
            }
        }
    }
    pw.flush();
    sw.flush();
    return sw.toString();
}

From source file:nl.minbzk.dwr.zoeken.enricher.processor.TikaProcessor.java

/**
 * Do the actual content processing./* w  w w.j ava  2s .  co m*/
 * 
 * @param envelope
 * @param settings
 * @param job
 * @param context
 * @return ProcessorResult
 * @throws Exception
 */
@Override
public ProcessorResult process(final ImportEnvelope envelope, final EnricherSettings settings,
        final EnricherJob job, final ProcessorContext context) throws Exception {
    String inputUri = envelope.getUri();
    String envelopeEncoding = envelope.getFields().get(settings.getEncodingMatch()) != null
            ? envelope.getFields().get(settings.getEncodingMatch()).get(0)
            : null;

    // Output just the usage information if so requested

    if (inputUri == null) {
        if (logger.isInfoEnabled())
            logger.info("Given import envelope contains no content URI and thus no content - only metadata");
    } else {
        if (logger.isDebugEnabled())
            logger.debug("Given import envelope content URI is " + inputUri);
    }

    // Handle the input content

    StringWriter output = new StringWriter();
    Metadata metadata = new Metadata();
    MediaType mediaType = null;

    // Add the reference for optimal detection

    if (job.getTikaResourceKeyPriority() != null && job.getTikaResourceKeyPriority().size() > 0)
        for (String resourceKey : job.getTikaResourceKeyPriority())
            if (envelope.getFields().containsKey(resourceKey)) {
                String resourceValue = envelope.getFields().get(resourceKey).get(0);

                if (logger.isInfoEnabled())
                    logger.info(format("Setting Tika resource to key '%s' with value '%s'", resourceKey,
                            resourceValue));

                metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, resourceValue);

                break;
            }

    if (metadata.get(TikaMetadataKeys.RESOURCE_NAME_KEY) == null)
        metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, envelope.getReference());

    // Determine whether to read from standard input, a file or a URL

    if (inputUri != null) {
        File inputFile = new File(inputUri);

        InputStream inputStream = readInputUri(inputUri, inputFile);

        // Pre-process the input if necessary

        try {
            mediaType = parser.getDetector().detect(inputStream, metadata);

            if (logger.isDebugEnabled())
                logger.debug("Parser detected " + mediaType.getType() + " / " + mediaType.getSubtype());

            // Detect the input encoding and introduce any optional encoding hints

            Charset inputEncoding = introduceEncodingHints(inputStream, metadata, envelopeEncoding,
                    envelope.getReferenceEncoding(),
                    job.getLanguageDetectionParameter() != null
                            ? envelope.getSingleValue(job.getLanguageDetectionParameter())
                            : null,
                    mediaType, job);

            // Pre-process the input stream, if needed

            for (Map.Entry<String, List<PreProcessor>> preprocessorsEntry : preprocessors.entrySet())
                if (mediaType.getSubtype().contains(preprocessorsEntry.getKey()))
                    for (PreProcessor preprocessor : preprocessorsEntry.getValue()) {
                        inputStream = preprocessor.process(inputStream, inputEncoding.toString(), envelope,
                                settings, job);

                        // Following the pre-processor contract, the stream encoding should have been transferred to UTF-8

                        inputEncoding = Charset.forName("UTF-8");
                        metadata.set(HttpHeaders.CONTENT_TYPE, mediaType.toString() + "; charset=UTF-8");
                    }

            parser.parse(inputStream, new BodyContentHandler(output), metadata, parseContext);
        } finally {
            inputStream.close();

            // Delete the file if requested to

            if (inputFile.isFile() && envelope.isDeleteOriginal())
                inputFile.delete();
        }

        output.flush();
    }

    String outputContent = output.toString().trim();

    // Handle the result

    Map<String, List<String>> metadataResult = new LinkedHashMap<String, List<String>>();
    List<ProcessorContent> contentResult = new ArrayList<ProcessorContent>();

    for (String name : metadata.names())
        if (!METADATA_IGNORE.contains(name)) {
            List<String> values = new Vector<String>();

            values.add(metadata.get(name));

            metadataResult.put(name, values);
        }

    contentResult.addAll(applyWordBreaking(envelope.getReference(), outputContent, settings.getWordBreakMin(),
            settings.getWordBreakMax()));

    // Only take the first language, should multiple ones be present

    String detectedLanguage = null;

    if (job.getLanguageDetectionParameter() != null) {
        if (!StringUtils.isEmpty(metadata.get(HttpHeaders.CONTENT_LANGUAGE)))
            detectedLanguage = metadata.get(HttpHeaders.CONTENT_LANGUAGE).split(",")[0].trim().split("-")[0]
                    .trim();
        else {
            // Use an n-gram language profiler to detect the effective language, if it was not given or could be detected otherwise

            String categorizerLanguage = categorizeCybozu(settings, job, outputContent);

            if (!categorizerLanguage.equals("unknown"))
                metadata.set(HttpHeaders.CONTENT_LANGUAGE, (detectedLanguage = categorizerLanguage));
            else
                logger.warn(
                        "The language could not be detected using n-gram detection; leaving language detection empty");
        }
    }

    // Perform entity extraction using UIMA, if applicable

    if (job.getEntityDetectionDescriptors() != null) {
        // We can only do this if we know the language

        if (detectedLanguage != null) {
            // And if the language is supported

            if (job.getEntityDetectionLanguages() != null && job.getEntityDetectionLanguages().size() > 0
                    && !job.getEntityDetectionLanguages().contains(detectedLanguage))
                logger.warn(
                        "Not performing UIMA processing as the document language is not covered by the UIMA detectors");
            else
                try {
                    performInjection(job, context, contentResult, detectedLanguage, mediaType);
                } catch (AnalysisEngineProcessException e) {
                    logger.error("Could not inject UIMA metadata due to an analysis engine process exception",
                            e);
                }
        } else
            logger.warn("Not performing UIMA processing as no language was provided or detected");
    }

    String actualMediaType = "text/plain";

    if (mediaType != null)
        actualMediaType = mediaType.getType() + "/" + mediaType.getSubtype();

    return new ProcessorResult(metadataResult, contentResult, actualMediaType, detectedLanguage);
}

From source file:com.aimluck.eip.schedule.util.ScheduleUtils.java

/**
 * ???????//from ww w  .  j  a v  a  2s.  co  m
 *
 * @return
 */
public static String createReminderMsgForCellPhone(EipTSchedule schedule, List<ALEipUser> memberList,
        int destUserID) {
    String date_detail = "";
    try {
        date_detail = getMsgDate(schedule);
    } catch (Exception e) {
        return "";
    }

    StringWriter out = null;
    try {
        VelocityService service = (VelocityService) ((TurbineServices) TurbineServices.getInstance())
                .getService(VelocityService.SERVICE_NAME);
        Context context = service.getContext();

        context.put("titleValue", schedule.getName().toString());
        context.put("dateValue", date_detail);

        if (memberList != null) {
            int size = memberList.size();
            int i;
            StringBuffer body = new StringBuffer("");
            for (i = 0; i < size; i++) {
                if (i != 0) {
                    body.append(", ");
                }
                ALEipUser member = memberList.get(i);
                body.append(member.getAliasName());
            }
            context.put("menbersList", body.toString());
        }

        ALEipUser destUser;
        try {
            destUser = ALEipUtils.getALEipUser(destUserID);
        } catch (ALDBErrorException ex) {
            logger.error("schedule", ex);
            return "";
        }

        context.put("Alias", ALOrgUtilsService.getAlias());

        context.put("globalUrl1",
                ALMailUtils.getGlobalurl() + "?key=" + ALCellularUtils.getCellularKey(destUser));

        out = new StringWriter();
        service.handleRequest(context, "mail/scheduleReminder.vm", out);
        out.flush();
        return out.toString();
    } catch (IllegalArgumentException e) {

    } catch (RuntimeException e) {
        String message = e.getMessage();
        logger.warn(message, e);
        e.printStackTrace();
    } catch (Exception e) {
        String message = e.getMessage();
        logger.warn(message, e);
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return null;
}

From source file:com.aimluck.eip.schedule.util.ScheduleUtils.java

/**
 * ??????/*w w w . ja v a  2s  .c o  m*/
 *
 * @return
 */
public static String createReminderMsgForPc(EipTSchedule schedule, List<ALEipUser> memberList) {
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);

    String date_detail = "";

    try {

        date_detail = getMsgDate(schedule);
    } catch (Exception e) {
        return "";
    }

    StringWriter out = null;
    try {
        VelocityService service = (VelocityService) ((TurbineServices) TurbineServices.getInstance())
                .getService(VelocityService.SERVICE_NAME);
        Context context = service.getContext();

        context.put("titleValue", schedule.getName().toString());
        context.put("dateValue", date_detail);

        if (schedule.getPlace().toString().length() > 0) {
            context.put("placeValue", schedule.getPlace().toString());
        }

        if (schedule.getNote().toString().length() > 0) {
            context.put("noteValue", schedule.getNote().toString());
        }

        if (memberList != null) {
            int size = memberList.size();
            int i;
            StringBuffer body = new StringBuffer("");
            for (i = 0; i < size; i++) {
                if (i != 0) {
                    body.append(", ");
                }
                ALEipUser member = memberList.get(i);
                body.append(member.getAliasName());
            }
            context.put("menbersList", body.toString());
        }

        context.put("Alias", ALOrgUtilsService.getAlias());

        if (enableAsp) {
            context.put("globalUrl1", ALMailUtils.getGlobalurl());
        } else {
            context.put("globalurl2", ALMailUtils.getGlobalurl());
            context.put("globalUrl3", ALMailUtils.getLocalurl());
        }

        out = new StringWriter();
        service.handleRequest(context, "mail/scheduleReminder.vm", out);
        out.flush();
        return out.toString();
    } catch (IllegalArgumentException e) {

    } catch (Exception e) {
        String message = e.getMessage();
        logger.warn(message, e);
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return null;
}

From source file:com.aimluck.eip.schedule.util.ScheduleUtils.java

public static String createReminderMsgForMessage(EipTSchedule schedule, List<ALEipUser> memberList) {
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);

    String date_detail = "";

    try {/*  w w w .ja  va 2s.c o  m*/

        date_detail = getMsgDate(schedule);
    } catch (Exception e) {
        return "";
    }

    StringWriter out = null;
    try {
        VelocityService service = (VelocityService) ((TurbineServices) TurbineServices.getInstance())
                .getService(VelocityService.SERVICE_NAME);
        Context context = service.getContext();

        context.put("titleValue", schedule.getName().toString());
        context.put("dateValue", date_detail);

        if (schedule.getPlace().toString().length() > 0) {
            context.put("placeValue", schedule.getPlace().toString());
        }

        if (schedule.getNote().toString().length() > 0) {
            context.put("noteValue", schedule.getNote().toString());
        }

        if (memberList != null) {
            int size = memberList.size();
            int i;
            StringBuffer body = new StringBuffer("");
            for (i = 0; i < size; i++) {
                if (i != 0) {
                    body.append(", ");
                }
                ALEipUser member = memberList.get(i);
                body.append(member.getAliasName());
            }
            context.put("menbersList", body.toString());
        }

        context.put("Alias", ALOrgUtilsService.getAlias());

        if (enableAsp) {
            context.put("globalUrl1", ALMailUtils.getGlobalurl());
        } else {
            context.put("globalurl2", ALMailUtils.getGlobalurl());
            context.put("globalUrl3", ALMailUtils.getLocalurl());
        }

        out = new StringWriter();
        service.handleRequest(context, "mail/scheduleReminderMessage.vm", out);
        out.flush();
        return out.toString();
    } catch (IllegalArgumentException e) {

    } catch (Exception e) {
        String message = e.getMessage();
        logger.warn(message, e);
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return null;

}