Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:edu.cornell.med.icb.goby.modes.CompactToFastaMode.java

@Override
public void execute() throws IOException {
    // output file extension is based on the output format type
    final String outputExtension = "." + outputFormat.name().toLowerCase(Locale.getDefault());
    if (outputFilename == null) {
        outputFilename = FilenameUtils.removeExtension(inputFilename) + (hashOutputFilename ? hash() : "")
                + outputExtension;/*from   w w  w  .  ja  va2  s . com*/
    } else if (hashOutputFilename) {
        outputFilename = FilenameUtils.removeExtension(outputFilename) + (hashOutputFilename ? hash() : "")
                + outputExtension;
    }

    ReadSet readIndexFilter = new ReadSet();
    if (readIndexFilterFile == null) {
        readIndexFilter = null;
    } else {
        readIndexFilter.load(readIndexFilterFile);
    }

    final ProgressLogger progress = new ProgressLogger();
    progress.start();
    progress.displayFreeMemory = true;

    // Only sanger and illumina encoding are supported at this time
    if (qualityEncoding == QualityEncoding.SOLEXA) {
        throw new UnsupportedOperationException(
                "SOLEXA encoding is not supported " + "at this time for lack of clear documentation.");
    } else if (qualityEncoding != QualityEncoding.SANGER && qualityEncoding != QualityEncoding.ILLUMINA) {
        throw new UnsupportedOperationException("Unknown encoding: " + qualityEncoding);
    }

    ReadsReader reader = null;
    Writer writer = null;
    OutputStreamWriter pairWriter = null;
    final int newEntryCharacter;
    switch (outputFormat) {
    case FASTQ:
        newEntryCharacter = '@';
        break;
    case FASTA:
    default:
        newEntryCharacter = '>';
        break;
    }
    try {
        writer = new OutputStreamWriter(new FastBufferedOutputStream(new FileOutputStream(outputFilename)));
        pairWriter = processPairs
                ? new OutputStreamWriter(new FastBufferedOutputStream(new FileOutputStream(outputPairFilename)))
                : null;

        final MutableString colorSpaceBuffer = new MutableString();
        final MutableString sequence = new MutableString();
        final MutableString sequencePair = new MutableString();

        if (hasStartOrEndPosition) {
            reader = new ReadsReader(startPosition, endPosition, inputFilename);
        } else {
            reader = new ReadsReader(inputFilename);
        }

        for (final Reads.ReadEntry readEntry : reader) {
            if (readIndexFilter == null || readIndexFilter.contains(readEntry.getReadIndex())) {
                final String description;

                if (indexToHeader) {
                    description = Integer.toString(readEntry.getReadIndex());
                } else if (identifierToHeader && readEntry.hasReadIdentifier()) {
                    description = readEntry.getReadIdentifier();
                } else if (readEntry.hasDescription()) {
                    description = readEntry.getDescription();
                } else {
                    description = Integer.toString(readEntry.getReadIndex());
                }

                writer.write(newEntryCharacter);
                writer.write(description);
                writer.write('\n');
                final boolean processPairInThisRead = processPairs && readEntry.hasSequencePair();
                if (processPairInThisRead) {
                    pairWriter.write(newEntryCharacter);
                    pairWriter.write(description);
                    pairWriter.write('\n');
                }
                observeReadIndex(readEntry.getReadIndex());
                ReadsReader.decodeSequence(readEntry, sequence);

                if (processPairInThisRead) {
                    ReadsReader.decodeSequence(readEntry, sequencePair, true);
                }

                if (queryLengths != null) {
                    queryLengths.put(readEntry.getReadIndex(), sequence.length());
                }

                MutableString transformedSequence = sequence;
                MutableString transformedSequencePair = sequencePair;
                if (outputColorMode) {
                    ColorSpaceConverter.convert(transformedSequence, colorSpaceBuffer, referenceConversion);
                    transformedSequence = colorSpaceBuffer;
                    if (processPairInThisRead) {
                        ColorSpaceConverter.convert(transformedSequencePair, colorSpaceBuffer,
                                referenceConversion);
                        transformedSequencePair = colorSpaceBuffer;
                    }
                }
                if (outputFakeNtMode) {
                    for (int i = 0; i < transformedSequence.length(); i++) {
                        transformedSequence.charAt(i, getFakeNtCharacter(transformedSequence.charAt(i)));
                    }
                    if (processPairInThisRead) {
                        for (int i = 0; i < transformedSequencePair.length(); i++) {
                            transformedSequencePair.charAt(i,
                                    getFakeNtCharacter(transformedSequencePair.charAt(i)));
                        }
                    }
                }
                if (trimAdaptorLength > 0) {
                    transformedSequence = transformedSequence.substring(trimAdaptorLength);
                    if (processPairInThisRead) {
                        transformedSequencePair = transformedSequencePair.substring(trimAdaptorLength);
                    }
                }
                // filter unrecognized bases from output
                if (alphabet != null) {
                    for (int i = 0; i < transformedSequence.length(); i++) {
                        if (alphabet.indexOf(transformedSequence.charAt(i)) == -1) {
                            transformedSequence.charAt(i, 'N');
                        }
                    }
                }
                if (processPairInThisRead) {
                    if (alphabet != null) {

                        for (int i = 0; i < transformedSequencePair.length(); i++) {
                            if (alphabet.indexOf(transformedSequencePair.charAt(i)) == -1) {
                                transformedSequencePair.charAt(i, 'N');
                            }
                        }
                    }
                }
                writeSequence(writer, transformedSequence, fastaLineLength);
                if (processPairInThisRead) {
                    writeSequence(pairWriter, transformedSequencePair, fastaLineLength);
                }
                if (outputFormat == OutputFormat.FASTQ) {
                    final int readLength = transformedSequence.length();
                    final byte[] qualityScores = readEntry.getQualityScores().toByteArray();
                    final boolean hasQualityScores = readEntry.hasQualityScores()
                            && !ArrayUtils.isEmpty(qualityScores);
                    writeQualityScores(writer, hasQualityScores, qualityScores, outputFakeQualityMode,
                            readLength);

                    if (processPairInThisRead) {
                        final int readLengthPair = transformedSequencePair.length();
                        final byte[] qualityScoresPair = readEntry.getQualityScoresPair().toByteArray();
                        final boolean hasPairQualityScores = readEntry.hasQualityScoresPair()
                                && !ArrayUtils.isEmpty(qualityScoresPair);
                        writeQualityScores(pairWriter, hasPairQualityScores, qualityScoresPair,
                                outputFakeQualityMode, readLengthPair);

                    }
                }
                ++numberOfFilteredSequences;

                progress.lightUpdate();
                ++numberOfSequences;
            }

        }
    } finally {
        IOUtils.closeQuietly(writer);
        if (processPairs) {
            IOUtils.closeQuietly(pairWriter);
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) { // NOPMD
                // silently ignore
            }
        }
    }

    progress.stop();
}

