Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

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

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }//from   w ww . ja  v a 2s.c  o m

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:com.redhat.rcm.version.Cli.java

private void loadConfiguration() throws VManException {
    final Logger logger = LoggerFactory.getLogger(getClass());

    File config = null;//from   www . ja va  2 s .  com

    if (configuration != null) {
        config = InputUtils.getFile(configuration, workspace);
    }

    if (config == null) {
        config = loadBootstrapConfig();
    }

    if (config == null) {
        configLocation = DEFAULT_CONFIG_FILE.getAbsolutePath();
        config = DEFAULT_CONFIG_FILE;
    }

    if (config != null && config.canRead()) {
        InputStream is = null;
        try {
            is = new FileInputStream(config);
            final Properties props = new Properties();
            props.load(is);

            final StringWriter sWriter = new StringWriter();
            for (final Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
                final String key = (String) e.nextElement();
                sWriter.write("  ");
                sWriter.write(key);
                sWriter.write(" = ");
                sWriter.write(props.getProperty(key));
                sWriter.write("\n");
            }

            props.list(new PrintWriter(sWriter));

            logger.info("Loading configuration from: " + config + ":\n\n" + sWriter);

            final File downloadsDir = VersionManagerSession.getDownloadsDir(workspace);
            final List<String> relocations = readListProperty(props, RELOCATIONS_PROPERTY);
            if (relocations != null) {
                relocatedCoords = readPropertiesList(relocations, downloadsDir, true);
            } else {
                relocatedCoords = new HashMap<String, String>();
            }

            final List<String> mappingsLocations = readListProperty(props, PROPERTY_MAPPINGS_PROPERTY);
            if (mappingsLocations != null) {
                this.propertyMappings = readPropertiesList(mappingsLocations, downloadsDir, true);
            } else {
                this.propertyMappings = new HashMap<String, String>();
            }

            if (removedPluginsList == null) {
                removedPlugins = readListProperty(props, REMOVED_PLUGINS_PROPERTY);
            }

            if (removedTestsList == null) {
                removedTests = readListProperty(props, REMOVED_TESTS_PROPERTY);
            }

            if (extensionsWhitelistList == null) {
                extensionsWhitelist = readListProperty(props, EXTENSIONS_WHITELIST_PROPERTY);
            }

            if (pomExcludeModules == null) {
                pomExcludeModules = props.getProperty(POM_EXCLUDE_MODULE_PROPERTY);
            }

            if (pomExcludePattern == null) {
                pomExcludePattern = props.getProperty(POM_EXCLUDE_FILE_PROPERTY);
            }

            if (modifications == null) {
                final List<String> lst = readListProperty(props, MODIFICATIONS);
                logger.info("modifications from properties: '" + join(lst, " ") + "'");
                if (lst != null) {
                    modders = modders == null ? new ArrayList<String>() : new ArrayList<String>(modders);
                    modders.addAll(lst);
                }
            }

            if (bomList == null) {
                if (boms == null) {
                    boms = new ArrayList<String>();
                }

                final List<String> pBoms = readListProperty(props, BOMS_LIST_PROPERTY);
                if (pBoms != null) {
                    boms.addAll(pBoms);
                }
            }

            if (toolchain == null) {
                toolchain = props.getProperty(TOOLCHAIN_PROPERTY);
                if (toolchain != null) {
                    toolchain = toolchain.trim();
                }
            }

            if (versionSuffix == null) {
                versionSuffix = props.getProperty(VERSION_SUFFIX_PROPERTY);
                if (versionSuffix != null) {
                    versionSuffix = versionSuffix.trim();
                }
            }

            if (versionModifier == null) {
                versionModifier = props.getProperty(VERSION_MODIFIER_PROPERTY);
                if (versionModifier != null) {
                    versionModifier = versionModifier.trim();
                }
            }

            if (remoteRepositories == null) {
                remoteRepositories = props.getProperty(REMOTE_REPOSITORIES_PROPERTY);
                if (remoteRepositories != null) {
                    remoteRepositories = remoteRepositories.trim();
                } else {
                    remoteRepositories = props.getProperty(REMOTE_REPOSITORY_PROPERTY);

                    if (remoteRepositories != null) {
                        logger.warn("Using deprecated " + REMOTE_REPOSITORY_PROPERTY);
                        remoteRepositories = remoteRepositories.trim();
                    }
                }
            }

            if (settings == null) {
                final String s = props.getProperty(SETTINGS_PROPERTY);
                if (s != null) {
                    settings = s;
                }
            }

            if (localRepository == null) {
                final String l = props.getProperty(LOCAL_REPOSITORY_PROPERTY);
                if (l != null) {
                    localRepository = new File(l);
                }
            }

            if (capturePom == null) {
                final String p = props.getProperty(CAPTURE_POM_PROPERTY);
                if (p != null) {
                    capturePom = new File(p);
                }
            }

            if (!strict) {
                strict = Boolean
                        .valueOf(props.getProperty(STRICT_MODE_PROPERTY, Boolean.toString(Boolean.FALSE)));
            }

            if (!useEffectivePoms) {
                useEffectivePoms = Boolean.valueOf(
                        props.getProperty(USE_EFFECTIVE_POMS_PROPERTY, Boolean.toString(Boolean.FALSE)));
            }

            if (truststorePath == null) {
                truststorePath = props.getProperty(TRUSTSTORE_PATH_PROPERTY);
            }

            final Map<String, String> userProps = new HashMap<String, String>();
            for (final Enumeration<?> keys = props.keys(); keys.hasMoreElements();) {
                final String key = (String) keys.nextElement();
                if (key.startsWith(REPORT_PROPERTY_PREFIX)) {
                    userProps.put(key.substring(REPORT_PROPERTY_PREFIX.length()), props.getProperty(key));
                }
            }

            if (!userProps.isEmpty()) {
                if (reportProperties == null) {
                    reportProperties = userProps;
                } else {
                    userProps.putAll(reportProperties);
                    reportProperties = userProps;
                }
            }
        } catch (final IOException e) {
            throw new VManException("Failed to load configuration from: " + config, e);
        } finally {
            closeQuietly(is);
        }
    } else {
        configLocation = "command-line";
    }
}

