Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

In this page you can find the example usage for java.io PrintWriter append.

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.LinuxdistroCommunity.android.client.PostEntry.java

/**
 * Fire the task to post the media entry. The media information is encoded
 * in Bundles. Each Bundle MUST contain the KEY_FILE_PATH pointing to the
 * resource. Bundles MAY contain KEY_TITLE and KEY_DESCRIPTION for passing
 * additional metadata./*from w  ww .  ja v  a2  s  .  com*/
 *
 */
@Override
protected JSONObject doInBackground(Bundle... mediaInfoBundles) {

    Bundle mediaInfo = mediaInfoBundles[0];
    HttpURLConnection connection = null;

    Uri.Builder uri_builder = Uri.parse(mServer + API_BASE + API_POST_ENTRY).buildUpon();
    uri_builder.appendQueryParameter(PARAM_ACCESS_TOKEN, mToken);

    String charset = "UTF-8";

    File binaryFile = new File(mediaInfo.getString(KEY_FILE_PATH));

    // Semi-random value to act as the boundary
    String boundary = Long.toHexString(System.currentTimeMillis());
    String CRLF = "\r\n"; // Line separator required by multipart/form-data.
    PrintWriter writer = null;

    try {
        URL url = new URL(uri_builder.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        OutputStream output = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

        // Send metadata
        if (mediaInfo.containsKey(KEY_TITLE)) {
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"title\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
            writer.append(CRLF);
            writer.append(mediaInfo.getString(KEY_TITLE)).append(CRLF).flush();
        }
        if (mediaInfo.containsKey(KEY_DESCRIPTION)) {
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"description\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
            writer.append(CRLF);
            writer.append(mediaInfo.getString(KEY_DESCRIPTION)).append(CRLF).flush();
        }

        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + binaryFile.getName() + "\"")
                .append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        InputStream input = null;
        try {
            input = new FileInputStream(binaryFile);
            byte[] buffer = new byte[1024];
            for (int length = 0; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
            output.flush(); // Important! Output cannot be closed. Close of
                            // writer will close output as well.
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException logOrIgnore) {
                }
        }
        writer.append(CRLF).flush(); // CRLF is important! It indicates end
                                     // of binary boundary.

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF);
        writer.close();

        // read the response
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(TAG, Integer.toString(serverResponseCode));
        Log.d(TAG, serverResponseMessage);

        InputStream is = connection.getInputStream();

        // parse token_response as JSON to get the token out
        String str_response = NetworkUtilities.readStreamToString(is);
        Log.d(TAG, str_response);
        JSONObject response = new JSONObject(str_response);

        return response;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // if (writer != null) writer.close();
    }

    return null;
}

From source file:org.apache.wicket.portlet.WicketPortlet.java

/**
 * Loops until wicket processing does not result in a redirect (redirects
 * have to be caught, and fed back into Wicket as we only want the portlet
 * redirected, not the entire page of course).
 * //from   w w  w. j  av a 2s.com
 * @param request
 * @param response
 * @param requestType
 * @param wicketURL
 * @param responseState
 * @throws PortletException
 * @throws IOException
 */
