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.qualogy.qafe.gwt.server.RPCServiceImpl.java

public String getUI(String xmlUI) throws GWTServiceException {
    String url = null;/*from  ww  w.j  a  v a 2 s.co m*/
    if (service.isValidXML(xmlUI)) {
        logger.fine("XML Send by client : \n" + xmlUI);

        try {

            String urlBase = ApplicationCluster.getInstance()
                    .getConfigurationItem(Configuration.FLEX_DEMO_WAR_URL);
            if (urlBase == null || urlBase.length() == 0) {
                urlBase = getThreadLocalRequest().getScheme() + "://" + getThreadLocalRequest().getServerName()
                        + ":" + getThreadLocalRequest().getServerPort() + "/qafe-web-flex";
            }

            String urlStore = urlBase + "/store";
            logger.fine("URL Store is =" + urlStore);

            OutputStreamWriter wr = null;
            BufferedReader rd = null;

            try {
                // Send data
                URL requestURL = new URL(urlStore);
                URLConnection conn = requestURL.openConnection();
                conn.setDoOutput(true);
                wr = new OutputStreamWriter(conn.getOutputStream());
                String data = "xml" + "=" + xmlUI;
                wr.write(data);
                wr.flush();

                // Get the response
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    url = urlBase + "/index.jsp?uuid=" + line;
                    logger.fine(url);
                }
            } finally {
                wr.close();
                rd.close();
            }
        } catch (Exception e) {
            throw handleException(e);
        }
    } else {
        try {
            service.getUIFromXML(xmlUI, null, null, getLocale());
        } catch (Exception e) {
            throw handleException(e);
        }
    }
    return url;
}

From source file:eu.elf.license.LicenseQueryHandler.java

/**
 * Performs HTTP GET or POST query to the backend server
 *
 * @param queryURL       The request string that is to be sent to the server
 * @param queryType      - Type of the query (get || post)
 * @param payloadForPost - POST payload, empty string for GET queries
 * @return The response of the server//ww w .j  a va  2s. co m
 * @throws IOException
 */
public StringBuffer doHTTPQuery(URL queryURL, String queryType, String payloadForPost,
        Boolean useBasicAuthentication) throws IOException {
    StringBuffer sbuf = new StringBuffer();
    URLConnection uc = null;
    HttpURLConnection httpuc;
    HttpsURLConnection httpsuc;
    String WFSResponseLine = "";
    String userPassword = "";
    String encoding = "";

    //System.out.println("queryURL: "+queryURL.toString());
    //System.out.println("PayloadForPost: "+payloadForPost);

    try {

        httpuc = (HttpURLConnection) queryURL.openConnection();
        httpuc.setDoInput(true);
        httpuc.setDoOutput(true);

        if (useBasicAuthentication == true) {
            userPassword = this.username + ":" + this.password;
            encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
            httpuc.setRequestProperty("Authorization", "Basic " + encoding);
        }

        if (queryType.equals("get")) {
            //System.out.println("queryURL: "+queryURL);

            BufferedReader buf = new BufferedReader(new InputStreamReader(httpuc.getInputStream(), "utf-8"));

            while ((WFSResponseLine = buf.readLine()) != null) {
                sbuf.append(WFSResponseLine);
            }

            buf.close();
        } else if (queryType.equals("post")) {
            //System.out.println("PayloadForPost"+payloadForPost);

            httpuc.setRequestMethod("POST");
            httpuc.setRequestProperty("Content-Type", "text/xml;charset=UTF8");
            httpuc.setRequestProperty("Content-Type", "text/plain");

            OutputStreamWriter osw = new OutputStreamWriter(httpuc.getOutputStream(), Charset.forName("UTF-8"));
            osw.write(URLDecoder.decode(payloadForPost, "UTF-8"));

            osw.flush();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpuc.getInputStream(), Charset.forName("UTF8")));

            while ((WFSResponseLine = in.readLine()) != null) {
                //System.out.println("WFSResponseLine: "+WFSResponseLine);

                sbuf.append(WFSResponseLine);
            }

            in.close();
            osw.close();
        }

    } catch (IOException ioe) {
        throw ioe;
    }

    return sbuf;
}

From source file:brugerautorisation.server.BrugerProtocol.java