From source file:org.alfresco.web.bean.forums.ForumsBean.java

protected void renderReplyContentHTML(FacesContext context, Node replyToNode, StringWriter writer,
        String contextPath, String colour, String bgColour) throws IOException {
    // get the content of the article being replied to
    String replyContent = "";
    ContentReader reader = this.getContentService().getReader(replyToNode.getNodeRef(),
            ContentModel.PROP_CONTENT);
    if (reader != null) {
        replyContent = Utils.stripUnsafeHTMLTags(reader.getContentString());
    }/*from ww w .j  a  va 2  s.c  om*/

    // get the date of the article being replied to
    String postedDate = Utils.getDateTimeFormat(context).format(replyToNode.getProperties().get("created"));

    // generate the HTML
    writer.write("<td width='100%'>");
    TopicBubbleViewRenderer.renderBubbleTop(writer, contextPath, colour, bgColour);
    writer.write("<span class='mainSubTitle'>");
    writer.write(Application.getMessage(context, "posted"));
    writer.write(":&nbsp</span>");
    writer.write(postedDate);
    TopicBubbleViewRenderer.renderBubbleMiddle(writer, contextPath, colour);
    writer.write(replyContent);
    TopicBubbleViewRenderer.renderBubbleBottom(writer, contextPath, colour);
    writer.write("</td>");
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

/**
 * Add JavaScript to the HTML to raise postback events to send messages to the bot.
 *//* w ww  . j a  v a  2  s  . c  om*/
public String linkPostbacks(String html) {
    if (html.contains("button")) {
        TextStream stream = new TextStream(html);
        StringWriter writer = new StringWriter();
        while (!stream.atEnd()) {
            writer.write(stream.upToAll("<button", true));
            if (!stream.atEnd()) {
                String element = stream.upTo('>', true);
                String button = stream.upTo('<', false);
                writer.write(" onclick=\"Android.postback('" + button + "')\" ");
                writer.write(element);
                writer.write(button);
            }
        }
        html = writer.toString();
    }
    if (html.contains("chat:")) {
        TextStream stream = new TextStream(html);
        StringWriter writer = new StringWriter();
        while (!stream.atEnd()) {
            writer.write(stream.upToAll("href=\"", true));
            if (stream.atEnd()) {
                break;
            }
            String protocol = stream.upTo(':', true);
            if (!protocol.equals("chat:")) {
                writer.write(protocol);
                continue;
            }
            String chat = stream.upTo('"', false);
            writer.write("#\"");
            writer.write(" onclick=\"Android.postback('" + chat + "')\" ");
        }
        html = writer.toString();
    }
    if (html.contains("select")) {
        TextStream stream = new TextStream(html);
        StringWriter writer = new StringWriter();
        while (!stream.atEnd()) {
            writer.write(stream.upToAll("<select", true));
            if (!stream.atEnd()) {
                writer.write(" onchange=\"Android.postback(this.value)\" ");
            }
        }
        html = writer.toString();
    }
    return html;
}

From source file:org.apache.openjpa.lib.conf.ConfigurationImpl.java

public void instantiateAll() {
    StringWriter errs = null;
    PrintWriter stack = null;/*from  w  w  w .  j  a  va  2  s. c om*/
    String getterName;
    Method getter;
    Object getterTarget;
    for (Value val : _vals) {
        getterName = val.getInstantiatingGetter();
        if (getterName == null)
            continue;

        getterTarget = this;
        if (getterName.startsWith("this.")) {
            getterName = getterName.substring("this.".length());
            getterTarget = val;
        }

        try {
            getter = getterTarget.getClass().getMethod(getterName, (Class[]) null);
            getter.invoke(getterTarget, (Object[]) null);
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException)
                t = ((InvocationTargetException) t).getTargetException();
            if (errs == null) {
                errs = new StringWriter();
                stack = new PrintWriter(errs);
            } else
                errs.write(SEP);
            t.printStackTrace(stack);
            stack.flush();
        }
    }
    if (errs != null)
        throw new RuntimeException(_loc.get("get-prop-errs", errs.toString()).getMessage());
}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