private void processMimeResponseRequest(String wicketURL, final PortletRequest request,
        final MimeResponse response, final ResponseState responseState) throws PortletException, IOException {
    PortletRequestDispatcher rd = null;
    String previousURL = null;
    // FIXME portal comment: explain while loop
    // keep looping until wicket processing does not result in a redirect
    // (redirects have to
    // be caught, and fed back into Wicket as we only want the portlet
    // redirected, not the
    // entire page of course.
    while (true) {
        rd = getPortletContext().getRequestDispatcher(wicketURL);
        if (rd != null) {
            // Need to use RequestDispatcher.include here otherwise
            // internally rewinding on a
            // redirect
            // won't be allowed (calling forward will close the response)
            rd.include(request, response);

            // process _other_ response states - check for redirects as a
            // result of wicket
            // processing the request

            String redirectLocation = responseState.getRedirectLocation();
            String ajaxRedirectLocation = responseState.getAjaxRedirectLocation();
            if (ajaxRedirectLocation != null) {
                // Ajax redirect
                ajaxRedirectLocation = fixWicketUrl(wicketURL, ajaxRedirectLocation);
                responseState.clear();
                responseState.setDateHeader("Date", System.currentTimeMillis());
                responseState.setDateHeader("Expires", 0);
                responseState.setHeader("Pragma", "no-cache");
                responseState.setHeader("Cache-Control", "no-cache, no-store");
                //client side javascript needs the Ajax-Location header see wicket-ajax-jquery.js line 771
                responseState.setHeader("Ajax-Location", ajaxRedirectLocation);//
                responseState.setContentType("text/xml;charset=UTF-8");
                responseState.getWriter().write("<ajax-response><redirect><![CDATA[" + ajaxRedirectLocation
                        + "]]></redirect></ajax-response>");
                responseState.flushAndClose();
            } else if (redirectLocation != null) {
                // TODO: check if its redirect to wicket page (find _wu or
                // _wuPortletMode or resourceId parameter)

                redirectLocation = fixWicketUrl(wicketURL, redirectLocation);

                final boolean validWicketUrl = redirectLocation.startsWith(wicketFilterPath);
                if (validWicketUrl) {
                    if (previousURL == null || previousURL != redirectLocation) {
                        previousURL = wicketURL;
                        wicketURL = redirectLocation;
                        ((RenderResponse) response).reset();
                        responseState.clear();
                        continue;
                    } else {
                        // internal Wicket redirection loop: unsure yet what
                        // to send out from
                        // here
                        // TODO: determine what kind of error (message or
                        // page) should be
                        // written out
                        // for now: no output available/written :(
                        responseState.clear();
                        break;
                    }
                } else {
                    responseState.clear();
                    if (responseState.isResourceResponse()) {
                        // Formally, the Portlet 2.0 Spec doesn't support
                        // directly redirecting
                        // from serveResource. However, it is possible to
                        // write response headers
                        // to the ResourceResponse (using setProperty),
                        // which means the
                        // technical implementation of a response.redirect
                        // call might be
                        // "simulated" by writing out:

                        // a) setting response.setStatus(SC_FOUND)
                        // b) setting header "Location" to the
                        // redirectLocation

                        // Caveat 1:
                        // ResourceResponse.setStatus isn't supported
                        // either, but this can be
                        // done by setting the header property
                        // ResourceResponse.HTTP_STATUS_CODE

                        // Caveat 2: Actual handling of Response headers as
                        // set through
                        // PortletResponse.setProperty is completely
                        // optional by the Portlet
                        // Spec so it really depends on the portlet
                        // container implementation
                        // (and environment, e.g. consider using WSRP
                        // here...) if this will
                        // work.

                        // On Apache Pluto/Jetspeed-2, the above descibed
                        // handling *will* be
                        // implemented as expected!

                        // HttpServletResponse.SC_FOUND == 302, defined by
                        // Servlet API >= 2.4
                        response.setProperty(ResourceResponse.HTTP_STATUS_CODE, Integer.toString(302));
                        response.setProperty("Location", redirectLocation);
                    } else {
                        response.reset();
                        response.setProperty("expiration-cache", "0");

                        PrintWriter writer = response.getWriter();
                        writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                        writer.append(
                                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
                        writer.append("<html><head><meta http-equiv=\"refresh\" content=\"0; url=")
                                .append(redirectLocation).append("\"/></head></html>");
                        writer.close();
                        break;
                    }
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("ajax redirect url after inclusion:" + redirectLocation);
                }
                // write response state out to the PortletResponse
                responseState.flushAndClose();
            }
        }
        break;
    }
}

From source file:org.kalypso.model.hydrology.internal.preprocessing.writer.BodentypWriter.java

private void writeSoilType(final PrintWriter buffer, final String soiltype,
        final SoilLayerParameter[] parameters) {
    buffer.format(Locale.US, "%-10s%4d%n", soiltype, ArrayUtils.getLength(parameters)); //$NON-NLS-1$

    for (final SoilLayerParameter parameter : parameters) {
        // basic soil type parameters
        final String layerName = parameter.getLinkedSoilLayer().getName();
        buffer.format(Locale.US, "%-8s%.1f %.1f", layerName, parameter.getThickness(), //$NON-NLS-1$
                parameter.isInterflowFloat());

        // additional drwbm soil type parameters
        if (parameter instanceof DRWBMSoilLayerParameter) {
            final DRWBMSoilLayerParameter drwbmParam = (DRWBMSoilLayerParameter) parameter;
            buffer.append(String.format(Locale.US, " %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f", //$NON-NLS-1$
                    drwbmParam.getPipeDiameter(), drwbmParam.getPipeRoughness(),
                    drwbmParam.getDrainagePipeKfValue(), drwbmParam.getDrainagePipeSlope(),
                    drwbmParam.getOverflowHeight(), drwbmParam.getAreaPerOutlet(),
                    drwbmParam.getWidthOfArea()));
        }/* w w w .ja v  a 2 s  . c o  m*/

        // line end
        buffer.format("%n"); //$NON-NLS-1$
    }
}

From source file:org.spoutcraft.launcher.skin.ConsoleFrame.java

/**
 * Internal method to consume a stream./*from www . j  ava 2s.c  o  m*/
 * 
 * @param from stream to consume
 * @param outputStream console stream to write to
 */
private void consume(InputStream from, ConsoleOutputStream outputStream) {
    final InputStream in = from;
    final PrintWriter out = new PrintWriter(outputStream, true);
    Thread thread = new Thread(new Runnable() {
        public void run() {
            byte[] buffer = new byte[1024];
            try {
                int len;
                while ((len = in.read(buffer)) != -1) {
                    String s = new String(buffer, 0, len);
                    System.out.print(s);
                    out.append(s);
                    out.flush();
                }
            } catch (IOException e) {
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }
        }
    });
    thread.setDaemon(true);
    thread.start();
}

From source file:org.opentox.toxotis.client.http.PostHttpClient.java

private void postMultiPart() throws ServiceInvocationException {
    String charset = "UTF-8";
    String LINE_FEED = "\r\n";
    InputStream is;/*w w  w  . j  a v  a2 s  .c  om*/

    try {
        getPostLock().lock(); // LOCK
        if (fileContentToPost != null) {
            is = new FileInputStream(fileContentToPost);
        } else {
            is = inputStream;
        }

        // creates a unique boundary based on time stamp
        long boundaryTs = System.currentTimeMillis();
        String boundary = "===" + boundaryTs + "===";

        HttpURLConnection httpConn = connect(getUri().toURI());
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=\"" + boundary + "\"");
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");

        OutputStream outputStream = httpConn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

        final int nParams = postParameters.size();

        if (nParams > 0) {
            for (Map.Entry<String, List<String>> e : postParameters.entrySet()) {
                List<String> values = e.getValue();
                for (String value : values) {

                    writer.append("--" + boundary).append(LINE_FEED);
                    writer.append("Content-Disposition: form-data; name=\"" + e.getKey() + "\"")
                            .append(LINE_FEED);
                    writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
                    writer.append(LINE_FEED);
                    writer.append(value).append(LINE_FEED);
                    writer.flush();
                }
            }
        }

        if (is.read() > 0) {
            is.reset();
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name=\"" + fileUploadFieldName + "\"; filename=\""
                    + fileUploadFilename + "\"").append(LINE_FEED);
            writer.append(
                    "Content-Type: " + java.net.URLConnection.guessContentTypeFromName(fileUploadFilename))
                    .append(LINE_FEED);
            writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            is.close();

            writer.append(LINE_FEED);
            writer.flush();
            writer.append(LINE_FEED).flush();
        }

        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();
    } catch (final IOException ex) {
        ConnectionException postException = new ConnectionException(
                "Exception caught while posting the parameters to the " + "remote web service located at '"
                        + getUri() + "'",
                ex);
        postException.setActor(getUri() != null ? getUri().toString() : "N/A");
        throw postException;
    } finally {
        getPostLock().unlock(); // UNLOCK
    }
}

