List of usage examples for java.io BufferedOutputStream write
@Override public synchronized void write(int b) throws IOException
From source file:org.iti.agrimarket.view.UpdateOfferController.java
/** * upload image and form data/*from www . j ava2 s .c o m*/ * */ @RequestMapping(method = RequestMethod.POST, value = { "/updateoffer.htm" }) public String updateOffer(@RequestParam("description") String description, @RequestParam("quantity") float quantity, @RequestParam("quantityunit") int quantityunit, @RequestParam("unitprice") int unitprice, @RequestParam("price") float price, @RequestParam("mobile") String mobile, @RequestParam("governerate") String governerate, @RequestParam("product") int product, @RequestParam("file") MultipartFile file, @RequestParam("offerId") int offerId, @ModelAttribute("user") User userFromSession, RedirectAttributes redirectAttributes, Model model, HttpServletRequest request) { System.out.println("product id PPPPPPPPPPPPPPPPPPPPPP:" + product); UserOfferProductFixed userOfferProductFixed = offerService.findUserOfferProductFixed(offerId); if (userOfferProductFixed != null) { userOfferProductFixed.setDescription(description); userOfferProductFixed.setPrice(price); userOfferProductFixed.setQuantity(quantity); userOfferProductFixed.setProduct(productService.getProduct(product)); userOfferProductFixed.setUnitByUnitId(unitService.getUnit(quantityunit)); userOfferProductFixed.setUnitByPricePerUnitId(unitService.getUnit(unitprice)); userOfferProductFixed.setUser(userFromSession); userOfferProductFixed.setUserLocation(governerate); userOfferProductFixed.setUserPhone(mobile); offerService.updateOffer(userOfferProductFixed); } if (!file.isEmpty()) { String fileName = userOfferProductFixed.getId() + String.valueOf(new Date().getTime()); try { System.out.println("fileName :" + fileName); byte[] bytes = file.getBytes(); System.out.println(new String(bytes)); MagicMatch match = Magic.getMagicMatch(bytes); final String ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.OFFER_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream( new File(Constants.IMAGE_PATH + Constants.USER_PATH + fileName + ext))); stream.write(bytes); stream.close(); userOfferProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.USER_PATH + fileName + ext); System.out.println("image url" + userOfferProductFixed.getImageUrl()); offerService.updateOffer(userOfferProductFixed); } catch (Exception e) { // logger.error(e.getMessage()); offerService.deleteOffer(userOfferProductFixed.getId()); // delete the category if something goes wrong redirectAttributes.addFlashAttribute("message", "You failed to upload because the file was empty"); return "redirect:/web/updateoffer.htm"; } } else { redirectAttributes.addFlashAttribute("message", "You failed to upload because the file was empty"); } //User user = userService.getUserByEmail(userFromSession.getMail()); // model.addAttribute("user", user); User oldUser = (User) request.getSession().getAttribute("user"); if (oldUser != null) { User user = userService.getUserEager(oldUser.getId()); request.getSession().setAttribute("user", user); model.addAttribute("user", user); } return "profile"; }
From source file:nl.phanos.liteliveresultsclient.LoginHandler.java
public void getZip() throws Exception { String url = "https://www.atletiek.nu/feeder.php?page=exportstartlijstentimetronics&event_id=" + nuid + "&forceAlleenGeprinteLijsten=1"; System.out.println(url);//from ww w .j av a 2 s.c o m HttpGet request = new HttpGet(url); request.setHeader("User-Agent", USER_AGENT); request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); request.setHeader("Accept-Language", "en-US,en;q=0.5"); request.setHeader("Cookie", getCookies()); HttpResponse response = client.execute(request); int responseCode = response.getStatusLine().getStatusCode(); System.out.println("Response Code : " + responseCode); //System.out.println(convertStreamToString(response.getEntity().getContent())); BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent()); String filePath = "tmp.zip"; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); // set cookies setCookies(response.getFirstHeader("Set-Cookie") == null ? "" : response.getFirstHeader("Set-Cookie").toString()); request.releaseConnection(); }
From source file:org.anon.smart.smcore.test.channel.upload.TestUploadEvent.java
private String downloadFile(String file) throws Exception { HttpClient httpclient = new DefaultHttpClient(); String dwnFile = file + ".1"; HttpGet httpget = new HttpGet("http://localhost:9020/errortenant/ErrorCases/DownloadEvent/" + file); HttpResponse response = httpclient.execute(httpget); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try {//w w w. j ava 2s. c o m BufferedInputStream bis = new BufferedInputStream(instream); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(new File(projectHome + "/" + dwnFile))); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { instream.close(); } httpclient.getConnectionManager().shutdown(); } return dwnFile; }
From source file:de.tudarmstadt.ukp.dkpro.core.io.mmax2.MMAXWriter.java
/** * Copies a source folder/file to a target folder/file. Used to duplicate the template project and template files. * @param source/*from w w w. jav a2 s . c o m*/ * @param target * @throws IOException */ private void copy(File source, File target) throws IOException { if (source.isFile() && !target.exists()) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); int i; while ((i = in.read()) != -1) { out.write(i); } in.close(); out.close(); log.trace(target.getName() + " copied."); } if (source.isDirectory()) { target.mkdirs(); File[] files = source.listFiles(); for (File file : files) { if (!file.getName().endsWith(".svn")) { // do not copy svn files! copy(file, new File(target, file.getName())); } } } }
From source file:org.iti.agrimarket.service.UserRestController.java
/** * @author Amr/* www . j a v a 2s .c o m*/ * @param json * @return success */ @RequestMapping(value = Constants.UPDATE_USER_URL, method = RequestMethod.POST) public Response updateUser(@RequestBody String param) { User user = paramExtractor.getParam(param, User.class); if (user.getId() == null || (userServiceInterface.getUser(user.getId())) == null) { // return missing parameter error logger.trace(Constants.INVALID_PARAM); return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build(); } //Use the generated id to form the image name String name = user.getId() + String.valueOf(new Date().getTime()); if (user.getImage() != null) { try { byte[] bytes = user.getImage(); MagicMatch match = Magic.getMagicMatch(bytes); final String ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.USER_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.USER_PATH + name))); stream.write(bytes); stream.close(); user.setImageUrl(Constants.IMAGE_PRE_URL + Constants.USER_PATH + name + ext); userServiceInterface.updateUser(user); } catch (Exception e) { logger.error(e.getMessage()); return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build(); } } else { userServiceInterface.updateUser(user); } return Response.ok(Constants.SUCCESS_JSON, MediaType.APPLICATION_JSON).build(); }
From source file:com.sangupta.clitools.file.RandomFile.java
private void createFile(int bytes, File file) { final int bufferSize = 2048; if (bytes < bufferSize) { byte[] data = new byte[bytes]; fillRandomData(data);//from ww w. jav a 2s .c om try { FileUtils.writeByteArrayToFile(file, data); } catch (IOException e) { System.out.println("Unable to write file to disk."); e.printStackTrace(); } return; } final long chunks = bytes / bufferSize; byte[] data = new byte[bufferSize]; FileOutputStream fileStream = null; BufferedOutputStream stream = null; try { fileStream = new FileOutputStream(file); stream = new BufferedOutputStream(fileStream); for (int ch = 0; ch < chunks; ch++) { if (!this.fastMode) { fillRandomData(data); } stream.write(data); } // last min chunk int pending = bytes % bufferSize; if (pending == 0) { return; } data = new byte[pending]; fillRandomData(data); stream.write(data); } catch (FileNotFoundException e) { // this should never happen } catch (IOException e) { System.out.println("Unable to write file to disk."); e.printStackTrace(); return; } finally { IOUtils.closeQuietly(stream); IOUtils.closeQuietly(fileStream); } }
From source file:org.iti.agrimarket.view.SignUpController.java
/** * Amr/* w w w . j a v a2 s . c o m*/ * */ @RequestMapping(method = RequestMethod.POST, value = "/signupgplusstep2") public String signupUserFb(Model model, @RequestParam("mobile") String mobil, @RequestParam("governerate") String governerate, HttpServletRequest request, HttpServletResponse response) { System.out.println("save user func fb2 google plus---------"); // System.out.println("image : "+img); User userStore = new User(); userStore.setGovernerate("Giza"); if (userEmail == null | userName == null) { return "redirect:signup.htm"; } userStore.setMail(userEmail); userStore.setFullName(userName); userStore.setMobile(mobil); userStore.setGovernerate(governerate); userStore.setLat(0.0); userStore.setLong_(0.0); userStore.setLoggedIn(true); userStore.setRatesAverage(0); userStore.setRegistrationChannel(0); // web userStore.setImageUrl("images/amr.jpg"); userService.addUser(userStore); User user = userService.getUserByEmail(userStore.getMail()); if (imgUrl != null) { String fileName = user.getId() + String.valueOf(new Date().getTime()); URL url; try { url = new URL(imgUrl); InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] bytes = out.toByteArray(); MagicMatch match = Magic.getMagicMatch(bytes); final String ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.USER_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.USER_PATH + fileName))); stream.write(bytes); stream.close(); user.setImageUrl(Constants.IMAGE_PRE_URL + Constants.USER_PATH + fileName + ext); userService.updateUser(user); } catch (MalformedURLException ex) { java.util.logging.Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); userService.deleteUser(user); // delete the category if something goes wrong return "signup"; } catch (IOException ex) { java.util.logging.Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); userService.deleteUser(user); // delete the category if something goes wrong return "signup"; } catch (MagicParseException ex) { java.util.logging.Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); userService.deleteUser(user); // delete the category if something goes wrong return "signup"; } catch (MagicMatchNotFoundException ex) { java.util.logging.Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); userService.deleteUser(user); // delete the category if something goes wrong return "signup"; } catch (MagicException ex) { java.util.logging.Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); userService.deleteUser(user); // delete the category if something goes wrong return "signup"; } } else { user.setImageUrl(Constants.IMAGE_PRE_URL + Constants.USER_PATH + "default_user.jpg"); userService.updateUser(user); } model.addAttribute("user", user); System.out.println("i Stored user in the DB"); return "redirect:/index.htm"; }
From source file:org.iti.agrimarket.service.UserRestController.java
/** * @author Amr/* w w w .j a v a2 s. c om*/ * @param json * @return user Id */ @RequestMapping(value = Constants.ADD_USER_URL, method = RequestMethod.POST) public Response addUser(@RequestBody String param) { User user = paramExtractor.getParam(param, User.class); if (!validateUser(user)) { // return missing parameter error logger.trace(Constants.INVALID_PARAM); return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build(); } user.setLoggedIn(true); int res = userServiceInterface.addUser(user); if (user.getId() == null) { logger.trace(Constants.DB_ERROR); return Response.status(Constants.DB_ERROR).build(); } //Use the generated id to form the image name String name = user.getId() + String.valueOf(new Date().getTime()); if (user.getImage() != null) { try { byte[] bytes = user.getImage(); MagicMatch match = Magic.getMagicMatch(bytes); final String ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.USER_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.USER_PATH + name))); stream.write(bytes); stream.close(); user.setImageUrl(Constants.IMAGE_PRE_URL + Constants.USER_PATH + name + ext); userServiceInterface.updateUser(user); } catch (Exception e) { logger.error(e.getMessage()); userServiceInterface.deleteUser(user); // delete the category if something goes wrong return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build(); } } else { } return Response.ok("{\"" + Constants.ID_PARAM + "\":" + user.getId() + "}", MediaType.APPLICATION_JSON) .build(); }
From source file:fr.enseirb.odroidx.videomanager.Uploader.java
public void doUpload(Uri myFile) { createNotification();/* w ww . j a v a 2s . com*/ File f = new File(myFile.getPath()); SendName(f.getName().replace(' ', '-')); Log.e(getClass().getSimpleName(), "test: " + f.exists()); if (f.exists()) { Socket s; try { Log.e(getClass().getSimpleName(), "test: " + server_ip); s = new Socket(InetAddress.getByName(server_ip), 5088);// Bug // using // variable // port OutputStream fluxsortie = s.getOutputStream(); int nb_parts = (int) (f.length() / PART_SIZE); InputStream in = new BufferedInputStream(new FileInputStream(f)); ByteArrayOutputStream byte_array = new ByteArrayOutputStream(); BufferedOutputStream buffer = new BufferedOutputStream(byte_array); byte[] to_write = new byte[PART_SIZE]; for (int i = 0; i < nb_parts; i++) { in.read(to_write, 0, PART_SIZE); buffer.write(to_write); buffer.flush(); fluxsortie.write(byte_array.toByteArray()); byte_array.reset(); if ((i % 250) == 0) { mBuilder.setProgress(nb_parts, i, false); mNotifyManager.notify(NOTIFY_ID, mBuilder.getNotification()); } } int remaining = (int) (f.length() - nb_parts * PART_SIZE); in.read(to_write, 0, remaining); buffer.write(to_write); buffer.flush(); fluxsortie.write(byte_array.toByteArray()); byte_array.reset(); buffer.close(); fluxsortie.close(); in.close(); s.close(); } catch (ConnectException e) { if (STATUS != HTTP_SERVER) STATUS = CONNECTION_ERROR; e.printStackTrace(); } catch (UnknownHostException e) { if (STATUS != HTTP_SERVER) STATUS = UNKNOWN; Log.i(getClass().getSimpleName(), "Unknown host"); e.printStackTrace(); } catch (IOException e) { if (STATUS != HTTP_SERVER) STATUS = CONNECTION_ERROR; e.printStackTrace(); } } }
From source file:gobblin.tunnel.TalkPastServer.java
@Override void handleClientSocket(Socket clientSocket) throws IOException { LOG.info("Writing to client"); try {// w w w . j a va 2s . c o m final BufferedOutputStream serverOut = new BufferedOutputStream(clientSocket.getOutputStream()); EasyThread clientWriterThread = new EasyThread() { @Override void runQuietly() throws Exception { long t = System.currentTimeMillis(); try { for (int i = 0; i < nMsgs; i++) { serverOut.write(generateMsgFromServer(i).getBytes()); sleepQuietly(2); } } catch (IOException e) { e.printStackTrace(); } LOG.info("Server done writing in " + (System.currentTimeMillis() - t) + " ms"); } }.startThread(); _threads.add(clientWriterThread); BufferedReader serverIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String line = serverIn.readLine(); while (line != null && !line.equals("Goodbye")) { String[] tokens = line.split(":", 2); String client = tokens[0]; digestMsgsRecvdAtServer.get(client).update(line.getBytes()); digestMsgsRecvdAtServer.get(client).update("\n".getBytes()); line = serverIn.readLine(); } LOG.info("Server done reading"); try { clientWriterThread.join(); } catch (InterruptedException e) { } serverOut.write("Goodbye\n".getBytes()); serverOut.flush(); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); throw e; } }