From source file:com.wentam.defcol.connect_to_computer.HomeCommandHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, HttpContext httpContext)
        throws HttpException, IOException {
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            String req = request.getRequestLine().getUri();

            req = req.replaceAll("/\\?", "");

            String[] pairs = req.split("&");

            HashMap data = new HashMap();

            for (int i = 0; i < pairs.length; i++) {
                if (pairs[i].contains("=")) {
                    String[] pair = pairs[i].split("=");
                    data.put(pair[0], pair[1]);
                }/*from   w w  w .  j  a  va2 s.  c om*/
            }

            String action = "none";
            if (data.containsKey("action")) {
                action = (String) data.get("action");
            }

            String resp = "404 on " + action;
            if (action.equals("none") || action.equals("home")) {
                response.setHeader("Content-Type", "text/html");

                resp = getHtml();

            } else if (action.equals("getPalettes")) {
                response.setHeader("Content-Type", "application/json");

                JSONArray json = new JSONArray();

                int tmp[] = { 0 };
                ArrayList<String> palettes = pFile.getRows(tmp);
                Iterator i = palettes.iterator();
                while (i.hasNext()) {
                    JSONObject item = new JSONObject();
                    try {
                        item.put("name", i.next());
                    } catch (JSONException e) {
                    }
                    json.put(item);
                }

                resp = json.toString();

            } else if (action.equals("getJquery")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = jquery;
            } else if (action.equals("getJs")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = getJs();
            } else if (action.equals("getPaletteColors")) {
                response.setHeader("Content-Type", "application/javascript");
                int id = Integer.parseInt((String) data.get("id"));

                int tmp[] = { 1 };
                String row = pFile.getRow(id, tmp);

                String colors[] = row.split("\\.");

                JSONArray json = new JSONArray();

                for (int i = 0; i < colors.length; i++) {
                    json.put(colors[i]);
                }

                resp = json.toString();
            }

            writer.write(resp);
            writer.flush();
        }
    });

    response.setEntity(entity);
}

