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:com.megahardcore.config.messages.MessageConfig.java

/**
 * Set the header of the file before writing to it with bukkit yaml implementation
 *
 * @param file file to write the header to
 *///  ww w .  ja  va2s.  c  o m
private void setHeader(File file) {
    try {
        //Write header to a new file
        ByteArrayOutputStream memStream = new ByteArrayOutputStream();
        OutputStreamWriter memWriter = new OutputStreamWriter(memStream, Charset.forName("UTF-8").newEncoder());
        String[] header = { "Messages sent by MegaHardCore",
                "Messages are only sent for modules that are activated",
                "Modes (has to match exactly, ignores case)",
                "Disabled: Message won't be sent even if feature that would sent the message is active",
                "One_Time: Will be sent to every player only once",
                "Notification: Gets sent every time with a timeout to prevent spamming chat",
                "Tutorial: Sent a limited number of times and not displayed after 3 times",
                "Broadcast: Shown to whole server. Only few messages make sense to be broadcasted",
                "Variables:", "$ALLCAPS is a variable and will be filled in for some messages",
                "$PLAYER: Affected player", "$PLAYERS: If multiple players are affected",
                "$DEATH_MSG: Death message if someone dies", "$ITEMS: a player lost" };
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.repeat("#", 100));
        sb.append(System.lineSeparator());
        for (String line : header) {
            sb.append('#');
            sb.append(StringUtils.repeat(" ", 100 / 2 - line.length() / 2 - 1));
            sb.append(line);
            sb.append(StringUtils.repeat(" ", 100 / 2 - line.length() / 2 - 1 - line.length() % 2));
            sb.append('#');
            sb.append(String.format(System.lineSeparator()));
        }
        sb.append(StringUtils.repeat("#", 100));
        sb.append(String.format(System.lineSeparator()));
        //String.format: %n as platform independent line seperator
        memWriter.write(sb.toString());
        memWriter.close();

        IoHelper.writeHeader(file, memStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public void saveCookies() {
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;
    // make dirs/*w w  w  .j  ava2 s  . c  o m*/
    File dir1 = new File(this.main_aagtl.main_dir + "/config");
    dir1.mkdirs();
    // save cookies to file
    try {
        File cookie_file = new File(this.main_aagtl.main_dir + "/config/cookie.txt");
        fOut = new FileOutputStream(cookie_file);
        osw = new OutputStreamWriter(fOut);
        osw.write(cookie_jar.toString());
        osw.flush();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("saveCookies: Exception1");
    } finally {
        try {
            osw.close();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("saveCookies: Exception2");
        }
    }
}

From source file:study.tdcc.act.MainCalendar.java

/**
 * XML?????/*w  w  w.ja v  a2 s  .  com*/
 * 
 * @param strUrl
 * @param strXml
 * @param strMethod (PUT,DELETE)
 * @return InputStream ???InputStream
 */
public InputStream httpPostXml(String strUrl, String strXml, String strMethod) {
    Log.d("DEBUG", "MainCalendar httpPostXml Start");
    blHttpSucceeded = false;
    try {
        while (strUrl != null) {
            URL urlObj = new URL(strUrl);
            //URL?????
            HttpURLConnection httpURLCObj = (HttpURLConnection) urlObj.openConnection();
            //?POST?
            httpURLCObj.setRequestMethod("POST");
            //GData-Version?
            httpURLCObj.setRequestProperty(GDATA_VERSION_TAG, GDATA_VERSION);
            if (strMethod != null) {
                //POST??????If-Match:*?X-HTTP-Method-Override
                httpURLCObj.setRequestProperty("If-Match", "*");
                httpURLCObj.setRequestProperty("X-HTTP-Method-Override", strMethod);
            }
            //
            httpURLCObj.setDoOutput(true);
            //Content-Type??XML
            httpURLCObj.setRequestProperty("Content-Type", CONTENT_TYPE_AA);
            //
            httpURLCObj.setUseCaches(false);
            //OutputStreamWriter??XML??
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLCObj.getOutputStream(),
                    "UTF-8");
            outputStreamWriter.write(strXml);
            outputStreamWriter.close();
            //HTTP??
            intResponseCode = 0;
            intResponseCode = httpURLCObj.getResponseCode();
            strUrl = null;
            Log.d("DEBUG", "MainCalendar httpPostXml HttpResponseCode : " + intResponseCode);
            if (intResponseCode == HttpURLConnection.HTTP_OK
                    || intResponseCode == HttpURLConnection.HTTP_CREATED) {
                //??OK???CREATED?????
                blHttpSucceeded = true;
                Log.d("DEBUG", "MainCalendar httpPostXml End(1)");
                //?InputStream??
                return httpURLCObj.getInputStream();
            } else if (intResponseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                //??MOVED_TEMP?????????
                //?Location????URL????(?while?
                Map<String, List<String>> mResponseHeaders = httpURLCObj.getHeaderFields();
                if (mResponseHeaders.containsKey("Location")) {
                    strUrl = mResponseHeaders.get("Location").get(0);
                } else if (mResponseHeaders.containsKey("location")) {
                    strUrl = mResponseHeaders.get("location").get(0);
                }
            } else {
                //??OK???CREATED???MOVED_TEMP??
                blHttpSucceeded = false;
                Log.d("DEBUG",
                        "MainCalendar httpPostXml End(2)  ??OK,CREATED,MOVED_TEMP??");
            }
        }
    } catch (Exception e) {
        Log.e("ERROR", "MainCalendar httpPostXml ERROR", e);
    }
    Log.d("DEBUG", "MainCalendar httpPostXml End(3)");
    return null;
}

From source file:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java

/**
 * Saves the mets document into a file//from w  w  w.  j  a  v  a 2 s .c  o m
 *
 * @param mets
 * @param outputFile
 * @throws MetsExportException
 */
private void saveMets(Mets mets, File outputFile, IMetsElement metsElement) throws MetsExportException {
    String fileMd5Name;
    try {
        addFileGrpToMets(fileGrpMap);
        addStructLink();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Mets.class, OaiDcType.class,
                    ModsDefinition.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
            // marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
            // "http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2001/XMLSchema.xsd http://www.loc.gov/METS/ http://www.loc.gov/standards/mets/mets.xsd http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/mods.xsd http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd");
            marshaller.marshal(mets, outputFile);
            MessageDigest md;
            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new MetsExportException("Unable to create MD5 hash", false, e);
            }
            md.reset();
            InputStream is;
            try {
                is = new FileInputStream(outputFile);
            } catch (FileNotFoundException e) {
                throw new MetsExportException("Unable to open file:" + outputFile.getAbsolutePath(), false, e);
            }
            byte[] bytes = new byte[2048];
            int numBytes;
            long totalBytes = 0;
            try {
                while ((numBytes = is.read(bytes)) != -1) {
                    totalBytes = totalBytes + numBytes;

                    md.update(bytes, 0, numBytes);
                }
            } catch (IOException e) {
                throw new MetsExportException("Unable to generate MD5 hash", false, e);
            }
            byte[] digest = md.digest();
            String result = new String(Hex.encodeHex(digest));
            metsElement.getMetsContext().getFileList()
                    .add(new FileMD5Info("." + File.separator + outputFile.getName(), result, totalBytes));
            fileMd5Name = "MD5_" + MetsUtils.removeNonAlpabetChars(metsElement.getMetsContext().getPackageID())
                    + ".md5";
            File fileMd5 = new File(metsElement.getMetsContext().getOutputPath() + File.separator
                    + metsElement.getMetsContext().getPackageID() + File.separator + fileMd5Name);
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileMd5));
            for (FileMD5Info info : metsElement.getMetsContext().getFileList()) {
                osw.write(info.getMd5() + " " + info.getFileName() + "\n");
            }
            osw.close();
            is.close();

            // calculate md5 for md5file - it's inserted into info.xml
            is = new FileInputStream(fileMd5);
            FileMD5Info md5InfoMd5File = MetsUtils.getDigest(is);
            is.close();
            metsElement.getMetsContext().getFileList()
                    .add(new FileMD5Info("." + File.separator + fileMd5Name, null, fileMd5.length()));
            MetsUtils.saveInfoFile(metsElement.getMetsContext().getOutputPath(), metsElement.getMetsContext(),
                    md5InfoMd5File.getMd5(), fileMd5Name, outputFile);
        } catch (Exception ex) {
            throw new MetsExportException(metsElement.getOriginalPid(),
                    "Unable to save mets file:" + outputFile.getAbsolutePath(), false, ex);
        }
        List<String> validationErrors;
        try {
            validationErrors = MetsUtils.validateAgainstXSD(outputFile,
                    Mets.class.getResourceAsStream("mets.xsd"));
        } catch (Exception ex) {
            throw new MetsExportException("Error while validation document:" + outputFile, false, ex);
        }
        if (validationErrors.size() > 0) {
            MetsExportException metsException = new MetsExportException("Invalid mets file:" + outputFile,
                    false, null);
            metsException.getExceptions().get(0).setValidationErrors(validationErrors);
            for (String error : validationErrors) {
                LOG.fine(error);
            }
            throw metsException;
        }
        LOG.log(Level.FINE,
                "Element validated:" + metsElement.getOriginalPid() + "(" + metsElement.getElementType() + ")");
    } finally {
        JhoveUtility.destroyConfigFiles(metsElement.getMetsContext().getJhoveContext());
    }
    metsElement.getMetsContext().getGeneratedPSP().add(metsElement.getMetsContext().getPackageID());
}