/**
 * Tunnels a request to the online application using given URL mapping and SSLSocketFactory.
 * This method returns the ResponseCode of the request to the online application. 
 * @param req HTTP request/* w  ww .java2s . co m*/
 * @param resp HTTP response
 * @param loginHeaders header field/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param loginParameters parameter name/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param publicURLPrefix prefix of request URL to be substituted for the <code>realURLPrefix</code>
 * @param realURLPrefix prefix of online application URL to substitute the <code>publicURLPrefix</code>
 * @param ssf SSLSocketFactory to use
 * @throws IOException if an I/O error occurs
 */
private int tunnelRequest(HttpServletRequest req, HttpServletResponse resp, Map loginHeaders,
        Map loginParameters, String publicURLPrefix, String realURLPrefix, SSLSocketFactory ssf, String binding)
        throws IOException {

    String originBinding = binding;
    String browserUserID = "";
    String browserPassword = "";
    //URL url = new URL(realURLPrefix); 
    //String realURLHost = url.getHost(); 
    if (INTERNAL_DEBUG && !binding.equals(""))
        Logger.debug("Binding: " + binding);

    // collect headers from request
    Map headers = new HashMap();
    for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) {
        String headerKey = (String) enu.nextElement();
        String headerKeyValue = req.getHeader(headerKey);
        if (INTERNAL_DEBUG)
            Logger.debug("Incoming:" + headerKey + "=" + headerKeyValue);
        //Analyze Basic-Auth-Headers from the client
        if (headerKey.equalsIgnoreCase("Authorization")) {
            if (headerKeyValue.substring(0, 6).equalsIgnoreCase("Basic ")) {
                String credentials = headerKeyValue.substring(6);
                byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                String plaintextcredentials = new String(bplaintextcredentials);
                browserUserID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                browserPassword = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
            if (headerKeyValue.substring(0, 9).equalsIgnoreCase("Negotiate")) {
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: Found NTLM Aut.: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
        } else {
            /* Headers MUST NOT be repaced according to our Spec.
            if (headerKey.equalsIgnoreCase("Host")) {
               headerKeyValue = realURLHost; 
                 //headerKeyValue= realURLPrefix.substring(hoststartpos);
              if (INTERNAL_DEBUG) Logger.debug("replaced:" + headerKey + "=" + headerKeyValue);           
            }
            */
            headers.put(headerKey, headerKeyValue);
        }
    }

    // collect login headers, possibly overwriting headers from request
    String authorizationvalue = "";
    if (req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {

        if (OAConfiguration.BINDUNG_NOMATCH.equals(binding)) {
            int loginTry = getLoginTry(req);
            Logger.debug("Binding: mode = " + OAConfiguration.BINDUNG_NOMATCH + "(try #"
                    + Integer.toString(loginTry) + ")");
            if (loginTry == 1) {
                binding = OAConfiguration.BINDUNG_FULL;
            } else {
                binding = OAConfiguration.BINDUNG_USERNAME;
            }
        }

        /* Soll auch bei anderen bindings zuerst ein passwort probiert werden knnen:
        //if we have the first Login-Try and we have Binding to Username and a predefined Password we try this one first
         // full binding will be covered by next block
         if (loginTry==1 && !OAConfiguration.BINDUNG_FULL.equals(binding)) {
           //1st try: if we have a password, try this one first
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
              String headerKey = (String) iter.next();
              String headerKeyValue = (String) loginHeaders.get(headerKey);
              if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
               String credentials = headerKeyValue.substring(6);
               byte [] bplaintextcredentials = Base64Utils.decode(credentials, true);
              String plaintextcredentials = new String(bplaintextcredentials);
              String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":")+1);
              if (password!=null && !password.equals("")) {
                  Logger.debug("Binding: found predefined password. Trying full binding first");
                 binding = OAConfiguration.BINDUNG_FULL;
                 break;
                }
              }
            }
         }
         */

        //we have a connection with not having logged on
        if (loginHeaders != null && (browserPassword.length() != 0 || browserUserID.length() != 0
                || OAConfiguration.BINDUNG_FULL.equals(binding))) {
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
                String headerKey = (String) iter.next();
                String headerKeyValue = (String) loginHeaders.get(headerKey);
                //customize loginheaders if necessary
                if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
                    if (OAConfiguration.BINDUNG_FULL.equals(binding)) {
                        authorizationvalue = headerKeyValue;
                        Logger.debug("Binding: full binding to user established");
                    } else {
                        String credentials = headerKeyValue.substring(6);
                        byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                        String plaintextcredentials = new String(bplaintextcredentials);
                        String userID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                        String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                        String userIDPassword = ":";
                        if (OAConfiguration.BINDUNG_USERNAME.equals(binding)) {
                            Logger.debug("Binding: Access with necessary binding to user");
                            userIDPassword = userID + ":" + browserPassword;
                        } else if (OAConfiguration.BINDUNG_NONE.equals(binding)) {
                            Logger.debug("Binding: Access without binding to user");
                            //If first time
                            if (browserUserID.length() == 0)
                                browserUserID = userID;
                            if (browserPassword.length() == 0)
                                browserPassword = password;
                            userIDPassword = browserUserID + ":" + browserPassword;
                        } else {
                            userIDPassword = userID + ":" + password;
                        }
                        credentials = Base64Utils.encode(userIDPassword.getBytes());
                        authorizationvalue = "Basic " + credentials;
                        headerKeyValue = authorizationvalue;
                    }
                }
                headers.put(headerKey, headerKeyValue);
            }
        }
    } else {
        //if OA needs Authorization header in each further request
        authorizationvalue = (String) req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER);
        if (loginHeaders != null)
            headers.put("Authorization", authorizationvalue);
    }

    Vector parameters = new Vector();
    for (Enumeration enu = req.getParameterNames(); enu.hasMoreElements();) {
        String paramName = (String) enu.nextElement();
        if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
            if (INTERNAL_DEBUG)
                Logger.debug("Req Parameter-put: " + paramName + ":" + req.getParameter(paramName));
            String parameter[] = new String[2];
            parameter[0] = paramName;
            parameter[1] = req.getParameter(paramName);
            parameters.add(parameter);
        }
    }
    // collect login parameters, possibly overwriting parameters from request
    if (loginParameters != null) {
        for (Iterator iter = loginParameters.keySet().iterator(); iter.hasNext();) {
            String paramName = (String) iter.next();
            if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
                if (INTERNAL_DEBUG)
                    Logger.debug(
                            "Req Login-Parameter-put: " + paramName + ":" + loginParameters.get(paramName));
                String parameter[] = new String[2];
                parameter[0] = paramName;
                parameter[1] = (String) loginParameters.get(paramName);
                parameters.add(parameter);
            }
        }
    }

    ConnectionBuilder cb = ConnectionBuilderFactory.getConnectionBuilder(publicURLPrefix);
    HttpURLConnection conn = cb.buildConnection(req, publicURLPrefix, realURLPrefix, ssf, parameters);

    // set headers as request properties of URLConnection
    for (Iterator iter = headers.keySet().iterator(); iter.hasNext();) {
        String headerKey = (String) iter.next();
        String headerValue = (String) headers.get(headerKey);
        String LogStr = "Req header " + headerKey + ": " + headers.get(headerKey);
        if (isBasicAuthenticationHeader(headerKey, headerValue)) {
            String credentials = headerValue.substring(6);
            byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
            String plaintextcredentials = new String(bplaintextcredentials);
            String uid = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
            String pwd = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
            //Sollte AuthorizationInfo vom HTTPClient benutzt werden:  cb.addBasicAuthorization(publicURLPrefix, uid, pwd);
            //deactivate following line for security
            //if (INTERNAL_DEBUG && Logger.isDebugEnabled()) LogStr = LogStr + "  >UserID:Password< >" + uid + ":" + pwd + "<";
        }
        conn.setRequestProperty(headerKey, headerValue);
        if (INTERNAL_DEBUG)
            Logger.debug(LogStr);
    }

    StringWriter sb = new StringWriter();

    // Write out parameters into output stream of URLConnection.
    // On GET request, do not send parameters in any case,
    // otherwise HttpURLConnection would send a POST.
    if (!"get".equalsIgnoreCase(req.getMethod()) && !parameters.isEmpty()) {
        boolean firstParam = true;
        String parameter[] = new String[2];
        for (Iterator iter = parameters.iterator(); iter.hasNext();) {
            parameter = (String[]) iter.next();
            String paramName = parameter[0];
            String paramValue = parameter[1];
            if (firstParam)
                firstParam = false;
            else
                sb.write("&");
            sb.write(paramName);
            sb.write("=");
            sb.write(paramValue);
            if (INTERNAL_DEBUG)
                Logger.debug("Req param " + paramName + ": " + paramValue);
        }
    }

    // For WebDAV and POST: copy content
    if (!"get".equalsIgnoreCase(req.getMethod())) {
        if (INTERNAL_DEBUG && !"post".equalsIgnoreCase(req.getMethod()))
            Logger.debug("---- WEBDAV ----  copying content");
        try {
            OutputStream out = conn.getOutputStream();
            InputStream in = req.getInputStream();
            if (!parameters.isEmpty())
                out.write(sb.toString().getBytes()); //Parameter nicht mehr mittels Printwriter schreiben 
            copyStream(in, out, null, req.getMethod());
            out.flush();
            out.close();
        } catch (IOException e) {
            if (!"post".equalsIgnoreCase(req.getMethod()))
                Logger.debug("---- WEBDAV ----  streamcopy problem");
            else
                Logger.debug("---- POST ----  streamcopy problem");
        }
    }

    // connect
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Request");
    conn.connect();
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Response");

    // check login tries
    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        int loginTry = getLoginTry(req);
        req.getSession().setAttribute(ATT_OA_LOGINTRY, Integer.toString(loginTry));
        if (loginTry > MAX_OA_LOGINTRY) {
            Logger.debug("Found 401 UNAUTHORIZED, maximum tries exceeded; leaving...");
            cb.disconnect(conn);
            return -401;
        }
    }

    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED
            && OAConfiguration.BINDUNG_FULL.equals(originBinding)) {
        Logger.debug("Found 401 UNAUTHORIZED, leaving...");
        cb.disconnect(conn);
        return conn.getResponseCode();
    }

    resp.setStatus(conn.getResponseCode());
    //Issue by Gregor Karlinger - content type was annotated twice
    //resp.setContentType(conn.getContentType());

    if (loginHeaders != null
            && (conn.getResponseCode() == HttpURLConnection.HTTP_OK
                    || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
            && req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {
        req.getSession().setAttribute(ATT_OA_AUTHORIZATION_HEADER, authorizationvalue);
        Logger.debug("Login OK. Saving authorization header to remember in further requests");
    }

    // Read response headers
    // Omit response header "content-length" if response header "Transfer-encoding: chunked" is set.
    // Otherwise, the connection will not be kept alive, resulting in subsequent missing requests.
    // See JavaDoc of javax.servlet.http.HttpServlet:
    // When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.
    Vector respHeaders = new Vector();

    boolean chunked = false;
    String contentLengthKey = null;
    String transferEncodingKey = null;
    int i = 1;
    String headerKey;
    String loginType = (String) req.getSession().getAttribute(ATT_OA_LOGINTYPE);
    while ((headerKey = conn.getHeaderFieldKey(i)) != null) {
        String headerValue = conn.getHeaderField(i);

        if (headerKey.equalsIgnoreCase("WWW-Authenticate")) {
            int start = headerValue.indexOf("Basic realm=\"");
            boolean requestsBasicAuth = headerValue.substring(start).startsWith("Basic realm=\"");
            if (requestsBasicAuth) {
                headerValue = "Basic realm=\"" + publicURLPrefix + "\"";

                if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding)
                        || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding))
                    headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
                else if ("none".equals(originBinding)) {
                    headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
                }
            }
        }

        //    // berschrift im Browser-Passworteingabedialog setzen (sonst ist der reale host eingetragen)
        //    if (headerKey.equalsIgnoreCase("WWW-Authenticate") && headerValue.startsWith("Basic realm=\"")) {
        //      headerValue = "Basic realm=\"" + publicURLPrefix + "\"";
        //      if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding) || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
        //      } else if (OAConfiguration.BINDUNG_NONE.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
        //      }
        //    }

        String respHeader[] = new String[2];
        if ((conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
                && headerKey.equalsIgnoreCase("content-length")) {
            //alter the unauthorized message with template for login 
            //TODO: supply a special login form on unauthorized messages with bindings!=full
            headerValue = Integer.toString(RET_401_MSG.length());
        }
        respHeader[0] = headerKey;
        respHeader[1] = headerValue;

        if (!(OAConfiguration.BINDUNG_FULL.equals(originBinding)
                && OAConfiguration.LOGINTYPE_STATELESS.equals(loginType)
                && headerKey.equalsIgnoreCase("WWW-Authenticate")
                && headerValue.startsWith("Basic realm=\""))) {
            respHeaders.add(respHeader);
            if (INTERNAL_DEBUG)
                Logger.debug("Resp header " + headerKey + ": " + headerValue);
        } else {
            Logger.debug("Resp header ---REMOVED--- " + headerKey + ": " + headerValue);
        }
        if (isTransferEncodingChunkedHeader(headerKey, headerValue)
                || "content-length".equalsIgnoreCase(headerKey)) {
            respHeaders.remove(respHeader);
            Logger.debug("Resp header " + headerKey + " REMOVED");
        }

        i++;
    }

    String headerValue;
    String respHeader[] = new String[2];

    //write out all Responseheaders 
    for (Iterator iter = respHeaders.iterator(); iter.hasNext();) {
        respHeader = (String[]) iter.next();
        headerKey = respHeader[0];
        headerValue = respHeader[1];
        resp.addHeader(headerKey, headerValue);
    }

    //Logger.debug(">>>> Copy Content");
    //Logger.debug("  from ()" + conn.getURL());
    //Logger.debug("  to (" + req.getRemoteAddr() + ":"+ ") " +req.getRequestURL());

    // read response stream
    Logger.debug("Resp from " + conn.getURL().toString() + ": status " + conn.getResponseCode());
    // Load content unless the server lets us know that the content is NOT MODIFIED...
    if (conn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED) {
        BufferedInputStream respIn = new BufferedInputStream(conn.getInputStream());
        //Logger.debug("Got Inputstream");
        BufferedOutputStream respOut = new BufferedOutputStream(resp.getOutputStream());
        //Logger.debug("Got Outputstream");

        byte[] buffer = new byte[4096];
        if (respOut != null) {
            int bytesRead;
            while ((bytesRead = respIn.read(buffer)) >= 0) {
                if (conn.getResponseCode() != HttpURLConnection.HTTP_UNAUTHORIZED)
                    respOut.write(buffer, 0, bytesRead);
            }
        } else {
            while (respIn.read(buffer) >= 0)
                ;
        }

        /*
        int ch;
        StringBuffer strBuf = new StringBuffer("");
        while ((ch = respIn.read()) >= 0) {
          if (conn.getResponseCode()!=HttpURLConnection.HTTP_UNAUTHORIZED) respOut.write(ch);
          strBuf.append((char)ch);
        }
        Logger.debug("Resp Content:");
        if (strBuf.toString().length()>500)
          Logger.debug(strBuf.toString().substring(0,500));
        else
          Logger.debug(strBuf.toString());
        */

        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            respOut.write(RET_401_MSG.getBytes());
        }
        respOut.flush();
        respOut.close();
        respIn.close();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            Logger.debug("Found 401 UNAUTHORIZED...");
            cb.disconnect(conn);
            return conn.getResponseCode();
        }
    } else {
        //if (conn.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED) 
        Logger.debug("Found 304 NOT MODIFIED...");
    }

    cb.disconnect(conn);
    Logger.debug("Request done");

    return conn.getResponseCode();
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