From source file:net.hasor.maven.ExecMojo.java

protected File createEnvWrapperFile(File envScript) throws IOException {
    PrintWriter writer = null;
    File tmpFile = null;//from   ww w. j a  va 2 s  .co m
    try {
        if (OS.isFamilyWindows()) {
            tmpFile = File.createTempFile("env", ".bat");
            writer = new PrintWriter(tmpFile);
            writer.append("@echo off").println();
            writer.append("call \"").append(envScript.getCanonicalPath()).append("\"").println();
            writer.append("echo " + EnvStreamConsumer.START_PARSING_INDICATOR).println();
            writer.append("set").println();
            writer.flush();
        } else {
            tmpFile = File.createTempFile("env", ".sh");
            // tmpFile.setExecutable( true );//java 6 only
            writer = new PrintWriter(tmpFile);
            writer.append("#! /bin/sh").println();
            writer.append(". ").append(envScript.getCanonicalPath()).println(); // works on all unix??
            writer.append("echo " + EnvStreamConsumer.START_PARSING_INDICATOR).println();
            writer.append("env").println();
            writer.flush();
        }
    } finally {
        IOUtil.close(writer);
    }
    return tmpFile;
}

From source file:com.silverpeas.form.AbstractForm.java

/**
 * Prints the javascripts which will be used to control the new values given to the data record
 * fields. The error messages may be adapted to a local language. The RecordTemplate gives the
 * field type and constraints. The RecordTemplate gives the local label too. Never throws an
 * Exception but log a silvertrace and writes an empty string when :
 * <UL>//from w  w  w .j av a2  s.  c  om
 * <LI>a field is unknown by the template.
 * <LI>a field has not the required type.
 * </UL>
 * @param jw the JSP writer into which the javascript is written.
 * @param pagesContext the JSP page context.
 */