From source file:TargetsAPI.java

/**
 * Send the POST request to the Wikitude Cloud Targets API.
 * //from  ww  w. ja  v a  2 s  .  co m
 * <b>Remark</b>: We are not using any external libraries for sending HTTP
 * requests, to be as independent as possible. Libraries like Apache
 * HttpComponents (included in Android already) make it a lot easier to
 * interact with HTTP connections.
 * 
 * @param body
 *            The JSON body that is sent in the request.
 * @return The response from the server, in JSON format
 * 
 * @throws IOException
 *             when the server cannot serve the request for any reason, or
 *             anything went wrong during the communication between client
 *             and server.
 * 
 */
private String sendRequest(String body) throws IOException {

    BufferedReader reader = null;
    OutputStreamWriter writer = null;

    try {

        // create the URL object from the endpoint
        URL url = new URL(API_ENDPOINT);

        // open the connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // use POST and configure the connection
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // set the request headers
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-Api-Token", apiToken);
        connection.setRequestProperty("X-Version", "" + apiVersion);
        connection.setRequestProperty("Content-Length", String.valueOf(body.length()));

        // construct the writer and write request
        writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(body);
        writer.flush();

        // listen on the server response
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        // construct the server response and return
        StringBuilder sb = new StringBuilder();
        for (String line; (line = reader.readLine()) != null;) {
            sb.append(line);
        }

        // return the result
        return sb.toString();

    } catch (MalformedURLException e) {
        // the URL we specified as endpoint was not valid
        System.err.println("The URL " + API_ENDPOINT + " is not a valid URL");
        e.printStackTrace();
        return null;
    } catch (ProtocolException e) {
        // this should not happen, it means that we specified a wrong
        // protocol
        System.err.println("The HTTP method is not valid. Please check if you specified POST.");
        e.printStackTrace();
        return null;
    } finally {
        // close the reader and writer
        try {
            writer.close();
        } catch (Exception e) {
            // intentionally left blank
        }
        try {
            reader.close();
        } catch (Exception e) {
            // intentionally left blank
        }
    }
}