private String getHsqlDBHistTriggerSql(Dialect dialect, String tableName, String histTableName,
        String histColName, Set<String> columns, List<String> pkColumns, List<String> histRelevantCols) {
    VelocityContext context = new VelocityContext();

    Set<String> nonPkColumns = new HashSet<String>(columns);
    nonPkColumns.removeAll(pkColumns);//from   w w  w  .  ja  va2 s.c om

    context.put("VERSION_COLUMN_NAME", VERSION_COLUMN_NAME);
    context.put("MODIFIER_COLUMN_NAME", AuditInfo.LAST_MODIFIED_BY);
    context.put("liveTableName", tableName);
    context.put("hstTableName", histTableName);
    context.put("columns", columns);
    context.put("histColName", histColName);
    context.put("pkColumns", pkColumns);
    context.put("nonPkColumns", nonPkColumns);
    context.put("histRelevantCols", histRelevantCols);

    StringWriter wr = new StringWriter();

    try {
        wr.append(STATEMENT_SEPARATOR);
        writeTriggerSingleOperation(dialect, wr, "HstTriggerSingleOperation.vm.pl.sql", context, tableName,
                "_ht", "I");
        wr.write("\n/\n");
        wr.append(STATEMENT_SEPARATOR);
        writeTriggerSingleOperation(dialect, wr, "HstTriggerSingleOperation.vm.pl.sql", context, tableName,
                "_ht", "U");
        wr.write("\n/\n");
        wr.append(STATEMENT_SEPARATOR);
        writeTriggerSingleOperation(dialect, wr, "HstTriggerSingleOperation.vm.pl.sql", context, tableName,
                "_ht", "D");
        wr.write("\n/\n");
    } catch (IOException e) {
        throw new IllegalStateException("cannot read history trigger template");
    }

    return wr.toString();
}