From source file:net.exclaimindustries.geohashdroid.services.WikiService.java

@Override
protected void serializeToDisk(Intent i, OutputStream os) {
    // We'll encode one line per object, with the last lines reserved for
    // the entire message (the only thing of these that can have multiple
    // lines)./*from   w w w .  j  av a2 s .c o  m*/
    OutputStreamWriter osw = new OutputStreamWriter(os);
    StringBuilder builder = new StringBuilder();

    // Always write out the \n, even if it's null.  An empty line will be
    // deserialized as a null.  Yes, even if that'll cause an error later.

    // The date can come in as a long.
    Calendar c = (Calendar) i.getParcelableExtra(EXTRA_TIMESTAMP);
    if (c != null)
        builder.append(c.getTimeInMillis());
    builder.append('\n');

    // The location is just two doubles.  Split 'em with a colon.
    Location loc = (Location) i.getParcelableExtra(EXTRA_LOCATION);
    if (loc != null)
        builder.append(Double.toString(loc.getLatitude())).append(':')
                .append(Double.toString(loc.getLongitude()));
    builder.append('\n');

    // The image is just a URI.  Easy so far.
    Uri uri = (Uri) i.getParcelableExtra(EXTRA_IMAGE);
    if (uri != null)
        builder.append(uri.toString());
    builder.append('\n');

    // And now comes Info.  It encompasses two doubles (the destination),
    // a Date (the date of the expedition), and a Graticule (two ints
    // and two booleans).  The Graticule part can be null if this is a
    // globalhash.
    Info info = (Info) i.getParcelableExtra(EXTRA_INFO);
    if (info != null) {
        builder.append(Double.toString(info.getLatitude())).append(':')
                .append(Double.toString(info.getLongitude())).append(':')
                .append(Long.toString(info.getDate().getTime())).append(':');

        if (!info.isGlobalHash()) {
            Graticule g = info.getGraticule();
            builder.append(Integer.toString(g.getLatitude())).append(':').append(g.isSouth() ? '1' : '0')
                    .append(':').append(Integer.toString(g.getLongitude())).append(':')
                    .append((g.isWest() ? '1' : '0'));
        }
    }
    builder.append('\n');

    // The rest of it is the message.  We'll URI-encode it so it comes out
    // as a single string without line breaks.
    String message = i.getStringExtra(EXTRA_MESSAGE);
    if (message != null)
        builder.append(Uri.encode(message));

    // Right... let's write it out.
    try {
        osw.write(builder.toString());
    } catch (IOException e) {
        // If we got an exception, we're in deep trouble.
        Log.e(DEBUG_TAG, "Exception when serializing an Intent!", e);
    }
}

From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java

/**
 * // w ww  . j  a v  a  2 s. com
 * also @see com.compositesw.ps.deploytool.dao.RegressionPubTestDAO#executeWs(com.compositesw.ps.deploytool.dao.RegressionPubTestDAO.Item, String, String)
 */