private void cmd(List<String> msg) {
    OutputStreamWriter out = null;
    Writer writer = null;// ww  w. jav  a 2  s.  c om
    try {
        out = new OutputStreamWriter(server.getOutputStream());
        writer = new BufferedWriter(out);
        switch (msg.get(0).toLowerCase().replace("\n", "")) {
        case ("hello"):
            break;
        case ("login"):
            System.out.println("v");
            JSONObject json = new JSONObject(msg.get(1));
            JSONObject json_return = new JSONObject();
            try {
                Bruger b = ba.hentBruger(json.getString("username"), json.getString("password"));
                json_return.put("username", b.brugernavn);
            } catch (SOAPFaultException e) {
                json_return.put("error", e.getMessage());
            }
            writer.write(json_return.toString());
            writer.flush();
            //out.flush();
            break;
        case ("forgot_pass"):
            break;
        default:
            System.out.println("ikke fundet");
            break;
        }
    } catch (IOException ex) {
        Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            writer.close();
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:com.BeatYourRecord.SubmitActivity.java

private String uploadMetaData(String filePath, boolean retry) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);/*from   w  w  w .j av  a  2  s .  c  o m*/
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData;
    int pos = filePath.indexOf("BYR");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
    String currentDateandTime = sdf.format(new Date());
    SharedPreferences pref1 = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
    Editor editor1 = pref1.edit();
    String username = pref1.getString("Username", null);
    String title = "BeatYourRecord Free Throws " + currentDateandTime + " Score : " + getTitleText()
            + " User : " + username;
    //this.initFile().getAbsolutePath();

    String description = "Beat Your Record Free Throw Tournament. User : " + username + ". Go to"
            + " www.ec2-54-212-221-3.us-west-2.compute.amazonaws.com"
            + " to take part in our other tournaments";
    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    if (!Util.isNullOrEmpty(this.getTagsText())) {
        this.tags = this.getTagsText();
    }

    if (this.videoLocation == null) {
        String template = Util.readFile(this, R.raw.gdata).toString();
        atomData = String.format(template, title, description, category, this.tags);
    } else {
        String template = Util.readFile(this, R.raw.gdata_geo).toString();
        atomData = String.format(template, title, description, category, this.tags, videoLocation.getLatitude(),
                videoLocation.getLongitude());
    }

    OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
    outStreamWriter.write(atomData);
    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();
    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(LOG_TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(filePath, false);
        } else {
            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));
        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:ie.pars.nlp.sketchengine.interactions.ViewSKEInteractions.java

/**
 * Get all the results and dump it into files this method can be changed so
 * that it resembles a stream on demand/*from w  w w .  j av a  2  s .com*/
 *
 * @param output
 * @param corpusName
 * @param cqlQuery
 * @param contextSizeLeft
 * @throws UnsupportedEncodingException
 * @throws IOExceptionsket
 * @throws Exception
 */
private void getStroConcordanceFile() throws UnsupportedEncodingException, IOException, Exception {
    HttpClient sessionID = super.getSessionID();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(this.outputFile),
            StandardCharsets.UTF_8);
    PrintWriter printer = new PrintWriter(outputStreamWriter);
    if (!writeParsedData) {
        printer.println("{\"results\": [");
    }
    int pageNumer = 0;
    JSONObject jsonObjP = null;
    boolean loopCondition = true;
    while (loopCondition) {
        jsonObjP = super.getHTTP(sessionID, encodeQuery(++pageNumer));
        if (this.writeParsedData) {
            ViewMethodJsonParser vmParser = new ViewMethodJsonParser(jsonObjP.toString());
            ConcordanceLine cl;
            while ((cl = vmParser.getNext()) != null) {
                printer.println(cl.toStringLine());
            }

        } else {
            printer.println(jsonObjP.toString(1));
        }
        loopCondition = loopCondition(jsonObjP, pageNumer);
        if (loopCondition) {
            if (!writeParsedData) {
                printer.println(" ,");
            }
        }

    }
    ;

    if (!writeParsedData) {
        printer.println("]" + "}"); // to the end the json file}
    }
    //printer.flush();
    //outputStreamWriter.flush();
    printer.close();
    outputStreamWriter.close();

}

From source file:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping("teacher/xgwork")
public @ResponseBody String xgwork(HttpServletRequest request) throws IOException {
    String textWork = request.getParameter("arred");//?
    String time = request.getParameter("time");//??
    String miaoshu = request.getParameter("miaoshu");
    String starttime = request.getParameter("starttime");
    String coursename = request.getParameter("courseName");
    String term = request.getParameter("term");
    String id = request.getParameter("id");
    String tec_name = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName();
    String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege();
    String sn = getCurrentUsername();
    //                                      ?   ??          ??
    String ff = getFileFolder(request) + "homework/" + term + "/" + collage + "/" + sn + "/" + tec_name + "/"
            + coursename + "/" + id + "/";

    //?html//from   w  w  w  . j ava  2  s. c  o  m
    OutputStreamWriter pw = null;
    pw = new OutputStreamWriter(new FileOutputStream(new File(ff + File.separator + "textWork.html")), "GBK");
    pw.write(textWork);
    pw.close();
    //??
    PrintStream ps = null;
    ps = new PrintStream(new FileOutputStream(new File(ff + File.separator + "Workall.txt")));
    ps.printf(miaoshu);//??:
    ps.println();
    ;
    ps.println(time);//??:
    ps.println(starttime);//??:
    ps.close();
    return "1";
}