From source file:org.alfresco.web.bean.forums.ForumsBean.java

/**
 * Returns the HTML to represent a bubble rendition of the text of the the
 * forum article being replied to.//w  w w.  j  a  va2 s.  c  o m
 * 
 * @return The HTML for the bubble
 */
public String getReplyBubbleHTML() {
    try {
        // if the forum being replied to was a new post show the orange bubble
        // with the user on the left otherwise show the yellow bubble with the
        // user on the right.
        StringWriter writer = new StringWriter();

        FacesContext context = FacesContext.getCurrentInstance();
        Node replyToNode = this.browseBean.getDocument();
        boolean isReplyPost = this.getNodeService().hasAspect(replyToNode.getNodeRef(),
                ContentModel.ASPECT_REFERENCING);
        String contextPath = context.getExternalContext().getRequestContextPath();
        String colour = isReplyPost ? "yellow" : "orange";
        String bgColour = isReplyPost ? "#FFF5A3" : "#FCC75E";

        // build the HTML to represent the user that posted the article being replied to
        StringBuilder replyPosterHTML = new StringBuilder("<td valign='top'>");
        replyPosterHTML.append("<img src='");
        replyPosterHTML.append(contextPath);
        replyPosterHTML.append("/images/icons/user_large.gif' /><br>");
        replyPosterHTML.append((String) replyToNode.getProperties().get("creator"));
        replyPosterHTML.append("</td>");

        // start the table
        writer.write("<table border='0' cellpadding='0' cellspacing='0' width='100%'><tr>");

        if (isReplyPost) {
            renderReplyContentHTML(context, replyToNode, writer, contextPath, colour, bgColour);
            writer.write(replyPosterHTML.toString());
        } else {
            writer.write(replyPosterHTML.toString());
            renderReplyContentHTML(context, replyToNode, writer, contextPath, colour, bgColour);
        }

        // finish the table
        writer.write("</tr></table>");

        return writer.toString();
    } catch (IOException ioe) {
        throw new AlfrescoRuntimeException("Failed to render reply bubble HTML", ioe);
    }
}