public static int executeWs(RegressionItem item, String outputFile, CompositeServer cisServerConfig,
        RegressionTestType regressionConfig, String delimiter, String printOutputType)
        throws CompositeException {
    // Set the command and action name
    String command = "executeWs";
    String actionName = "REGRESSION_TEST";

    // Check the input parameter values:
    if (cisServerConfig == null || regressionConfig == null) {
        throw new CompositeException(
                "XML Configuration objects are not initialized when trying to run Regression test.");
    }

    URLConnection urlConn = null;
    BufferedReader rd = null;
    OutputStreamWriter wr = null;
    int rows = 0;
    String host = cisServerConfig.getHostname();
    int wsPort = cisServerConfig.getPort(); // port in servers.xml defines WS port
    boolean useHttps = cisServerConfig.isUseHttps();

    // Execute the webservice
    try {
        // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
        if (CommonUtils.isExecOperation()) {
            boolean encrypt = item.encrypt;
            // Override the encrypt flag when useHttps is set from an overall PDTool over SSL (https) setting.
            if (useHttps && !encrypt) {
                encrypt = true;
                RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                        "The regression input file encrypt=false has been overridden by useHttps=true for path="
                                + item.path,
                        "");
            }

            String urlString = "http://" + host + ":" + wsPort + item.path;
            if (encrypt) {
                urlString = "https://" + host + ":" + (wsPort + 2) + item.path;
            }
            RegressionManagerUtils.printOutputStr(printOutputType, "summary", "urlString=" + urlString, "");
            URL url = new URL(urlString);
            urlConn = url.openConnection();
            if (encrypt) {
                // disable hostname verification
                ((HttpsURLConnection) urlConn).setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String urlHostName, SSLSession session) {
                        return true;
                    }
                });

            }
            // 2014-02-09 (mtinius) - added basic authorization to allow for connections with new users
            String credentials = cisServerConfig.getUser() + ":"
                    + CommonUtils.decrypt(cisServerConfig.getPassword());
            String encoded = Base64EncodeDecode.encodeString(credentials);
            urlConn.setRequestProperty("Authorization", "Basic " + encoded);

            urlConn.setRequestProperty("SOAPAction", item.action);
            urlConn.setRequestProperty("Content-Type", item.contentType);
            urlConn.setDoOutput(true);

            wr = new OutputStreamWriter(urlConn.getOutputStream());
            wr.write(item.input);
            wr.flush();

            // Get the response
            rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String line;
            StringBuffer buf = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                rows++;
                buf.append(line);
                if (outputFile != null)
                    CommonUtils.appendContentToFile(outputFile, line);
            }
            line = buf.toString();
            RegressionManagerUtils.printOutputStr(printOutputType, "results", line, "");
            if (line.indexOf("<fault") >= 0 || line.indexOf(":fault") >= 0) {
                if (rd != null) {
                    rd.close();
                }
                if (wr != null) {
                    wr.close();
                }
                throw new IllegalStateException("Fault encountered.");
            }
            if (line.trim().length() == 0) {
                if (rd != null) {
                    rd.close();
                }
                if (wr != null) {
                    wr.close();
                }
                throw new IllegalStateException("No response document.");
            }
            urlConn.getInputStream().close();
            //              urlConn.getOutputStream().flush();
            wr.close();
            rd.close();
            RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeWs()", "");
        } else {
            logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                    + "] WAS NOT PERFORMED.\n");
        }

        return rows;
    } catch (IOException e) {
        try {
            HttpURLConnection httpConn = (HttpURLConnection) urlConn;
            BufferedReader brd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
            String line;
            StringBuffer buf = new StringBuffer();
            while ((line = brd.readLine()) != null) {
                buf.append(line + "\n");
            }
            brd.close();
            String error = buf.toString();
            throw new ApplicationException("executeWs(): " + error, e);

        } catch (Exception err) {
            String error = e.getMessage() + "\n" + "DETAILED_MESSAGE=[" + err.getMessage() + "]";
            //debug:               System.out.println("*************** ERROR ENCOUNTERED IN executeWs THREAD FOR TYPE:webservice *****************");
            throw new ApplicationException("executeWs(): " + error, err);
        }
    } finally {
        try {
            if (rd != null) {
                rd.close();
            }
            if (wr != null) {
                wr.close();
            }
        } catch (Exception e) {
            rd = null;
            wr = null;
            throw new CompositeException(
                    "executeWs(): unable to close BufferedReader (rd) and OutputStreamWriter (wr): "
                            + e.getMessage());
        }
    }
}

From source file:com.MainFiles.Functions.java