@Override
public void displayScripts(final JspWriter jw, final PagesContext pagesContext) {
    try {
        String language = pagesContext.getLanguage();
        StringWriter sw = new StringWriter();
        PrintWriter out = new PrintWriter(sw, true);

        boolean jsAdded = false;
        if (StringUtil.isDefined(pagesContext.getComponentId()) && StringUtil.isDefined(getName())) {
            ComponentInstLight component = OrganisationControllerFactory.getOrganisationController()
                    .getComponentInstLight(pagesContext.getComponentId());
            if (component != null && component.isWorkflow()) {
                out.append("<script type=\"text/javascript\" src=\"/weblib/workflows/")
                        .append(component.getName()).append("/").append(getName()).append(".js\"></script>\n");
                jsAdded = true;
            }
        }

        if (!jsAdded) {
            if (!fieldTemplates.isEmpty()) {
                FieldTemplate fieldTemplate = fieldTemplates.get(0);
                if (StringUtil.isDefined(fieldTemplate.getTemplateName())) {
                    out.append("<script type=\"text/javascript\" src=\"/weblib/xmlForms/")
                            .append(fieldTemplate.getTemplateName()).append(".js\"></script>\n");
                }
            }
        }

        PagesContext pc = new PagesContext(pagesContext);
        pc.incCurrentFieldIndex(1);

        out.append(Util.getJavascriptIncludes(language)).append("\n<script type=\"text/javascript\">\n")
                .append("   var errorNb = 0;\n").append("   var errorMsg = \"\";\n")
                .append("function addXMLError(message) {\n").append("   errorMsg+=\"  - \"+message+\"\\n\";\n")
                .append("   errorNb++;\n").append("}\n").append("function getXMLField(fieldName) {\n")
                .append("   return document.getElementById(fieldName);\n").append("}\n")
                .append("function isCorrectForm() {\n").append("   errorMsg = \"\";\n")
                .append("   errorNb = 0;\n").append("   var field;\n").append("   \n\n");

        for (FieldTemplate fieldTemplate : fieldTemplates) {
            if (fieldTemplate != null) {
                String fieldDisplayerName = fieldTemplate.getDisplayerName();
                String fieldType = fieldTemplate.getTypeName();
                String fieldName = fieldTemplate.getFieldName();
                boolean mandatory = fieldTemplate.isMandatory();
                FieldDisplayer fieldDisplayer = null;
                try {
                    if (fieldDisplayerName == null || fieldDisplayerName.isEmpty()) {
                        fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
                    }
                    fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);

                    if (fieldDisplayer != null) {
                        int nbFieldsToDisplay = fieldTemplate.getMaximumNumberOfOccurrences();
                        for (int i = 0; i < nbFieldsToDisplay; i++) {
                            String currentFieldName = Util.getFieldOccurrenceName(fieldName, i);
                            ((GenericFieldTemplate) fieldTemplate).setFieldName(currentFieldName);
                            if (i > 0) {
                                ((GenericFieldTemplate) fieldTemplate).setMandatory(false);
                            }
                            out.append("   field = document.getElementById(\"").append(currentFieldName)
                                    .append("\");\n");
                            out.append("   if (field == null) {\n");
                            // try to find field by name
                            out.append("  field = $(\"input[name=").append(currentFieldName).append("]\");\n");
                            out.println("}");
                            out.append(" if (field != null) {\n");
                            fieldDisplayer.displayScripts(out, fieldTemplate, pc);
                            out.println("}");
                            pc.incCurrentFieldIndex(
                                    fieldDisplayer.getNbHtmlObjectsDisplayed(fieldTemplate, pc));
                        }

                        // set original data
                        ((GenericFieldTemplate) fieldTemplate).setFieldName(fieldName);
                        ((GenericFieldTemplate) fieldTemplate).setMandatory(mandatory);
                    }
                } catch (FormException fe) {
                    SilverTrace.error("form", "AbstractForm.display", "form.EXP_UNKNOWN_FIELD", null, fe);
                }
            }
        }

        out.append("   \n\n").append("   switch(errorNb)\n").append("   {\n").append("   case 0 :\n")
                .append("      result = true;\n").append("      break;\n").append("   case 1 :\n")
                .append("      errorMsg = \"").append(Util.getString("GML.ThisFormContains", language))
                .append(" 1 ").append(Util.getString("GML.error", language)).append(" : \\n \" + errorMsg;\n")
                .append("      window.alert(errorMsg);\n").append("      result = false;\n")
                .append("      break;\n").append("   default :\n").append("      errorMsg = \"")
                .append(Util.getString("GML.ThisFormContains", language)).append(" \" + errorNb + \" ")
                .append(Util.getString("GML.errors", language)).append(" :\\n \" + errorMsg;\n")
                .append("      window.alert(errorMsg);\n").append("      result = false;\n")
                .append("      break;\n").append("   }\n").append("   return result;\n").append("}\n")
                .append("   \n\n");

        out.append("function showOneMoreField(fieldName) {\n");
        out.append("$('.field_'+fieldName+' ." + REPEATED_FIELD_CSS_HIDE + ":first').removeClass('"
                + REPEATED_FIELD_CSS_HIDE + "').addClass('" + REPEATED_FIELD_CSS_SHOW + "');\n");
        out.append("if ($('.field_'+fieldName+' ." + REPEATED_FIELD_CSS_HIDE + "').length == 0) {\n");
        out.append(" $('#form-row-'+fieldName+' #moreField-'+fieldName).hide();\n");
        out.append("}\n");
        out.append("}\n");

        out.append("</script>\n");
        out.flush();
        jw.write(sw.toString());
    } catch (java.io.IOException fe) {
        SilverTrace.error("form", "AbstractForm.display", "form.EXP_CANT_WRITE", null, fe);
    }
}