From source file:eu.sisob.uma.restserver.TaskManager.java

/**
  * Create a new folder for a new task if is possible to launch new task
  * Note:// w ww .j a  v a2 s .  c  o m
  *  use MAX_TASKS_PER_USER and validateAccess()
  *  Is possible that use thee locker of AuthorizationManager
  * @param user
  * @param pass
  * @param status
  * @param message 
  * @return
  */
public static String prepareNewTask(String user, String pass, StringWriter status, StringWriter message) {
    String new_folder_name = "";
    if (message == null)
        return "";
    message.getBuffer().setLength(0);

    if (user != null && pass != null) {
        if (AuthorizationManager.validateAccess(user, pass, message)) {
            message.getBuffer().setLength(0);
            List<String> task_code_list = TaskManager.listTasks(user, pass);

            int num_tasks_alive = 0;
            int max = -1;
            if (task_code_list.size() > 0) {
                for (String task_code : task_code_list) {
                    OutputTaskStatus task_status = TaskManager.getTaskStatus(user, pass, task_code, false,
                            false, false);
                    if (task_status.status.equals(OutputTaskStatus.TASK_STATUS_EXECUTED)) {

                    } else {
                        //Think about it
                        num_tasks_alive++;
                    }

                    try {
                        int act = Integer.parseInt(task_code);
                        if (max < act) {
                            max = act;
                        }
                    } catch (Exception ex) {

                    }

                }
            }

            if (num_tasks_alive < AuthorizationManager.MAX_TASKS_PER_USER) {
                new_folder_name = String.valueOf(max + 1);

                String code_task_folder = TASKS_USERS_PATH + File.separator + user + File.separator
                        + new_folder_name;
                File task_dir = new File(code_task_folder);
                if (!task_dir.exists()) {
                    task_dir.mkdir();
                    status.append(OutputTaskStatus.TASK_STATUS_TO_EXECUTE);
                    if (message != null)
                        message.append("A new task has been created successfully."); //FIXME
                } else {
                    new_folder_name = "";
                    status.append(OutputTaskStatus.TASK_STATUS_NO_ACCESS);
                    if (message != null)
                        message.append("Error creating place for the new task."); //FIXME
                }
            } else {
                new_folder_name = "";
                status.append(OutputTaskStatus.TASK_STATUS_EXECUTING);
                if (message != null)
                    message.append(
                            "There are still tasks running or there are a task created ready to be launched."); //FIXME
            }

        } else {
            new_folder_name = "";
            status.append(OutputTaskStatus.TASK_STATUS_NO_AUTH);
        }
    } else {
        new_folder_name = "";
        status.write(OutputTaskStatus.TASK_STATUS_NO_AUTH);
        if (message != null)
            message.write(TheResourceBundle.getString("Jsp Params Invalid Msg"));
    }

    return new_folder_name;
}