public String getCustomerDetails(String strAccountNumber) throws IOException {
    String[] strCustomerNameArray;
    String strCustomerName = "";
    String fname = "";
    String mname = "";
    String lname = "";
    try {// w  w  w  .j a va2  s .c om
        URL url = new URL(CUSTOMER_DETAILS_URL);
        Map<String, String> params = new LinkedHashMap<>();

        params.put("username", CUSTOMER_DETAILS_USERNAME);
        params.put("password", CUSTOMER_DETAILS_PASSWORD);
        params.put("source", CUSTOMER_DETAILS_SOURCE_ID);
        params.put("account", strAccountNumber);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        String urlParameters = postData.toString();
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String result = "";
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        while ((line = reader.readLine()) != null) {
            result += line;
        }
        writer.close();
        reader.close();

        JSONObject respobj = new JSONObject(result);
        if (respobj.has("FSTNAME") || respobj.has("MIDNAME") || respobj.has("LSTNAME")) {
            if (respobj.has("FSTNAME")) {
                fname = respobj.get("FSTNAME").toString().toUpperCase() + ' ';
            }
            if (respobj.has("MIDNAME")) {
                mname = respobj.get("MIDNAME").toString().toUpperCase() + ' ';
            }
            if (respobj.has("LSTNAME")) {
                lname = respobj.get("LSTNAME").toString().toUpperCase() + ' ';
            }
            strCustomerName = fname + mname + lname;
        } else {
            strCustomerName = "N/A";
        }

    } catch (Exception ex) {
        this.log("\nINFO : Function getCustomerDetails() " + ex.getMessage() + "\n" + this.StackTraceWriter(ex),
                "ERROR");
    }

    // System.out.println(strCustomerName);
    return strCustomerName;
}

From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

public void getRawTextFromUrlIfNeeded(DocumentPojo doc, SourceRssConfigPojo feedConfig) throws IOException {
    if (null != doc.getFullText()) { // Nothing to do
        return;/*  w  w w  . j a  v  a2s.  c o m*/
    }
    Scanner s = null;
    OutputStreamWriter wr = null;
    try {
        URL url = new URL(doc.getUrl());
        URLConnection urlConnect = null;
        String postContent = null;
        if (null != feedConfig) {
            urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
            if (null != feedConfig.getUserAgent()) {
                urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
            } // TESTED (by hand)
            if (null != feedConfig.getHttpFields()) {
                for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                    if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                        postContent = httpFieldPair.getValue();
                        urlConnect.setDoInput(true);
                        urlConnect.setDoOutput(true);
                    } else {
                        urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                    }
                }
            } //TESTED (by hand)
        } else {
            urlConnect = url.openConnection();
        }
        InputStream urlStream = null;
        try {
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } catch (SecurityException se) {
            throw se;
        } catch (Exception e) { // Try one more time, this time exception out all the way
            securityManager.setSecureFlag(false); // (some file stuff - so need to re-enable)
            if (null != feedConfig) {
                urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
                if (null != feedConfig.getUserAgent()) {
                    urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
                } // TESTED
                if (null != feedConfig.getHttpFields()) {
                    for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                        if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                            urlConnect.setDoInput(true); // (need to do this again)
                            urlConnect.setDoOutput(true);
                        } else {
                            urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                        }
                    }
                } //TESTED
            } else {
                urlConnect = url.openConnection();
            }
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } finally {
            securityManager.setSecureFlag(false); // (turn security check for local URL/file access off)
        }
        // Grab any interesting header fields
        Map<String, List<String>> headers = urlConnect.getHeaderFields();
        BasicDBObject metadataHeaderObj = null;
        for (Map.Entry<String, List<String>> it : headers.entrySet()) {
            if (null != it.getKey()) {
                if (it.getKey().startsWith("X-") || it.getKey().startsWith("Set-")
                        || it.getKey().startsWith("Location")) {
                    if (null == metadataHeaderObj) {
                        metadataHeaderObj = new BasicDBObject();
                    }
                    metadataHeaderObj.put(it.getKey(), it.getValue());
                }
            }
        } //TESTED
          // Grab the response code
        try {
            HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect;
            int responseCode = httpUrlConnect.getResponseCode();
            if (200 != responseCode) {
                if (null == metadataHeaderObj) {
                    metadataHeaderObj = new BasicDBObject();
                }
                metadataHeaderObj.put("responseCode", String.valueOf(responseCode));
            }
        } //TESTED
        catch (Exception e) {
        } // interesting, not an HTTP connect ... shrug and carry on
        if (null != metadataHeaderObj) {
            doc.addToMetadata("__FEED_METADATA__", metadataHeaderObj);
        } //TESTED
        s = new Scanner(urlStream, "UTF-8");
        doc.setFullText(s.useDelimiter("\\A").next());
    } catch (MalformedURLException me) { // This one is worthy of a more useful error message
        throw new MalformedURLException(me.getMessage()
                + ": Likely because the document has no full text (eg JSON) and you are calling a contentMetadata block without setting flags:'m' or 'd'");
    } finally { //(release resources)
        if (null != s) {
            s.close();
        }
        if (null != wr) {
            wr.close();
        }
    }

}

