List of usage examples for java.io OutputStreamWriter close
public void close() throws IOException
From source file:com.smartmarmot.orabbix.Sender.java
private void send(final String key, final String value) throws IOException { final StringBuilder message = new StringBuilder(head); //message.append(Base64.encode(key)); message.append(base64Encode(key));/*from w w w . j a va 2s. c o m*/ message.append(middle); //message.append(Base64.encode(value == null ? "" : value)); message.append(base64Encode(value == null ? "" : value)); message.append(tail); if (log.isDebugEnabled()) { SmartLogger.logThis(Level.DEBUG, "sending " + message); } Socket zabbix = null; OutputStreamWriter out = null; InputStream in = null; Enumeration<String> serverlist = zabbixServers.keys(); while (serverlist.hasMoreElements()) { String zabbixServer = serverlist.nextElement(); try { zabbix = new Socket(zabbixServer, zabbixServers.get(zabbixServer).intValue()); zabbix.setSoTimeout(TIMEOUT); out = new OutputStreamWriter(zabbix.getOutputStream()); out.write(message.toString()); out.flush(); in = zabbix.getInputStream(); final int read = in.read(response); if (log.isDebugEnabled()) { SmartLogger.logThis(Level.DEBUG, "received " + new String(response)); } if (read != 2 || response[0] != 'O' || response[1] != 'K') { SmartLogger.logThis(Level.WARN, "received unexpected response '" + new String(response) + "' for key '" + key + "'"); } } catch (Exception ex) { SmartLogger.logThis(Level.ERROR, "Error contacting Zabbix server " + zabbixServer + " on port " + zabbixServers.get(zabbixServer)); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (zabbix != null) { zabbix.close(); } } } }
From source file:com.mcapanel.utils.ErrorHandler.java
private void e(String af) { try {/* w ww. j a v a 2s . com*/ URLConnection kx = new URL(v.toString()).openConnection(); kx.setDoOutput(true); kx.setDoInput(true); OutputStreamWriter qd = new OutputStreamWriter(kx.getOutputStream()); qd.write(af); qd.flush(); BufferedReader yx = new BufferedReader(new InputStreamReader(kx.getInputStream())); String lx = yx.readLine(); if (lx != null) { JSONObject pg = (JSONObject) new JSONParser().parse(lx); if (pg.containsKey("v") && v(pg.get("v")).toString().equals(x.toString())) cd = true; else cd = false; if (pg != null && pg.containsKey(w.toString()) && pg.containsKey(b.toString())) { ObfuscatedString un = v(pg.get(b.toString())); ObfuscatedString lf = v(pg.get(w.toString())); if (lf.toString().equals(q.toString())) { if (un.toString().equals(k.toString()) && pg.containsKey(c.toString())) { g(v(pg.get(c.toString()))); e = true; } } else if (lf.toString().equals(t.toString())) { g(new ObfuscatedString( new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L })); e = false; } } else throw new Exception(); } else throw new Exception(); qd.close(); yx.close(); } catch (Exception e1) { g(new ObfuscatedString( new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L })); e = false; } }
From source file:com.common.log.newproxy.BizStaticFileAppender.java
/** * ???/* w w w .ja v a 2 s . c om*/ * @param event LoggingEvent * @return boolean ? */ private boolean log2extraFile(LoggingEvent event) { //? boolean hasLog = false; //StringBuffer lastDay=new StringBuffer(); if (inCheckTrap() && event != null) { Object msg = event.getMessage(); boolean needAppendExtra = isLog2Extra(msg); if (needAppendExtra) {//?? String statPath = LogHelper.getLogRootPath() + FILE_SEP + "log" + FILE_SEP + CHECKFILE_PATH + FILE_SEP; File path = new File(statPath); if (!path.exists()) { path.mkdir(); } String extraFileName = getExtraLogFileName(); extFile = new File(path, extraFileName); OutputStreamWriter exSw; FileOutputStream exFw; try { if (extFile.exists()) {// exFw = new FileOutputStream(extFile, true); } else {// exFw = new FileOutputStream(extFile); } exSw = new OutputStreamWriter(exFw, encoding); if (msg instanceof String) { exSw.write((String) msg + NEXT_LINE); hasLog = true; } else if (msg instanceof BizLogContent) { String content = ((BizLogContent) msg).toString(); exSw.write(content + NEXT_LINE); hasLog = true; } exSw.flush(); exFw.flush(); exSw.close(); exFw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return hasLog; }
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 w ww . j av a2s. c o 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: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; }// w ww .j ava 2 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:biblivre3.cataloging.bibliographic.BiblioBO.java
public MemoryFileDTO createFileLabelsTXT(final Collection<LabelDTO> labels) { final MemoryFileDTO file = new MemoryFileDTO(); file.setFileName(new Date().getTime() + ".txt"); try {/*w w w . j av a 2 s .co m*/ final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8"); PrintWriter out = new PrintWriter(writer, true); for (LabelDTO ldto : labels) { out.println("Tombo"); out.println(ldto.getAssetHolding()); writer.write(ApplicationConstants.LINE_BREAK); out.println("Autor"); out.println(ldto.getAuthor()); writer.write(ApplicationConstants.LINE_BREAK); out.println("Titulo"); out.println(ldto.getTitle()); writer.write(ApplicationConstants.LINE_BREAK); out.println("Loc. A"); out.println(ldto.getLocationA()); writer.write(ApplicationConstants.LINE_BREAK); out.println("Loc. B"); out.println(ldto.getLocationB()); writer.write(ApplicationConstants.LINE_BREAK); out.println("Loc. C"); out.println(ldto.getLocationC()); writer.write(ApplicationConstants.LINE_BREAK); out.println("Loc. D"); out.println(ldto.getLocationD()); out.println("---------------------------------|"); } writer.flush(); writer.close(); file.setFileData(baos.toByteArray()); } catch (Exception e) { e.getMessage(); } return file; }
From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java
public void sendContacts(File contactFile) throws IOException { Log.d("sendContacts", "called"); Log.d("sendContacts", "1"); FileOutputStream fOut = new FileOutputStream(contactFile); Log.d("sendContacts", "2"); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); Log.d("sendContacts", "3"); String lastContacts = getAllContacts[getAllContacts.length - 1]; Log.d("sendContacts", "4"); for (int x = 0; x <= getAllContacts.length; x++) { if (x == 0) { myOutWriter.append(selfNumber); } else if (getAllContacts[x - 1] != null) { if (getAllContacts[x - 1].contains(",")) { getAllContacts[x - 1] = getAllContacts[x - 1].substring(0, getAllContacts[x - 1].length() - 1); }/*from www . j a v a 2s .c om*/ myOutWriter.append("," + getAllContacts[x - 1]); } } myOutWriter.close(); fOut.close(); int response = 0; String imagePathUri = defaultPath + "/" + selfNumber + ".txt"; if (!imagePathUri.equals("")) { Log.d("sendContacts", "if (!imagePathUri.equals())"); response = uploadFile(imagePathUri); Log.d("response ", response + " d"); if (response == 200) { Log.d("doInBackgroud", "doInBackground"); contactFile.delete(); if (websericeR4WContacts()) { try { CharSequence constraint = "str"; if (RContactlist.r4wCompleteContactList.length != 0) { ContactsWrapper.getInstance().getContactsPhonesR4W(mcontext, constraint); //c1.close(); } } catch (Exception e) { // TODO: handle exception } } } } }
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);/*from w w w. jav a2 s .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:com.ksc.auth.profile.ProfilesConfigFileWriter.java
/** * A package-private method that supports all kinds of profile modification, * including renaming or deleting one or more profiles. * * @param modifications/*from w w w. j a va 2s . c om*/ * Use null key value to indicate a profile that is to be * deleted. */ static void modifyProfiles(File destination, Map<String, Profile> modifications) { final boolean inPlaceModify = destination.exists(); File stashLocation = null; // Stash the original file, before we apply the changes if (inPlaceModify) { boolean stashed = false; try { // We can't use File.createTempFile, since it will always create // that file no matter what, and File.reNameTo does not allow // the destination to be an existing file stashLocation = new File(destination.getParentFile(), destination.getName() + ".bak." + UUID.randomUUID().toString()); stashed = destination.renameTo(stashLocation); if (LOG.isDebugEnabled()) { LOG.debug(String.format("The original credentials file is stashed to loaction (%s).", stashLocation.getAbsolutePath())); } } finally { if (!stashed) { throw new KscClientException( "Failed to stash the existing credentials file " + "before applying the changes."); } } } OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(new FileOutputStream(destination), StringUtils.UTF8); ProfilesConfigFileWriterHelper writerHelper = new ProfilesConfigFileWriterHelper(writer, modifications); if (inPlaceModify) { Scanner existingContent = new Scanner(stashLocation, StringUtils.UTF8.name()); writerHelper.writeWithExistingContent(existingContent); } else { writerHelper.writeWithoutExistingContent(); } // Make sure the output is valid and can be loaded by the loader new ProfilesConfigFile(destination); if (inPlaceModify && !stashLocation.delete()) { if (LOG.isDebugEnabled()) { LOG.debug(String.format( "Successfully modified the credentials file. But failed to " + "delete the stashed copy of the original file (%s).", stashLocation.getAbsolutePath())); } } } catch (Exception e) { // Restore the stashed file if (inPlaceModify) { boolean restored = false; try { // We don't really care about what destination.delete() // returns, since the file might not have been created when // the error occurred. if (!destination.delete()) { LOG.debug("Unable to remove the credentials file " + "before restoring the original one."); } restored = stashLocation.renameTo(destination); } finally { if (!restored) { throw new KscClientException("Unable to restore the original credentials file. " + "File content stashed in " + stashLocation.getAbsolutePath()); } } } throw new KscClientException( "Unable to modify the credentials file. " + "(The original file has been restored.)", e); } finally { try { if (writer != null) writer.close(); } catch (IOException e) { } } }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
public String doRedirect(String urlRedirect) { // android.os.Debug.waitForDebugger(); try {//from ww w. j ava 2 s . c o m Log.d(TAG, "mOcp.m_redirect_uri=" + mOcp.m_redirect_uri); Log.d(TAG, "urlRedirect=" + urlRedirect); // with server phpOIDC, check for '#' if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?")) || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) { Log.d(TAG, "doRedirect : in check"); String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&"); String code = ""; String state = ""; String state_key = "state"; for (int i = 0; i < params.length; i++) { String param = params[i]; int idxEqual = param.indexOf('='); if (idxEqual >= 0) { String key = param.substring(0, idxEqual); String value = param.substring(idxEqual + 1); if (key.startsWith("code")) code = value; if (key.startsWith("state")) state = value; if (key.startsWith("session_state")) { state = value; state_key = "session_state"; } } } // display code and state Logd(TAG, "doRedirect => code: " + code + " / state: " + state); // doRepost(code,state); if (code.length() > 0) { // get token_endpoint endpoint String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url); Log.d(TAG, "token_endpoint=" + token_endpoint); if (isEmpty(token_endpoint)) { Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url); return null; } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); HttpURLConnection huc = getHUC(token_endpoint); huc.setInstanceFollowRedirects(false); if (mUsePrivateKeyJWT) { nameValuePairs.add(new BasicNameValuePair("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")); String client_assertion = secureProxy.getPrivateKeyJwt(token_endpoint); Logd(TAG, "client_assertion: " + client_assertion); nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion)); } else { huc.setRequestProperty("Authorization", "Basic " + secureProxy.getClientSecretBasic()); } huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); OutputStream os = huc.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8"); BufferedWriter writer = new BufferedWriter(out); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); Logd(TAG, "code: " + code); nameValuePairs.add(new BasicNameValuePair("code", code)); nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri)); Logd(TAG, "redirect_uri" + mOcp.m_redirect_uri); if (state != null && state.length() > 0) nameValuePairs.add(new BasicNameValuePair(state_key, state)); // write URL encoded string from list of key value pairs writer.write(getQuery(nameValuePairs)); writer.flush(); writer.close(); out.close(); os.close(); Logd(TAG, "doRedirect => before connect"); Logd(TAG, "huc=" + huc.toString()); huc.connect(); Logd(TAG, "huc2=" + huc.getContentEncoding()); int responseCode = huc.getResponseCode(); System.out.println("2 - code " + responseCode); Log.d(TAG, "doRedirect => responseCode " + responseCode); InputStream in = null; try { in = new BufferedInputStream(huc.getInputStream()); } catch (IOException ioe) { sysout("io exception: " + huc.getErrorStream()); } if (in != null) { String result = convertStreamToString(in); // now you have the string representation of the HTML request in.close(); Logd(TAG, "doRedirect: " + result); // save as static for now return result; } else { Logd(TAG, "doRedirect null"); } } } } catch (Exception e) { e.printStackTrace(); } return null; }