List of usage examples for java.io OutputStreamWriter write
public void write(int c) throws IOException
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 ww .j av a2 s. c om*/ 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);/*from w ww . ja v a2 s . co 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"; }
From source file:io.fabric8.devops.connector.DevOpsConnector.java
protected void postJenkinsBuild(String jobName, String xml, boolean create) { String address = getServiceUrl(ServiceNames.JENKINS, false, namespace, jenkinsNamespace); if (Strings.isNotBlank(address)) { String jobUrl = URLUtils.pathJoin(address, "/job", jobName, "config.xml"); if (create && !existsXmlURL(jobUrl)) { jobUrl = URLUtils.pathJoin(address, "/createItem") + "?name=" + jobName; }/*from w w w . java2 s. c o m*/ getLog().info("POSTING the jenkins job to: " + jobUrl); getLog().debug("Jenkins XML: " + xml); HttpURLConnection connection = null; try { URL url = new URL(jobUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(xml); out.close(); int status = connection.getResponseCode(); String message = connection.getResponseMessage(); getLog().info("Got response code from Jenkins: " + status + " message: " + message); if (status != 200) { getLog().error("Failed to register job " + jobName + " on " + jobUrl + ". Status: " + status + " message: " + message); } } catch (Exception e) { getLog().error("Failed to register jenkins on " + jobUrl + ". " + e, e); } finally { if (connection != null) { connection.disconnect(); } } } }
From source file:io.fabric8.devops.connector.DevOpsConnector.java
protected void triggerJenkinsWebHook(String jobUrl, String triggerUrl, String secret) { // lets check if this build is already running in which case do nothing String lastBuild = URLUtils.pathJoin(jobUrl, "/lastBuild/api/json"); JsonNode lastBuildJson = parseLastBuildJson(lastBuild); JsonNode building = null;/*from ww w. j a v a 2s .co m*/ if (lastBuildJson != null && lastBuildJson.isObject()) { building = lastBuildJson.get("building"); if (building != null && building.isBoolean()) { if (building.booleanValue()) { getLog().info("Build is already running so lets not trigger another one!"); return; } } } getLog().info("Got last build JSON: " + lastBuildJson + " building: " + building); getLog().info("Triggering Jenkins webhook: " + triggerUrl); String json = "{}"; HttpURLConnection connection = null; try { URL url = new URL(triggerUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(json); out.close(); int status = connection.getResponseCode(); String message = connection.getResponseMessage(); getLog().info("Got response code from Jenkins: " + status + " message: " + message); if (status != 200) { getLog().error( "Failed to trigger job " + triggerUrl + ". Status: " + status + " message: " + message); } } catch (Exception e) { getLog().error("Failed to trigger jenkins on " + triggerUrl + ". " + e, e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.witness.ssc.xfer.utils.PublishingUtils.java
private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title, String description, boolean retry) throws IOException { String uploadUrl = INITIAL_UPLOAD_URL; HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true);/* w w w. j av a 2s . com*/ urlConnection.setRequestProperty("Content-Type", "application/atom+xml"); // urlConnection.setRequestProperty("Content-Length", newValue); urlConnection.setRequestProperty("Slug", filePath); String atomData = null; String category = DEFAULT_VIDEO_CATEGORY; this.tags = DEFAULT_VIDEO_TAGS; String template = readFile(activity, R.raw.gdata).toString(); // Workarounds for corner cases. Youtube doesnt like empty titles if (title == null || title.length() == 0) { title = "Untitled"; } if (description == null || description.length() == 0) { description = "No description"; } atomData = String.format(template, title, description, category, this.tags); OutputStreamWriter outStreamWriter = null; int responseCode = -1; try { outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); outStreamWriter.write(atomData); outStreamWriter.close(); /* * urlConnection.connect(); InputStream is = * urlConnection.getInputStream(); BufferedReader in = new * BufferedReader(new InputStreamReader(is)); String inputLine; * * while ((inputLine = in.readLine()) != null) { * Log.d(TAG,inputLine); } in.close(); */ responseCode = urlConnection.getResponseCode(); // ERROR LOGGING InputStream is = urlConnection.getErrorStream(); if (is != null) { Log.e(TAG, " Error stream from Youtube available!"); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String inputLine; while ((inputLine = in.readLine()) != null) { Log.d(TAG, inputLine); } in.close(); Map<String, List<String>> hfs = urlConnection.getHeaderFields(); for (Entry<String, List<String>> hf : hfs.entrySet()) { Log.d(TAG, " entry : " + hf.getKey()); List<String> vals = hf.getValue(); for (String s : vals) { Log.d(TAG, "vals:" + s); } } } } catch (IOException e) { // // Catch IO Exceptions here, like UnknownHostException, so we can // detect network failures, and send a notification // Log.d(TAG, " Error occured in uploadMetaData! "); e.printStackTrace(); responseCode = -1; outStreamWriter = null; // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); // forward it on! throw e; } if (responseCode < 200 || responseCode >= 300) { // The response code is 40X if ((responseCode + "").startsWith("4") && retry) { Log.d(TAG, "retrying to fetch auth token for " + youTubeName); this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken); // Try again with fresh token return uploadMetaData(activity, handler, filePath, title, description, false); } else { // Probably not authorised! // Need to setup a Youtube account. // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); throw new IOException(String.format("response code='%s' (code %d)" + " for %s", urlConnection.getResponseMessage(), responseCode, urlConnection.getURL())); } } return urlConnection.getHeaderField("Location"); }
From source file:org.jmxtrans.embedded.output.CopperEggWriter.java
public String Send_Commmand(String command, String msgtype, String payload, Integer ExpectInt) { HttpURLConnection urlConnection = null; URL myurl = null;/* ww w .jav a2s. c o m*/ OutputStreamWriter wr = null; int responseCode = 0; String id = null; int error = 0; try { myurl = new URL(url_str + command); urlConnection = (HttpURLConnection) myurl.openConnection(); urlConnection.setRequestMethod(msgtype); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(coppereggApiTimeoutInMillis); urlConnection.addRequestProperty("User-Agent", "Mozilla/4.76"); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); wr = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"); wr.write(payload); wr.flush(); responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn( "Send Command: Response code " + responseCode + " url is " + myurl + " command " + msgtype); error = 1; } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command: url is " + myurl + " command " + msgtype + "; " + e); error = 1; } finally { if (urlConnection != null) { try { if (error > 0) { InputStream err = urlConnection.getErrorStream(); String errString = convertStreamToString(err); logger.warn("Reported error : " + errString); IoUtils2.closeQuietly(err); } else { InputStream in = urlConnection.getInputStream(); String theString = convertStreamToString(in); id = jparse(theString, ExpectInt); IoUtils2.closeQuietly(in); } } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command : flushing http connection " + e); } } if (wr != null) { try { wr.close(); } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command: closing OutputWriter " + e); } } } return (id); }
From source file:com.fluidops.iwb.widget.ImportRDFWidget.java
private FButton createRefineButton(final FTextInput2 context, final FTextInput2 baseURI, final FContainer stat, final FTextInput2 project, final FTextInput2 refineFormat, final FTextInput2 refineURL, final FTextInput2 engine, final FCheckBox keepSourceCtx, final FCheckBox contextEditable) { return new FButton("refineButton", "Import RDF Data") { @Override/*from w w w .j a va 2 s . c om*/ public void onClick() { try { getBasicInput(context, baseURI); } catch (Exception e) { stat.hide(true); logger.info(e.getMessage()); return; } if (engine.getInput().length() > 0 && project.getInput().length() > 0 && refineFormat.getInput().length() > 0 && refineURL.getInput().length() > 0) { Map<String, String> parameter = new HashMap<String, String>(); parameter.put(engine.getName(), engine.getInput()); parameter.put(project.getName(), project.getInput()); parameter.put(refineFormat.getName(), refineFormat.getInput()); URL urlValue = null; try { urlValue = new URL(refineURL.getInput()); } catch (MalformedURLException e) { stat.hide(true); getPage().getPopupWindowInstance().showError(refineURL.getInput() + " is not a valid URL"); logger.error(e.getMessage(), e); return; } OutputStreamWriter wr = null; InputStream input = null; try { // Collect the request parameters StringBuilder params = new StringBuilder(); for (Entry<String, String> entry : parameter.entrySet()) params.append(StringUtil.urlEncode(entry.getKey())).append("=") .append(StringUtil.urlEncode(entry.getValue())).append("&"); // Send data URLConnection urlcon = urlValue.openConnection(); urlcon.setDoOutput(true); wr = new OutputStreamWriter(urlcon.getOutputStream()); wr.write(params.toString()); wr.flush(); // Get the response input = urlcon.getInputStream(); importData(this, input, baseUri, RDFFormat.RDFXML, contextUri, "Open Refine", keepSourceCtx.getChecked(), contextEditable.getChecked()); } catch (Exception e) { logger.error(e.getMessage(), e); getPage().getPopupWindowInstance().showError(e.getMessage()); } finally { stat.hide(true); IOUtils.closeQuietly(input); IOUtils.closeQuietly(wr); } } else { stat.hide(true); getPage().getPopupWindowInstance().showError("All marked fields should be filled out"); } } }; }
From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java
public void saveCookies() { FileOutputStream fOut = null; OutputStreamWriter osw = null; // make dirs//from ww 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:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title, String description, boolean retry, long sdrecord_id) throws IOException { String uploadUrl = INITIAL_UPLOAD_URL; HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true);/*from www . j a v a 2 s. c o m*/ urlConnection.setRequestProperty("Content-Type", "application/atom+xml"); // urlConnection.setRequestProperty("Content-Length", newValue); urlConnection.setRequestProperty("Slug", filePath); String atomData = null; String category = DEFAULT_VIDEO_CATEGORY; this.tags = DEFAULT_VIDEO_TAGS; String template = readFile(activity, R.raw.gdata).toString(); // Workarounds for corner cases. Youtube doesnt like empty titles if (title == null || title.length() == 0) { title = "Untitled"; } if (description == null || description.length() == 0) { description = "No description"; } // Check user preference to see if YouTube videos should be private by // default. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext()); Boolean ytPrivate = prefs.getBoolean("defaultYouTubePrivatePreference", true); String private_or_not = "<yt:private />"; if (!ytPrivate) { private_or_not = ""; } atomData = String.format(template, title, description, category, this.tags, private_or_not); OutputStreamWriter outStreamWriter = null; int responseCode = -1; try { outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); outStreamWriter.write(atomData); outStreamWriter.close(); /* * urlConnection.connect(); InputStream is = * urlConnection.getInputStream(); BufferedReader in = new * BufferedReader(new InputStreamReader(is)); String inputLine; * * while ((inputLine = in.readLine()) != null) { * Log.d(TAG,inputLine); } in.close(); */ responseCode = urlConnection.getResponseCode(); // ERROR LOGGING InputStream is = urlConnection.getErrorStream(); if (is != null) { Log.e(TAG, " Error stream from Youtube available!"); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String inputLine; while ((inputLine = in.readLine()) != null) { Log.d(TAG, inputLine); } in.close(); Map<String, List<String>> hfs = urlConnection.getHeaderFields(); for (Entry<String, List<String>> hf : hfs.entrySet()) { Log.d(TAG, " entry : " + hf.getKey()); List<String> vals = hf.getValue(); for (String s : vals) { Log.d(TAG, "vals:" + s); } } } } catch (IOException e) { // // Catch IO Exceptions here, like UnknownHostException, so we can // detect network failures, and send a notification // Log.d(TAG, " Error occured in uploadMetaData! "); e.printStackTrace(); responseCode = -1; outStreamWriter = null; mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); // forward it on! throw e; } if (responseCode < 200 || responseCode >= 300) { // The response code is 40X if ((responseCode + "").startsWith("4") && retry) { Log.d(TAG, "retrying to fetch auth token for " + youTubeName); this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken); // Try again with fresh token return uploadMetaData(activity, handler, filePath, title, description, false, sdrecord_id); } else { mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT); // Probably not authorised! // Need to setup a Youtube account. // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); throw new IOException(String.format("response code='%s' (code %d)" + " for %s", urlConnection.getResponseMessage(), responseCode, urlConnection.getURL())); } } return urlConnection.getHeaderField("Location"); }