From source file:graphene.rest.ws.impl.UDSessionRSImpl.java

private String saveSessionToFile(final String rootName, final String sessionData) {

    String response = "{ id: \"TBD\", error:\"no error\" }";
    String errormsg = null;/*from   w  w w.jav  a2 s. com*/

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    // DEBUG
    logger.debug("saveSessionToFile: sessionData received =");
    logger.debug(sessionData);

    // Create the file on the Web Server
    File filedir = null;
    File file = null;

    // sessionId has this format:
    // userId + "_" + sessionname + "_" + new Date().getTime()).toString()

    String basepath = null;

    // sessionData should contain the following at the beginning
    // {
    // name: "xxx", - Name of the session
    // userId: "yyy", - unique user id for the associated user
    // lastUpdated: "zzz", - Date and timestamp (in milliseconds) when the
    // session was saved by the user
    // sessionActions: ....

    final int indxName = sessionData.indexOf("name");
    final int indxuserId = sessionData.indexOf("userId");
    final int indxDate = sessionData.indexOf("lastUpdated");
    final int indxAfterDate = sessionData.indexOf("sessionActions");
    if ((indxName < 0) || (indxuserId < 0) || (indxDate < 0) || (indxAfterDate < 0)) {
        errormsg = "saveSessionToFile: Invalid session data was received, unable to save it.";
        logger.error(errormsg);
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    String sessionName = sessionData.substring(indxName + 5, indxuserId - 1);
    sessionName = sessionName.replace("\"", "");
    sessionName = sessionName.replace(",", "");
    sessionName = sessionName.trim();

    String userId = sessionData.substring(indxuserId + 7, indxDate - 1);
    userId = userId.replace("\"", "");
    userId = userId.replace(",", "");
    userId = userId.trim();

    String lastUpdated = sessionData.substring(indxDate + 12, indxAfterDate - 1);
    lastUpdated = lastUpdated.replace("\"", "");
    lastUpdated = lastUpdated.replace(",", "");
    lastUpdated = lastUpdated.trim();

    if (servletContext != null) {
        basepath = servletContext.getRealPath("/");
    }

    // TODO the file should be placed under the webserver's dir
    if (basepath == null) {
        // TODO - handle case if the Server is Linux instead of Windows
        basepath = "C:/Windows/Temp"; // Temp hack
    }

    try {
        writer.write(sessionData);
    } catch (final IOException e) {
        errormsg = "saveSessionToFile: Server Exception writing session JSON data";
        logger.error(errormsg);
        logger.error(e.getMessage());
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    try {
        writer.close();
        outputStream.flush();
        outputStream.close();
    } catch (final java.io.IOException e) {
        errormsg = "saveSessionToFile: I/O Exception when attempting to close output after write. Details "
                + e.getMessage();
        logger.error(errormsg);
        logger.error(e.getMessage());
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    // Files are written as:
    // <basepath>/UDS/<userId>/<sessionname>_<date>
    final String serverPathName = basepath + "/" + rootName + "/" + userId;
    final String serverfileName = sessionName + "_" + lastUpdated + ".txt";

    // DEBUG
    logger.debug(
            "saveSessionToFile: serverPathName = " + serverPathName + ", serverfileName = " + serverfileName);

    try {
        filedir = new File(serverPathName);
        filedir.setWritable(true);
        filedir.mkdirs();

        file = new File(serverPathName + "/" + serverfileName);
        final FileOutputStream fout = new FileOutputStream(file);
        fout.write(outputStream.toByteArray());
        fout.close();
        // String finalPath = file.toURI().toString();
        // finalPath = finalPath.replace("file:/", ""); // remove leading

    } catch (final Exception fe) {
        errormsg = "saveSessionToFile: Failed to create file for session data. Details: "
                + fe.getLocalizedMessage();
        logger.error(errormsg);
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    // set the unique id of the response
    final String sessionId = createSessionId(userId, sessionName, lastUpdated);

    response = "{ id: \"" + sessionId + "\", error:\"no error\" }";
    return response;
}

From source file:cgeo.geocaching.cgBase.java

public static void postTweet(cgeoapplication app, cgSettings settings, String status, final Geopoint coords) {
    if (app == null) {
        return;//  w ww  .  j  a  v a2s  .c om
    }
    if (settings == null || StringUtils.isBlank(settings.tokenPublic)
            || StringUtils.isBlank(settings.tokenSecret)) {
        return;
    }

    try {
        Map<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (coords != null) {
            parameters.put("lat", String.format("%.6f", coords.getLatitude()));
            parameters.put("long", String.format("%.6f", coords.getLongitude()));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}

From source file:cgeo.geocaching.cgBase.java

public static String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    //String httpLocation = null;

    if (method == null) {
        method = "GET";
    } else {/*from w w w. j  a va2 s . c  o m*/
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                InputStream ins = getInputstreamFromConnection(connection);
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr, 1024);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(cgSettings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(cgSettings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (StringUtils.isNotBlank(buffer)) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    //This is reported as beeing deadCode (httpLocation is always null)
    //2011-08-09 - 302 is redirect so something should probably be done
    /*
     * if (httpCode == 302 && httpLocation != null) {
     * final Uri newLocation = Uri.parse(httpLocation);
     * if (newLocation.isRelative()) {
     * page = requestJSONgc(host, path, params);
     * } else {
     * page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
     * }
     * } else {
     */
    replaceWhitespace(buffer);
    page = buffer.toString();
    //}

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:FourByFour.java

public void actionPerformed(ActionEvent event) {

    Object target = event.getSource();

    // Process the button events.
    if (target == skill_return_button) {
        skill_panel.setVisible(false);//from w  w w  . ja  v a 2  s  .c o  m
        skill_return_button.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
        newGame();
    } else if (target == winner_return_button) {
        if (winner_flag) {
            String name = winner_name.getText();
            String tmp_name = new String("");
            int tmp_score = 0;
            boolean insert_flag = false;
            winner_flag = false;
            for (int i = 0; i < 20; i++) {
                if (insert_flag) {
                    name = names[i];
                    score = scores[i];
                    names[i] = tmp_name;
                    scores[i] = tmp_score;
                    tmp_name = name;
                    tmp_score = score;
                }
                if (!insert_flag && score > scores[i]) {
                    tmp_name = names[i];
                    tmp_score = scores[i];
                    scores[i] = score;
                    names[i] = name;
                    insert_flag = true;
                }
                high_names[i].setText(names[i]);
                high_scores[i].setText(Integer.toString(scores[i]));
            }
            scoresString = new String("");
            int place;
            for (int i = 0; i < 20; i++) {
                place = (int) places[i];
                scoresString += Integer.toString(place);
                scoresString += "\t";
                scoresString += names[i];
                scoresString += "   ";
                scoresString += Integer.toString(scores[i]);
                scoresString += "\n";
            }

            if (appletFlag) {
                // Use this section of code when writing the high
                // scores file back to a server. Requires the use
                // of a deamon on the server to receive the socket
                // connection.
                //
                // Create the output stream.
                // try {
                //    Socket socket = new Socket(host, port);
                //    outStream = new BufferedOutputStream
                //       (socket.getOutputStream(), 8192);
                // }
                // catch(IOException ioe) {
                //    System.out.println("Error: " + ioe.toString());
                // }
                // System.out.println("Output stream opened");
                //
                // Write the scores to the file back on the server.
                // outText = scoresString.getBytes();
                // try {
                //    outStream.write(outText);
                //    outStream.flush();
                //    outStream.close();
                //    outStream = null;
                // }
                // catch (IOException ioe) {
                //    System.out.println("Error: " + ioe.toString());
                // }
                // System.out.println("Output stream written");

                try {
                    OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream("scores.txt"));
                    outFile.write(scoresString);
                    outFile.flush();
                    outFile.close();
                    outFile = null;
                } catch (IOException ioe) {
                    System.out.println("Error: " + ioe.toString());
                } catch (Exception e) {
                    System.out.println("Error: " + e.toString());
                }
            } else {

                try {
                    OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream("scores.txt"));
                    outFile.write(scoresString);
                    outFile.flush();
                    outFile.close();
                    outFile = null;
                } catch (IOException ioe) {
                    System.out.println("Error: " + ioe.toString());
                }
            }
        }
        winner_panel.setVisible(false);
        winner_return_button.setVisible(false);
        winner_label.setVisible(false);
        winner_score_label.setVisible(false);
        winner_name_label.setVisible(false);
        winner_top_label.setVisible(false);
        winner_name.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == high_return_button) {
        high_return_button.setVisible(false);
        high_panel.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == instruct_return_button) {
        instruct_text.setVisible(false);
        instruct_return_button.setVisible(false);
        instruct_text.repaint();
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == undo_button) {
        board.undo_move();
        canvas2D.repaint();
    } else if (target == instruct_button) {
        c_container.setVisible(false);
        b_container.setVisible(false);
        instruct_text.setVisible(true);
        instruct_return_button.setVisible(true);
    } else if (target == new_button) {
        newGame();
    } else if (target == skill_button) {
        c_container.setVisible(false);
        b_container.setVisible(false);
        skill_panel.setVisible(true);
        skill_return_button.setVisible(true);
    } else if (target == high_button) {
        // Read the high scores file.
        if (appletFlag) {
            try {
                inStream = new BufferedInputStream(new URL(getCodeBase(), "scores.txt").openStream(), 8192);
                Reader read = new BufferedReader(new InputStreamReader(inStream));
                StreamTokenizer st = new StreamTokenizer(read);
                st.whitespaceChars(32, 44);
                st.eolIsSignificant(false);

                int count = 0;
                int token = st.nextToken();
                boolean scoreFlag = true;
                String string;
                while (count < 20) {
                    places[count] = (int) st.nval;
                    string = new String("");
                    token = st.nextToken();
                    while (token == StreamTokenizer.TT_WORD) {
                        string += st.sval;
                        string += " ";
                        token = st.nextToken();
                    }
                    names[count] = string;
                    scores[count] = (int) st.nval;
                    token = st.nextToken();
                    count++;
                }
                inStream.close();
            } catch (Exception ioe) {
                System.out.println("Error: " + ioe.toString());
            }
        } else {
            try {
                inStream = new BufferedInputStream(new FileInputStream("scores.txt"));
                Reader read = new BufferedReader(new InputStreamReader(inStream));
                StreamTokenizer st = new StreamTokenizer(read);
                st.whitespaceChars(32, 44);
                st.eolIsSignificant(false);

                int count = 0;
                int token = st.nextToken();
                boolean scoreFlag = true;
                String string;
                while (count < 20) {
                    places[count] = (int) st.nval;
                    string = new String("");
                    token = st.nextToken();
                    while (token == StreamTokenizer.TT_WORD) {
                        string += st.sval;
                        string += " ";
                        token = st.nextToken();
                    }
                    names[count] = string;
                    scores[count] = (int) st.nval;
                    token = st.nextToken();
                    count++;
                }
                inStream.close();
            } catch (Exception ioe) {
                System.out.println("Error: " + ioe.toString());
            }
        }
        c_container.setVisible(false);
        b_container.setVisible(false);
        high_panel.setVisible(true);
        high_return_button.setVisible(true);
    }

    Checkbox box = group.getSelectedCheckbox();
    String label = box.getLabel();
    if (label.equals("Babe in the Woods        ")) {
        board.set_skill_level(0);
    } else if (label.equals("Walk and Chew Gum        ")) {
        board.set_skill_level(1);
    } else if (label.equals("Jeopardy Contestant      ")) {
        board.set_skill_level(2);
    } else if (label.equals("Rocket Scientist         ")) {
        board.set_skill_level(3);
    } else if (label.equals("Be afraid, be very afraid")) {
        board.set_skill_level(4);
    }
}