Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:at.kc.tugraz.ss.serv.job.dataexport.impl.SSDataExportImpl.java

@Override
public void dataExportUserEntityTagCategoryTimestamps(final SSServPar parA) throws Exception {

    final SSDataExportUserEntityTagCategoryTimestampPar par = new SSDataExportUserEntityTagCategoryTimestampPar(
            parA);/*from  w ww.  ja v a 2  s  . c  o m*/
    CSVWriter fileWriter = null;
    FileOutputStream out = null;
    OutputStreamWriter writer = null;

    try {

        final Map<String, List<SSUri>> usersResources = new HashMap<>();
        final Map<String, List<String>> tagsPerEntities = new HashMap<>();
        final Map<String, List<String>> categoriesPerEntities = new HashMap<>();
        final List<String> lineParts = new ArrayList<>();
        final List<String> allUsers;
        SSUri user;
        String resourceString;

        out = SSFileU.openOrCreateFileWithPathForWrite(SSFileU.dirWorkingDataCsv() + par.fileName);
        writer = new OutputStreamWriter(out, Charset.forName(SSEncodingU.utf8.toString()));
        fileWriter = new CSVWriter(writer, SSStrU.semiColon.charAt(0));

        try {
            allUsers = SSStrU.toStr(SSServCaller.userAll(false));
        } catch (SSErr error) {

            switch (error.code) {
            case notServerServiceForOpAvailable:
                SSLogU.warn(error.getMessage());
                return;
            default:
                SSServErrReg.regErrThrow(error);
                return;
            }
        }

        for (SSServContainerI serv : SSServReg.inst.getServsGatheringUsersResources()) {
            ((SSUsersResourcesGathererI) serv.serv()).getUsersResources(allUsers, usersResources);
        }

        for (Map.Entry<String, List<SSUri>> resourcesForUser : usersResources.entrySet()) {

            user = SSUri.get(resourcesForUser.getKey());

            tagsPerEntities.clear();
            categoriesPerEntities.clear();

            if (par.exportTags) {
                tagsPerEntities.putAll(SSDataExportFct.getTagsOfUserPerEntities(user,
                        resourcesForUser.getValue(), par.usePrivateTagsToo));
            }

            if (par.exportCategories) {
                categoriesPerEntities.putAll(SSDataExportFct.getCategoriesPerEntities(tagsPerEntities.size()));
            }

            for (SSUri resource : resourcesForUser.getValue()) {

                resourceString = SSStrU.toStr(resource);

                lineParts.clear();

                lineParts.add(SSStrU.toStr(user));
                lineParts.add(SSStrU.toStr(resource));
                lineParts.add(SSStrU.toStr(SSDateU.dateAsLong() / 1000)); //TODO: provide tag time stamps for tags

                if (tagsPerEntities.containsKey(resourceString)) {
                    lineParts.add(StringUtils.join(tagsPerEntities.get(resourceString), SSStrU.comma));
                } else {
                    lineParts.add(SSStrU.empty);
                }

                if (categoriesPerEntities.containsKey(resourceString)) {
                    lineParts.add(StringUtils.join(categoriesPerEntities.get(resourceString), SSStrU.comma));
                } else {
                    lineParts.add(SSStrU.empty);
                }

                fileWriter.writeNext((String[]) lineParts.toArray(new String[lineParts.size()]));
            }
        }
    } catch (Exception error) {
        SSServErrReg.regErrThrow(error);
    } finally {

        if (fileWriter != null) {
            fileWriter.close();
        } else {

            if (writer != null) {
                writer.close();
            } else {

                if (out != null) {
                    out.close();
                }
            }
        }
    }
}

From source file:edu.gslis.ts.ThriftToTREC.java

/**
 * @param thriftFile//from www .ja v  a 2s.co m
 */