From source file:com.ibm.bi.dml.test.utils.TestUtils.java

public static String processMultiPartCSVForR(String csvFile) throws IOException {
    File csv = new File(csvFile);
    if (csv.isDirectory()) {
        File[] parts = csv.listFiles();

        int count = 0;
        int index = -1;
        for (int i = 0; i < parts.length; i++) {
            File f = parts[i];//www .java2 s. c  o m
            String path = f.getPath();
            if (path.startsWith(".") && path.endsWith(".crc"))
                continue;
            count++;
            index = i;
        }

        if (count == 1) {
            csvFile = parts[index].toString();
        } else if (count > 1) {
            File tmp = new File(csvFile + "_temp.csv");
            OutputStreamWriter out = null;

            try {
                out = new OutputStreamWriter(new FileOutputStream(tmp), "UTF-8");

                // Directory listing may contain .crc files or may be in the
                // wrong order. Sanitize the list of names.
                ArrayList<String> partNames = new ArrayList<String>();
                for (File part : parts) {
                    String partName = part.getName();
                    if (false == partName.endsWith(".crc")) {
                        partNames.add(partName);
                    }
                }
                Collections.sort(partNames);

                for (String name : partNames) {
                    File part = new File(csv, name);
                    // Assume that each file fits into memory.
                    String fileContents = FileUtils.readFileToString(part, "UTF-8");
                    out.append(fileContents);
                }
            } finally {
                if (null != out)
                    out.close();
            }

            csvFile = tmp.getCanonicalPath();
        } else {
            throw new RuntimeException("Unexpected error while reading a CSV file in R: " + count);
        }
    }
    return csvFile;
}

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

