List of usage examples for java.io OutputStream write
public void write(byte b[]) throws IOException
b.length
bytes from the specified byte array to this output stream. From source file:org.gvnix.service.roo.addon.addon.security.GvNix509TrustManager.java
/** * Export the given certificate to a file in SRC_MAIN_RESOURCES. The cert * file will have given <code>{alias}.cer</code> as file name. * <p>//from w w w. j av a 2s .c o m * <b>We don't use Roo FileManager API</b> here in order to create cert * files because in this way if we have any problem importing them to the * JVM <code>cacerts</cacerts> Roo won't undo the cert files creation. * </p> * * @param alias * @param cert * @param fileManager * @param pathResolver * @throws Exception */ public static void saveCertFile(String alias, X509Certificate cert, FileManager fileManager, PathResolver pathResolver) throws Exception { String aliasCerFileName = alias.concat(".cer"); String cerFilePath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_RESOURCES, ""), aliasCerFileName); if (!fileManager.exists(cerFilePath)) { File cerFile = new File(cerFilePath); OutputStream os = null; try { os = new FileOutputStream(cerFile); os.write(cert.getEncoded()); } finally { IOUtils.closeQuietly(os); } logger.info("Created ".concat(Path.SRC_MAIN_RESOURCES.name()).concat("/").concat(aliasCerFileName)); } }
From source file:com.baasbox.service.push.providers.GCMServer.java
public static void validateApiKey(String apikey) throws MalformedURLException, IOException, PushInvalidApiKeyException { Message message = new Message.Builder().addData("message", "validateAPIKEY").build(); Sender sender = new Sender(apikey); List<String> deviceid = new ArrayList<String>(); deviceid.add("ABC"); Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); jsonRequest.put(JSON_REGISTRATION_IDS, deviceid); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); }/* www . ja v a 2 s. co m*/ String requestBody = JSONValue.toJSONString(jsonRequest); String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); byte[] bytes = requestBody.getBytes(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + apikey); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); int status = conn.getResponseCode(); if (status != 200) { if (status == 401) { throw new PushInvalidApiKeyException("Wrong api key"); } if (status == 503) { throw new UnknownHostException(); } } }
From source file:org.droidparts.http.worker.HttpURLConnectionWorker.java
public static void postOrPut(HttpURLConnection conn, String contentType, String data) throws HTTPException { conn.setRequestProperty("Accept-Charset", UTF8); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Connection", "Keep-Alive"); OutputStream os = null; try {/*from w w w . j a va2 s . c o m*/ os = conn.getOutputStream(); os.write(data.getBytes(UTF8)); } catch (Exception e) { throw new HTTPException(e); } finally { silentlyClose(os); } }
From source file:Main.java
public static void writeNumber(OutputStream out, long s, int len, boolean big_endian) throws IOException { if (len <= 0 || len > 8) throw new IllegalArgumentException("length must between 1 and 8."); byte[] buffer = numberToBytes(s, len, big_endian); out.write(buffer); out.flush();//w ww.jav a 2 s. c o m }
From source file:com.fluidops.iwb.cms.util.IWBCmsUtil.java
public static File upload(String filename, Resource subject, InputStream is, Collector collector) throws FileNotFoundException, IOException { if (Config.getConfig().uploadFileClass().equals(LocalFile.class.getName())) GenUtil.mkdirs(IWBFileUtil.getUploadFolder()); File file = uploadedFileFor(filename); if (file.exists()) throw new IllegalStateException("Error during upload: File " + filename + " already exists."); ReadWriteDataManager dm = null;//from w w w. j a v a 2s . co m try { dm = ReadWriteDataManagerImpl.openDataManager(Global.repository); OutputStream out = file.getOutputStream(); out.write(GenUtil.readUrlToBuffer(is).toByteArray()); out.flush(); out.close(); // if we have a page subject, write triple (subject, hasFile, file) ValueFactory vf = ValueFactoryImpl.getInstance(); Context c = Context.getFreshUserContextWithURI(getFileContextURI(file), ContextLabel.FILE_UPLOAD); c.setEditable(false); if (subject != null) dm.addToContext(vf.createStatement(subject, Vocabulary.SYSTEM.ATTACHEDFILE, file.getURI()), c); dm.addToContext(collector.collectRDF(file, file.getURI()), c); return file; } finally { ReadWriteDataManagerImpl.closeQuietly(dm); } }
From source file:com.chicm.cmraft.rpc.PacketUtils.java
public static void writeIntToStream(int n, OutputStream os) throws IOException { byte[] b = int2Bytes(n); os.write(b); }
From source file:org.shareok.data.webserv.WebUtil.java
public static void setupFileDownload(HttpServletResponse response, String downloadPath) { try {/*from w w w .jav a 2 s.co m*/ File file = new File(downloadPath); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException ioex) { logger.error("Cannot set up a file download.", ioex); } }
From source file:org.shareok.data.webserv.WebUtil.java
public static void downloadFileFromServer(HttpServletResponse response, String downloadPath) { try {/*from w w w.java2 s. c om*/ File file = new File(downloadPath); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException ioex) { logger.error("Cannot download file responding to downloading resquest!", ioex); } }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void SendNotification(int userId, int notificationCounter) { String msg[] = new String[2]; if (notificationCounter > 1) msg = new String[] { "Tienes " + notificationCounter + " nuevas notificaciones.", "/topics/" + userId }; else// w w w .ja v a 2 s . c om msg = new String[] { "Tienes " + notificationCounter + " nueva notificacion.", "/topics/" + userId }; if (msg.length < 1 || msg.length > 2 || msg[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println( "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and // where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", msg[0].trim()); // Where to send GCM message. if (msg.length > 1 && msg[1] != null) { jGcmData.put("to", msg[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); updateNotificationAsSent(userId); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); log.error(e.getMessage()); e.printStackTrace(); } }
From source file:ReadTemp.java
/** Executes the given applescript code and returns the first line of the output as a string *//*from www . ja v a 2 s. c o m*/ static String doApplescript(String script) { String line; try { // Start applescript Process p = Runtime.getRuntime().exec("/usr/bin/osascript -s o -"); // Send applescript via stdin OutputStream stdin = p.getOutputStream(); stdin.write(script.getBytes()); stdin.flush(); stdin.close(); // get first line of output BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); line = input.readLine(); input.close(); // If we get an exit code, print it out if (p.waitFor() != 0) { System.err.println("exit value = " + p.exitValue()); System.err.println(line); } return line; } catch (Exception e) { System.err.println(e); } return ""; }