From source file:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping("teacher/work")
public @ResponseBody String work(HttpServletRequest request) throws IOException {
    int length = 0;
    String textWork = request.getParameter("arred");//?
    String time = request.getParameter("time");//??
    String starttime = request.getParameter("onetime");//??
    String miaoshu = request.getParameter("miaoshu");
    String coursename = request.getParameter("courseName");
    String term = request.getParameter("term");
    String tec_name = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName();
    String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege();
    String sn = getCurrentUsername();
    //                                      ?   ??          ??
    String ff = getFileFolder(request) + "homework/" + term + "/" + collage + "/" + sn + "/" + tec_name + "/"
            + coursename + "/";
    file(ff);//??
    length = haveFile(ff);//from   w  ww  .  j  av a  2  s .c  om
    ff = ff + (length + 1) + "/";
    file(ff);
    //?html
    OutputStreamWriter pw = null;
    pw = new OutputStreamWriter(new FileOutputStream(new File(ff + File.separator + "textWork.html")), "GBK");
    pw.write(textWork);
    pw.close();
    //??
    PrintStream ps = null;
    ps = new PrintStream(new FileOutputStream(new File(ff + File.separator + "Workall.txt")));
    ps.printf(miaoshu);//??:
    ps.println();
    ;
    ps.println(time);//??:
    ps.println(starttime);//??
    ps.close();
    return "1";
}

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

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

    final SSDataExportAddTagsCategoriesTimestampsForUserEntityPar par = new SSDataExportAddTagsCategoriesTimestampsForUserEntityPar(
            parA);/*  w  ww  . j  av a 2s  . co m*/
    CSVWriter fileWriter = null;
    FileOutputStream out = null;
    OutputStreamWriter writer = null;

    try {

        final List<String> lineParts = new ArrayList<>();

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

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

        if (!par.tags.isEmpty()) {
            lineParts.add(StringUtils.join(par.tags, SSStrU.comma));
        } else {
            lineParts.add(SSStrU.empty);
        }

        if (!par.categories.isEmpty()) {
            lineParts.add(StringUtils.join(par.categories, 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:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping(value = "saveTree", method = RequestMethod.POST)
public @ResponseBody String saveTree(HttpServletRequest request, @RequestBody Tree3[] users) throws Exception {
    String sn = getCurrentUsername();
    Teacher tec = TeacherDao.getTeacherBySn(sn);
    String tec_sn = tec.getTeacherSn();
    String tec_name = tec.getTeacherName();
    String collage = tec.getTeacherCollege();
    String term = request.getParameter("term");
    String courseName = request.getParameter("courseName");
    // ...//???????? //
    File f = new File(getFileFolder(request) + term + "/" + collage + "/" + tec_sn + "/" + tec_name + "/"
            + courseName + "/" + "" + "/");
    //??//from  w w w .ja v a2  s  .  co  m
    if (!f.exists() && !f.isDirectory()) {
        System.out.println("?");
        f.mkdirs();
    } else {
        System.out.println("");
    }
    String ff = getFileFolder(request) + term + "/" + collage + "/" + tec_sn + "/" + tec_name + "/" + courseName
            + "/" + "" + "/";
    List list = new LinkedList();
    String ss = "", aa;
    for (int i = 0; i < users.length - 1; i++) {
        list.add(users[i]);
        aa = JSONObject.fromObject(users[i]) + "";
        ss += aa + ',';
    }
    aa = JSONObject.fromObject(users[3]) + "";
    ss = ss + aa;
    ss = '[' + ss + ']';
    System.out.println(ss);
    OutputStreamWriter pw = null;//?
    pw = new OutputStreamWriter(new FileOutputStream(new File(ff + File.separator + "test.json")), "GBK");
    pw.write(ss);
    pw.close();
    return "1";
}

From source file:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping("teacher/homework_submit")
public @ResponseBody String homework_submit(HttpServletRequest request,
        @RequestParam("file") MultipartFile file) throws FileNotFoundException, IOException {
    int length = 0;
    String textWork = request.getParameter("arr1");//?
    String time = request.getParameter("time");//??
    String miaoshu = request.getParameter("miaoshu");
    String coursename = request.getParameter("courseName");
    String term = request.getParameter("term");
    String tec_name = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName();
    String sn = getCurrentUsername();
    String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege();
    //                                      ?   ??          ??
    String ff = getFileFolder(request) + "homework/" + term + "/" + collage + "/" + sn + "/" + tec_name + "/"
            + coursename + "/";
    file(ff);//??
    length = haveFile(ff);/*w w  w.j  a v a 2 s .c o m*/
    ff = ff + (length + 1) + "/";
    file(ff);
    //?html
    OutputStreamWriter pw = null;//?
    pw = new OutputStreamWriter(new FileOutputStream(new File(ff + File.separator + "textWork.html")), "GBK");
    pw.write(textWork);
    pw.close();
    //??
    PrintStream ps = null;
    ps = new PrintStream(new FileOutputStream(new File(ff + File.separator + "Workall.txt")));
    ps.printf(miaoshu);//??:
    ps.println();
    ;
    ps.println(time);//??:
    ps.close();
    //
    if (!file.isEmpty()) {
        try {
            InputStream in;
            try (FileOutputStream os = new FileOutputStream(ff + "/" + file.getOriginalFilename())) {
                in = file.getInputStream();
                int b = 0;
                while ((b = in.read()) != -1) {
                    os.write(b);
                }
                os.flush();
            }
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
    }
    return "1";
}