From source file:org.xwiki.lesscss.internal.compiler.CachedIntegratedLESSCompiler.java

@Override
public String compute(LESSResourceReference lessResourceReference, boolean includeSkinStyle,
        boolean useVelocity, String skin) throws LESSCompilerException {
    StringWriter source = new StringWriter();
    List<Path> includePaths = new ArrayList<>();
    List<File> tempFilesToDelete = new ArrayList<>();
    File tempDir = null;//from   w  w w  .j a va2  s . c  o m

    try {
        if (lessResourceReference instanceof LESSSkinFileResourceReference || includeSkinStyle) {
            // Because of possible collisions between the LESS and the Velocity syntaxes, and some limitations
            // of the LESS compiler, we do not execute Velocity on included files .
            //
            // But since we want to include the main skin file (to be able to use LESS variables and mix-ins defined
            // by the skin (see http://jira.xwiki.org/browse/XWIKI-10708), we need this file to be rendered by
            // Velocity AND included by the current LESS resource.
            //
            // To do that, we create a temporary directory where we put the Velocity-rendered content of the main
            // skin file, so that the LESS resource can include it.
            //
            // This temp directory is also used to store LESS Skin files that are overwritten in the skin object.
            // (see http://jira.xwiki.org/browse/XWIKI-11394)
            // TODO: it is actually not implemented yet
            //
            // Finally, this directory is used as the main include path by LESS Compiler.
            tempDir = createTempDir(includePaths, tempFilesToDelete);

            // TODO: implement http://jira.xwiki.org/browse/XWIKI-11394 here

            // Get the skin directory, where LESS resources are located
            Path lessFilesPath = skinDirectoryGetter.getLESSSkinFilesDirectory(skin);
            includePaths.add(lessFilesPath);

            // Render and include the main skin file
            if (includeSkinStyle) {
                importMainSkinStyle(source, skin, tempDir, tempFilesToDelete);
            }

            // Get the content of the LESS resource
            source.write(lessResourceReader.getContent(lessResourceReference, skin));
        }

        // Parse the LESS content with Velocity
        String lessCode = source.toString();
        if (useVelocity) {
            lessCode = executeVelocity(source.toString(), skin);
        }

        // Compile the LESS code
        Path[] includePathsArray = includePaths.toArray(new Path[1]);
        String result = lessCompiler.compile(lessCode, includePathsArray);

        // Remove some useless code
        if (includeSkinStyle) {
            result = removeMainSkinStyleUndesiredOutput(result);
        }

        // End
        return result;
    } catch (LESSCompilerException | IOException e) {
        throw new LESSCompilerException(
                String.format("Failed to compile the resource [%s] with LESS.", lessResourceReference), e);
    } finally {
        deleteTempFiles(tempFilesToDelete);
    }
}