From source file:org.silverpeas.core.contribution.content.form.AbstractForm.java

/**
 * Prints the javascripts which will be used to control the new values given to the data record
 * fields. The error messages may be adapted to a local language. The RecordTemplate gives the
 * field type and constraints. The RecordTemplate gives the local label too. Never throws an
 * Exception but log a a trace and writes an empty string when :
 * <UL>//  ww w . j  a v a  2 s .co  m
 * <LI>a field is unknown by the template.
 * <LI>a field has not the required type.
 * </UL>
 * @param jw the JSP writer into which the javascript is written.
 * @param pagesContext the JSP page context.
 */
@Override
public void displayScripts(final JspWriter jw, final PagesContext pagesContext) {
    try {
        String language = pagesContext.getLanguage();
        StringWriter sw = new StringWriter();
        PrintWriter out = new PrintWriter(sw, true);

        boolean jsAdded = false;
        if (StringUtil.isDefined(pagesContext.getComponentId()) && StringUtil.isDefined(getName())) {
            ComponentInstLight component = OrganizationControllerProvider.getOrganisationController()
                    .getComponentInstLight(pagesContext.getComponentId());
            if (component != null && component.isWorkflow()) {
                out.append("<script type=\"text/javascript\" src=\"/weblib/workflows/")
                        .append(component.getName()).append("/").append(getName()).append(".js\"></script>\n");
                jsAdded = true;
            }
        }

        if (!jsAdded) {
            out.append(getJavascriptSnippet());
        }

        PagesContext pc = new PagesContext(pagesContext);
        pc.incCurrentFieldIndex(1);

        out.append(Util.getJavascriptIncludes(language)).append("\n<script type=\"text/javascript\">\n")
                .append("   var errorNb = 0;\n").append("   var errorMsg = \"\";\n")
                .append("function addXMLError(message) {\n").append("   errorMsg+=\"  - \"+message+\"\\n\";\n")
                .append("   errorNb++;\n").append("}\n").append("function getXMLField(fieldName) {\n")
                .append("   return document.getElementById(fieldName);\n").append("}\n")
                .append("function ifCorrectFormExecute(callback) {\n").append("   errorMsg = \"\";\n")
                .append("   errorNb = 0;\n").append("   var field;\n").append("   \n\n");

        for (FieldTemplate fieldTemplate : fieldTemplates) {
            if (fieldTemplate != null) {
                String fieldDisplayerName = fieldTemplate.getDisplayerName();
                String fieldType = fieldTemplate.getTypeName();
                String fieldName = fieldTemplate.getFieldName();
                boolean mandatory = fieldTemplate.isMandatory();
                FieldDisplayer fieldDisplayer;
                try {
                    if (fieldDisplayerName == null || fieldDisplayerName.isEmpty()) {
                        fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
                    }
                    fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);

                    if (fieldDisplayer != null) {
                        int nbFieldsToDisplay = fieldTemplate.getMaximumNumberOfOccurrences();
                        for (int i = 0; i < nbFieldsToDisplay; i++) {
                            String currentFieldName = Util.getFieldOccurrenceName(fieldName, i);
                            ((GenericFieldTemplate) fieldTemplate).setFieldName(currentFieldName);
                            if (i > 0) {
                                ((GenericFieldTemplate) fieldTemplate).setMandatory(false);
                            }
                            out.append("   field = document.getElementById(\"").append(currentFieldName)
                                    .append("\");\n");
                            out.append("   if (field == null) {\n");
                            // try to find field by name
                            out.append("  var $field = $(\"input[name=").append(currentFieldName)
                                    .append("]\");\n");
                            out.append("  field = $field.length ? $field[0] : null;\n");
                            out.println("}");
                            out.append(" if (field != null) {\n");
                            fieldDisplayer.displayScripts(out, fieldTemplate, pc);
                            out.println("}");
                            pc.incCurrentFieldIndex(
                                    fieldDisplayer.getNbHtmlObjectsDisplayed(fieldTemplate, pc));
                        }

                        // set original data
                        ((GenericFieldTemplate) fieldTemplate).setFieldName(fieldName);
                        ((GenericFieldTemplate) fieldTemplate).setMandatory(mandatory);
                    }
                } catch (FormException e) {
                    SilverLogger.getLogger(this).error(e.getMessage(), e);
                }
            }
        }

        out.append("   \n\n").append("   switch(errorNb)\n").append("   {\n").append("   case 0 :\n")
                .append("      callback.call(this);\n").append("      break;\n").append("   case 1 :\n")
                .append("      errorMsg = \"").append(Util.getString("GML.ThisFormContains", language))
                .append(" 1 ").append(Util.getString("GML.error", language)).append(" : \\n \" + errorMsg;\n")
                .append("      jQuery.popup.error(errorMsg);\n").append("      break;\n")
                .append("   default :\n").append("      errorMsg = \"")
                .append(Util.getString("GML.ThisFormContains", language)).append(" \" + errorNb + \" ")
                .append(Util.getString("GML.errors", language)).append(" :\\n \" + errorMsg;\n")
                .append("      jQuery.popup.error(errorMsg);\n").append("   }\n").append("}\n")
                .append("   \n\n");

        out.append("function showOneMoreField(fieldName) {\n");
        out.append("$('.field_'+fieldName+' ." + REPEATED_FIELD_CSS_HIDE + ":first').removeClass('"
                + REPEATED_FIELD_CSS_HIDE + "').addClass('" + REPEATED_FIELD_CSS_SHOW + "');\n");
        out.append("if ($('.field_'+fieldName+' ." + REPEATED_FIELD_CSS_HIDE + "').length == 0) {\n");
        out.append(" $('#form-row-'+fieldName+' #moreField-'+fieldName).hide();\n");
        out.append("}\n");
        out.append("}\n");

        out.append("</script>\n");
        out.flush();
        jw.write(sw.toString());
    } catch (java.io.IOException e) {
        SilverLogger.getLogger(this).error(e.getMessage(), e);
    }
}