/**
 * Send an SMS.// ww w . j ava2  s .  c  o  m
 *
 * @param destinationNumber the destination number
 * @param txt the Text of the message. Messages longer than the allowed
 * character length will be split into multiple messages.
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String sendSMS(String destinationNumber, String txt) throws IOException {
    String out = "";
    String smsdata = "";

    smsdata += URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc);
    smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc);
    smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc);
    URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/");

    URLConnection smsconn = smsurl.openConnection();
    smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    smsconn.setRequestProperty("User-agent", USER_AGENT);

    smsconn.setDoOutput(true);
    OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream());
    callwr.write(smsdata);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;
}

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

/**
 * Send an SMS./*from ww w . j a va  2 s. co  m*/
 *
 * @param destinationNumber the destination number
 * @param txt the Text of the message. Messages longer than the allowed
 * character length will be split into multiple messages.
 * @param id the Text of the message. Messages longer than the allowed
 * character length will be split into multiple messages.
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String sendSMS(String destinationNumber, String txt, String id) throws IOException {
    String out = "";
    String smsdata = "";
    smsdata += URLEncoder.encode("id", enc) + "=" + URLEncoder.encode(id, enc);
    smsdata += "&" + URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc);
    smsdata += "&" + URLEncoder.encode("conversationId", enc) + "=" + URLEncoder.encode(id, enc);
    smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc);
    smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc);
    System.out.println("smsdata: " + smsdata);

    URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/");

    URLConnection smsconn = smsurl.openConnection();
    smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    smsconn.setRequestProperty("User-agent", USER_AGENT);

    smsconn.setDoOutput(true);
    OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream());
    callwr.write(smsdata);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;
}

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

/**
 * Executes the enable/disable action with the provided url params.
 *
 * @param paraString the URL Parameters (encoded), ie ?auth=3248sdf7234&enable=0&phoneId=1&enable=1&phoneId=2&_rnr_se=734682ghdsf
 * @return the raw response of the disable action.
 * @throws IOException Signals that an I/O exception has occurred.
 *///ww w  .j  ava  2 s .  c  om
private String phonesEnableDisableApply(String paraString) throws IOException {
    String out = "";

    // POST /voice/call/connect/ outgoingNumber=[number to
    // call]&forwardingNumber=[forwarding
    // number]&subscriberNumber=undefined&remember=0&_rnr_se=[pull from
    // page]

    //
    if (PRINT_TO_CONSOLE)
        System.out.println(phoneEnableURLString);
    if (PRINT_TO_CONSOLE)
        System.out.println(paraString);
    URL requestURL = new URL(phoneEnableURLString);

    URLConnection conn = requestURL.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream());
    callwr.write(paraString);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;

}