public Map<String, String> filter(File infile, File outfile, String parser) {
    Map<String, String> results = new TreeMap<String, String>();
    try {
        InputStream in = null;

        if (infile.getName().endsWith(".gz"))
            in = new GZIPInputStream(new FileInputStream(infile));
        else if (infile.getName().endsWith("xz"))
            in = new XZInputStream(new FileInputStream(infile));
        else
            in = new FileInputStream(infile);

        TTransport inTransport = new TIOStreamTransport(new BufferedInputStream(in));
        TBinaryProtocol inProtocol = new TBinaryProtocol(inTransport);
        inTransport.open();

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outfile, false), "UTF-8");
        try {
            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder decoder = charset.newDecoder();

            // Run through items in the thrift file
            while (true) {
                final StreamItem item = new StreamItem();
                item.read(inProtocol);
                if (item.body == null || item.body.clean_visible == null) {
                    continue;
                }

                String streamId = "";
                if (item.stream_id != null) {
                    streamId = item.stream_id;
                }

                String dateTime = "";
                long epochTime = 0;
                if (item.stream_time != null && item.stream_time.zulu_timestamp != null) {
                    dateTime = item.stream_time.zulu_timestamp;
                    DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
                    epochTime = dtf.parseMillis(dateTime);
                }

                String source = "";
                if (item.source != null) {
                    source = item.source;
                }

                String url = "";
                if (item.abs_url != null) {
                    url = decoder.decode(item.abs_url).toString();
                }

                Map<String, List<Sentence>> parsers = item.body.sentences;
                List<Sentence> sentenceParser = parsers.get(parser);

                String sentencesText = "";
                int sentenceNum = 0;
                if (sentenceParser != null && sentenceParser.size() > 0) {

                    for (Sentence s : sentenceParser) {
                        List<Token> tokens = s.tokens;
                        String sentence = "";
                        for (Token token : tokens) {
                            String tok = token.token;
                            sentence += tok + " ";
                        }
                        sentencesText += sentenceNum + " " + sentence + "\n";
                        sentenceNum++;
                    }
                }

                try {
                    String hourDayDir = outfile.getName().replace(".txt", "");
                    out.write("<DOC>\n");
                    out.write("<DOCNO>" + streamId + "</DOCNO>\n");
                    out.write("<SOURCE>" + source + "</SOURCE>\n");
                    out.write("<URL>" + url + "</URL>\n");
                    out.write("<DATETIME>" + dateTime + "</DATETIME>\n");
                    out.write("<HOURDAYDIR>" + hourDayDir + "</HOURDAYDIR>\n");
                    out.write("<EPOCH>" + epochTime + "</EPOCH>\n");
                    out.write("<TEXT>\n" + sentencesText + "\n</TEXT>\n");
                    out.write("</DOC>\n");
                } catch (Exception e) {
                    System.out.println("Error processing " + infile.getAbsolutePath() + " " + item.stream_id);
                    e.printStackTrace();
                }

            }
        } catch (TTransportException te) {
            if (te.getType() == TTransportException.END_OF_FILE) {
            } else {
                throw te;
            }
        }
        inTransport.close();
        out.close();

    } catch (Exception e) {
        System.out.println("Error processing " + infile.getName());
        e.printStackTrace();
    }
    return results;
}

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. j av  a 2  s .  c o  m*/

    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:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java

/**
 * /*from   w w  w.ja  v  a  2  s  .c  o  m*/
 * 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:cgeo.geocaching.cgBase.java

public static void postTweet(cgeoapplication app, cgSettings settings, String status, final Geopoint coords) {
    if (app == null) {
        return;/*  ww w  .  ja  v a2 s  .c  o m*/
    }
    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  av  a2s  .c  om*/
        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:dev.ukanth.ufirewall.Api.java

public static boolean saveAllPreferencesToFile(Context ctx) {
    boolean res = false;
    File sdCard = Environment.getExternalStorageDirectory();
    if (isExternalStorageWritable()) {
        File dir = new File(sdCard.getAbsolutePath() + "/afwall/");
        dir.mkdirs();//from  ww w  . j  a va 2  s.com
        File file = new File(dir, "backup_all.json");

        try {
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

            JSONObject exportObject = new JSONObject();
            //if multiprofile is enabled
            if (G.enableMultiProfile()) {
                JSONObject profileObject = new JSONObject();
                //store all the profile settings
                for (String profile : G.profiles) {
                    Map<String, JSONObject> exportMap = new HashMap<String, JSONObject>();
                    final SharedPreferences prefs = ctx.getSharedPreferences(profile, Context.MODE_PRIVATE);
                    updatePackage(ctx, prefs.getString(PREF_WIFI_PKG_UIDS, ""), exportMap, WIFI_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_3G_PKG_UIDS, ""), exportMap, DATA_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_ROAMING_PKG_UIDS, ""), exportMap, ROAM_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_VPN_PKG_UIDS, ""), exportMap, VPN_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_LAN_PKG_UIDS, ""), exportMap, LAN_EXPORT);
                    profileObject.put(profile, new JSONObject(exportMap));
                }
                exportObject.put("profiles", profileObject);

                //if any additional profiles
                int defaultProfileCount = 3;
                JSONObject addProfileObject = new JSONObject();
                for (String profile : G.getAdditionalProfiles()) {
                    defaultProfileCount++;
                    Map<String, JSONObject> exportMap = new HashMap<String, JSONObject>();
                    final SharedPreferences prefs = ctx
                            .getSharedPreferences("AFWallProfile" + defaultProfileCount, Context.MODE_PRIVATE);
                    updatePackage(ctx, prefs.getString(PREF_WIFI_PKG_UIDS, ""), exportMap, WIFI_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_3G_PKG_UIDS, ""), exportMap, DATA_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_ROAMING_PKG_UIDS, ""), exportMap, ROAM_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_VPN_PKG_UIDS, ""), exportMap, VPN_EXPORT);
                    updatePackage(ctx, prefs.getString(PREF_LAN_PKG_UIDS, ""), exportMap, LAN_EXPORT);
                    addProfileObject.put(profile, new JSONObject(exportMap));
                }
                exportObject.put("additional_profiles", addProfileObject);
            } else {
                //default Profile - current one
                JSONObject obj = new JSONObject(getCurrentRulesAsMap(ctx));
                exportObject.put("default", obj);
            }

            //now gets all the preferences
            exportObject.put("prefs", getAllAppPreferences(ctx, G.gPrefs));

            myOutWriter.append(exportObject.toString());
            res = true;
            myOutWriter.close();
            fOut.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d(TAG, e.getLocalizedMessage());
        } catch (JSONException e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
    }

    return res;
}