From source file:au.gov.ansto.bragg.kowari.ui.views.AnalysisControlView.java

private void exportReport(URI targetFolderURI, Plot resultPlot) {
    File folder = null;/*w ww .  ja va 2 s  . c  o m*/
    try {
        folder = new File(targetFolderURI);
        if (!folder.exists())
            folder.mkdirs();
    } catch (Exception e) {
        folder = new File(".");
    }
    PrintWriter outputfile = null;
    try {
        File nexusFile = new File(resultPlot.getLocation());
        String sourceFilename = nexusFile.getName();
        String runNumber = sourceFilename.substring(3, sourceFilename.indexOf("."));
        File newFile = new File(
                targetFolderURI.getPath() + "/KWR" + runNumber + getProcessInfo(resultPlot) + ".sum");
        outputfile = new PrintWriter(new FileWriter(newFile));
        outputfile.append("#" + HEADER_LINE + "\r\n");
        Data intensity = resultPlot.findCalculationData("intensity");
        Data area = resultPlot.findCalculationData("intensity");
        Variance areaVariance = area.getVariance();
        Data mean = resultPlot.findCalculationData("mean");
        Variance meanVariance = mean.getVariance();
        Data sigma = resultPlot.findCalculationData("sigma");
        Variance sigmaVariance = sigma.getVariance();
        Data chi2 = resultPlot.findCalculationData("Chi2");
        IArrayIterator intensityIterator = intensity.getData().getIterator();
        IArrayIterator areaIterator = area.getData().getIterator();
        IArrayIterator areaVarIterator = areaVariance.getData().getIterator();
        IArrayIterator meanIterator = mean.getData().getIterator();
        IArrayIterator meanVarIterator = meanVariance.getData().getIterator();
        IArrayIterator sigmaIterator = sigma.getData().getIterator();
        IArrayIterator sigmaVarIterator = sigmaVariance.getData().getIterator();
        IArrayIterator chi2Iterator = chi2.getData().getIterator();
        String calculationString = null;
        int index = 0;
        while (intensityIterator.hasNext()) {
            String instrumentInfo = getInstrumentInfo(resultPlot, index);
            calculationString = getFormatedString(intensityIterator.getDoubleNext(), "%.1f") + "\t "
                    + getFormatedString(areaIterator.getDoubleNext(), "%.1f") + "\t "
                    + getFormatedString(Math.sqrt(areaVarIterator.getDoubleNext()), "%.1f") + "\t "
                    + getFormatedString(meanIterator.getDoubleNext(), "%.5f") + "\t "
                    + getFormatedString(Math.sqrt(meanVarIterator.getDoubleNext()), "%.5f") + "\t "
                    + getFormatedString(2 * sigmaIterator.getDoubleNext(), "%.5f") + "\t "
                    + getFormatedString(2 * Math.sqrt(sigmaVarIterator.getDoubleNext()), "%.5f") + "\t "
                    + getFormatedString(chi2Iterator.getDoubleNext(), "%.5f");
            outputfile.append(runNumber + "\t " + (++index) + "\t " + instrumentInfo + "\t " + "1\t "
                    + calculationString + "\r\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outputfile != null)
            outputfile.close();
    }

}

From source file:com.espertech.esper.rowregex.EventRowRegexNFAView.java

private void indent(PrintWriter writer, int indent) {
    for (int i = 0; i < indent; i++) {
        writer.append(' ');
    }/*from  w w w .  j a v  a 2  s  .c o m*/
}