From source file:com.techventus.server.voice.Voice.java

/**
 * Use this login method to login - use captchaAnswer to answer a captcha challenge
 * @param pCaptchaAnswer (optional) String entered by the user as an answer to a CAPTCHA challenge. - null to make a normal login attempt
 * @param pCaptchaToken (optional) token which matches the response/url from the captcha challenge
 * @throws IOException if login encounters a connection error
 *//*  ww w . j  a va  2  s . c o  m*/
public void login(String pCaptchaAnswer, String pCaptchaToken) throws IOException {

    String data = URLEncoder.encode("accountType", enc) + "=" + URLEncoder.encode(account_type, enc);
    data += "&" + URLEncoder.encode("Email", enc) + "=" + URLEncoder.encode(user, enc);
    data += "&" + URLEncoder.encode("Passwd", enc) + "=" + URLEncoder.encode(pass, enc);
    data += "&" + URLEncoder.encode("service", enc) + "=" + URLEncoder.encode(SERVICE, enc);
    data += "&" + URLEncoder.encode("source", enc) + "=" + URLEncoder.encode(source, enc);
    if (pCaptchaAnswer != null && pCaptchaToken != null) {
        data += "&" + URLEncoder.encode("logintoken", enc) + "=" + URLEncoder.encode(pCaptchaToken, enc);
        data += "&" + URLEncoder.encode("logincaptcha", enc) + "=" + URLEncoder.encode(pCaptchaAnswer, enc);
    }

    // Send data
    URL url = new URL(loginURLString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("User-agent", USER_AGENT);

    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    conn.connect();
    int responseCode = conn.getResponseCode();
    if (PRINT_TO_CONSOLE)
        System.out.println(loginURLString + " - " + conn.getResponseMessage());
    InputStream is;
    if (responseCode == 200) {
        is = conn.getInputStream();
    } else {
        is = conn.getErrorStream();
    }
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader rd = new BufferedReader(isr);
    String line;
    String completelineDebug = "";

    /*
     * A failure response contains an error code and a URL to an error page that can be displayed to the user. 
     * If the error code is a CAPTCHA challenge, the response also includes a URL to a CAPTCHA image and a special 
     * token. Your application should be able to solicit an answer from the user and then retry the login request. 
     * To display the CAPTCHA image to the user, prefix the CaptchaUrl value with "http://www.google.com/accounts/", 
     * for example: " http://www.google.com/accounts/Captcha?ctoken=HiteT4b0Bk5Xg18_AcVoP6-yFkHPibe7O9EqxeiI7lUSN".
     */
    String lErrorString = "Unknown Connection Error."; // ex: Error=CaptchaRequired

    // String AuthToken = null;
    while ((line = rd.readLine()) != null) {
        completelineDebug += line + "\n";
        if (line.contains("Auth=")) {
            this.authToken = line.split("=", 2)[1].trim();
            if (PRINT_TO_CONSOLE) {
                System.out.println("Logged in to Google - Auth token received");
            }
        } else if (line.contains("Error=")) {
            lErrorString = line.split("=", 2)[1].trim();
            //error = getErrorEnumByCode(lErrorString);
            error = ERROR_CODE.valueOf(lErrorString);
            if (PRINT_TO_CONSOLE)
                System.out.println("Login error - " + lErrorString);

        }
        if (line.contains("CaptchaToken=")) {
            captchaToken = line.split("=", 2)[1].trim();
        }

        if (line.contains("CaptchaUrl=")) {
            captchaUrl = "http://www.google.com/accounts/" + line.split("=", 2)[1].trim();
        }
        if (line.contains("Url=")) {
            captchaUrl2 = line.split("=", 2)[1].trim();
        }

    }
    wr.close();
    rd.close();

    //      if (PRINT_TO_CONSOLE){
    //         System.out.println(completelineDebug);
    //      }

    if (this.authToken == null) {
        AuthenticationException.throwProperException(error, captchaToken, captchaUrl);
    }

    String response = this.getRawPhonesInfo();
    int phoneIndex = response.indexOf("gc-user-number-value\">");
    this.phoneNumber = response.substring(phoneIndex + 22, phoneIndex + 36);
    this.phoneNumber = this.phoneNumber.replaceAll("[^a-zA-Z0-9]", "");
    if (this.phoneNumber.indexOf("+") == -1) {
        this.phoneNumber = "+1" + this.phoneNumber;
    }
}

From source file:com.denimgroup.threadfix.importer.cli.ScriptRunner.java

public long checkRunningAndFixStatements(String errorLogFile, String fixedSqlFile) {

    long errorCount = 0;

    File outputFixedScript = new File(fixedSqlFile);

    FileOutputStream fos = null;//from www. j a  v  a  2 s.  c  o m
    try {
        List<String> lines = FileUtils.readLines(new File(errorLogFile));

        if (lines != null && lines.size() > 1) {
            fos = new FileOutputStream(outputFixedScript);
            OutputStreamWriter osw = new OutputStreamWriter(fos);

            String preLine = null;
            Map<String, Object> map = new HashMap<>();
            osw.write("SET FOREIGN_KEY_CHECKS=0;\n");
            for (String currentLine : lines) {

                if (!currentLine.contains("Error executing: INSERT INTO")) {
                    // Remove all weird characters if they cause 'incorrect string value' SQLExeption
                    if (currentLine.toLowerCase().contains("incorrect string value")) {
                        if (preLine != null) {
                            String fixedStatement = preLine.replace("Error executing: ", "")
                                    .replaceAll("[^\\x00-\\x7F]", "");
                            osw.write(fixedStatement + ";\n");
                        }
                    }
                    // If there is unknown column, then delete that column and its value
                    else if (currentLine.contains("MySQLSyntaxErrorException: Unknown column")) {
                        osw.write(getFixedUnknownColStatement(currentLine,
                                preLine.replace("Error executing: ", "")));
                    }
                    // too long string for column, cut it off
                    else if (currentLine.contains("Data too long for column")) {
                        map = exactTableFromString(preLine);
                        if (map == null || map.isEmpty()) {
                            LOGGER.error("Unable to fix statement: " + preLine);
                            LOGGER.error("Error was: " + currentLine);
                            osw.write(preLine.replace("Error executing: ", "") + ";\n");
                            continue;
                        }
                        osw.write(fixLongColumnStatement(preLine, currentLine, map));
                    }
                    // Older version of MySQL doesn't take time with fraction like '2015-10-28 13:01:59.289000000'
                    else if (currentLine.contains("Data truncation: Incorrect datetime value")) {
                        osw.write(fixDateWrongStatement(preLine, currentLine));
                    } else if (currentLine.contains("Packet for query is too large")) {
                        LOGGER.error(currentLine);
                        if (preLine.contains("INSERT INTO DOCUMENT")) {
                            LOGGER.warn(
                                    "You have failed to import a big document. Please upload that document by ThreadFix UI.");
                            map = exactTableFromString(preLine);
                            if (map != null && !map.isEmpty()) {
                                Map<String, String> fieldMap = (Map) map.get("tableFields");
                                for (String key : fieldMap.keySet()) {
                                    if (!key.equalsIgnoreCase("file")) {
                                        LOGGER.warn(key + ": " + fieldMap.get(key));
                                    }
                                }
                            }
                        } else {
                            osw.write(preLine.replace("Error executing: ", "") + ";\n");
                        }
                    } else if (currentLine
                            .contains("MySQLSyntaxErrorException: You have an error in your SQL syntax; "
                                    + "check the manual that corresponds to your MySQL server version")) {
                        osw.write(fixSyntaxStatement(preLine.replace("Error executing: ", ""), currentLine));
                    }
                    // Unresolved-yet SQLException, then write whole statement to fixed Sql script
                    else {
                        if (preLine != null && preLine.contains("Error executing: INSERT INTO")) {
                            osw.write(preLine.replace("Error executing: ", "") + ";\n");
                        }
                    }
                } else {
                    errorCount += 1;
                }
                preLine = currentLine;
            }

            osw.write("SET FOREIGN_KEY_CHECKS=1;\n");
            osw.close();
        }
    } catch (IOException e) {
        LOGGER.error("Error", e);
    }
    return errorCount;
}

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);/* ww  w.  j a  v  a2s. co  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);
    }
}