Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

In this page you can find the example usage for java.io BufferedOutputStream write.

Prototype

@Override
public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte to this buffered output stream.

Usage

From source file:org.iti.agrimarket.administration.view.AddCategoryController.java

/**
 * Amr upload image and form data/*w  w w .  j av  a2 s. com*/
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/addcategory")
public String addCategory(@RequestParam("nameAr") String nameAr, @RequestParam("nameEn") String nameEn,
        @RequestParam("parentCategoryId") int parentCategoryId, @RequestParam("file") MultipartFile file) {

    System.out.println("save user func ---------");
    System.out.println("full Name :" + nameAr);

    Category category = new Category();
    category.setNameAr(nameAr);
    category.setNameEn(nameEn);
    Category parentCategory = categoryService.getCategory(parentCategoryId);

    category.setCategory(parentCategory);

    category.setSoundUrl("/to be continue");
    int res = categoryService.addCategory(category);

    if (!file.isEmpty()) {
        String fileName = category.getId() + String.valueOf(new Date().getTime());

        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH + fileName)));
            stream.write(bytes);

            stream.close();
            category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + fileName + ext);
            categoryService.updateCategory(category);
        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong
            return "redirect:/admin/categories_page.htm";
        }

    } else {

        category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + "default_category.jpg");
        categoryService.updateCategory(category);

    }

    return "redirect:/admin/categories_page.htm";
}

From source file:org.iti.agrimarket.administration.view.AddProductController.java

/**
 * Amr upload image and form data/*from w  w  w .j a  va2s .com*/
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/addproduct")
public String addproduct(@RequestParam("nameAr") String nameAr, @RequestParam("nameEn") String nameEn,
        @RequestParam("parentCategoryId") int parentCategoryId, @RequestParam("file") MultipartFile file) {

    System.out.println("save user func ---------");
    System.out.println("full Name :" + nameAr);

    Product product = new Product();
    product.setNameAr(nameAr);

    product.setNameEn(nameEn);
    Category parentCategory = categoryService.getCategory(parentCategoryId);

    product.setCategory(parentCategory);

    product.setSoundUrl("/to be continue");

    int res = productService.addProduct(product);

    if (!file.isEmpty()) {
        String fileName = product.getId() + String.valueOf(new Date().getTime());

        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.PRODUCT_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.PRODUCT_PATH + fileName)));
            stream.write(bytes);

            stream.close();
            product.setImageUrl(Constants.IMAGE_PRE_URL + Constants.PRODUCT_PATH + fileName + ext);
            productService.updateProduct(product);
        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            productService.deleteProduct(product.getId()); // delete the category if something goes wrong
            return "redirect:/admin/products_page.htm";
        }

    } else {

        product.setImageUrl(Constants.IMAGE_PRE_URL + Constants.PRODUCT_PATH + "default_category.jpg");
        productService.updateProduct(product);

    }

    return "redirect:/admin/products_page.htm";
}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/singleSave", method = RequestMethod.POST)
public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file,
        @RequestParam("desc") String desc) {
    System.out.println("File Description:" + desc);
    String fileName = null;//from   w  ww  .  ja va  2  s  . c o  m
    if (!file.isEmpty()) {
        try {
            fileName = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            BufferedOutputStream buffStream = new BufferedOutputStream(
                    new FileOutputStream(new File("C:/cp/" + fileName)));
            buffStream.write(bytes);
            buffStream.close();
            return "You have successfully uploaded " + fileName;
        } catch (Exception e) {
            return "You failed to upload " + fileName + ": " + e.getMessage();
        }
    } else {
        return "Unable to upload. File is empty.";
    }
}

From source file:com.pipinan.githubcrawler.GithubCrawler.java

/**
 *
 * @param username the owner name of respoitory
 * @param reponame the name of respoitory
 * @param path which folder would you like to save the zip file
 * @throws IOException//from   w  w  w. j a  v a2  s  .c  o  m
 */
public void crawlRepoZip(String username, String reponame, String path) throws IOException {
    GHRepository repo = github.getRepository(username + "/" + reponame);

    HttpClient httpclient = getHttpClient();
    //the url pattern is https://github.com/"USER_NAME"/"REPO_NAME"/archive/master.zip
    HttpGet httpget = new HttpGet("https://github.com/" + username + "/" + reponame + "/archive/master.zip");
    HttpResponse response = httpclient.execute(httpget);
    try {
        System.out.println(response.getStatusLine());
        if (response.getStatusLine().toString().contains("200 OK")) {

            //the header "Content-Disposition: attachment; filename=JSON-java-master.zip" can find the filename
            String filename = null;
            Header[] headers = response.getHeaders("Content-Disposition");
            for (Header header : headers) {
                System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
                String tmp = header.getValue();
                filename = tmp.substring(tmp.lastIndexOf("filename=") + 9);
            }

            if (filename == null) {
                System.err.println("Can not find the filename in the response.");
                System.exit(-1);
            }

            HttpEntity entity = response.getEntity();

            BufferedInputStream bis = new BufferedInputStream(entity.getContent());
            String filePath = path + filename;
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();

            EntityUtils.consume(entity);
        }
    } finally {

    }

}

From source file:android.webkit.cts.CtsTestServer.java

private static FileEntity createFileEntity(String downloadId, int numBytes) throws IOException {
    String storageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equalsIgnoreCase(storageState)) {
        File storageDir = Environment.getExternalStorageDirectory();
        File file = new File(storageDir, downloadId + ".bin");
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
        byte data[] = new byte[1024];
        for (int i = 0; i < data.length; i++) {
            data[i] = 1;/*from ww  w . j  a v a  2 s . c o m*/
        }
        try {
            for (int i = 0; i < numBytes / data.length; i++) {
                stream.write(data);
            }
            stream.write(data, 0, numBytes % data.length);
            stream.flush();
        } finally {
            stream.close();
        }
        return new FileEntity(file, "application/octet-stream");
    } else {
        throw new IllegalStateException("External storage must be mounted for this test!");
    }
}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/multipleSave", method = RequestMethod.POST)
public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files) {
    String fileName = null;/*from  w  w  w.  j a v  a2  s  .  com*/
    String msg = "";
    if (files != null && files.length > 0) {
        for (int i = 0; i < files.length; i++) {
            try {
                fileName = files[i].getOriginalFilename();
                byte[] bytes = files[i].getBytes();
                BufferedOutputStream buffStream = new BufferedOutputStream(
                        new FileOutputStream(new File("C:/cp/" + fileName)));
                buffStream.write(bytes);
                buffStream.close();
                msg += "You have successfully uploaded " + fileName + "<br/>";
            } catch (Exception e) {
                return "You failed to upload " + fileName + ": " + e.getMessage() + "<br/>";
            }
        }
        return msg;
    } else {
        return "Unable to upload. File is empty.";
    }
}

From source file:com.sshdemo.common.report.manage.service.RepositoryService.java

@Override
public void publishRepository(List<Long> repositoryIds) {
    for (Long repositoryId : repositoryIds) {
        Repository repository = findRepositoryById(repositoryId);
        String type = repository.getType();
        byte[] bytes = repository.getEntity();
        String outputFile = repository.getName() + "." + type;

        //         Resource.Type resourceType = Resource.Type.ANNEX;
        //         if (type.toLowerCase().equals("png")) {
        //            resourceType = Resource.Type.IMAGE;
        //         }

        File file = null;/* ww w  .  j  a v a2 s .  co  m*/
        FileOutputStream fileStream = null;
        BufferedOutputStream bufferStream = null;
        try {
            file = new File(outputFile);
            fileStream = new FileOutputStream(file);
            bufferStream = new BufferedOutputStream(fileStream);
            bufferStream.write(bytes);
            //TODO ??

            //            resourceService.upload(site, file, outputFile, resourceType);

            repository.setPublishDate(new Date(Calendar.getInstance().getTime().getTime()));
            repositoryDAO.merge(repository);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (IOException e) {
                }
                fileStream = null;
            }
            if (bufferStream != null) {
                try {
                    bufferStream.close();
                } catch (IOException e) {
                }
                bufferStream = null;
            }
            file = null;
        }
    }
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Sends a string via POST to a given url.
 *
 * @param context      the context to use.
 * @param urlStr       the url to which to send to.
 * @param string       the string to send as post body.
 * @param user         the user or <code>null</code>.
 * @param password     the password or <code>null</code>.
 * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message.
 * @return the response./*from   w ww.  j  av  a 2s  .c  om*/
 * @throws Exception if something goes wrong.
 */
public static String sendPost(Context context, String urlStr, String string, String user, String password,
        boolean readResponse) throws Exception {
    BufferedOutputStream wr = null;
    HttpURLConnection conn = null;
    try {
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(false);
        if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        // Make server believe we are form data...
        wr = new BufferedOutputStream(conn.getOutputStream());
        byte[] bytes = string.getBytes();
        wr.write(bytes);
        wr.flush();

        int responseCode = conn.getResponseCode();
        if (readResponse) {
            StringBuilder returnMessageBuilder = new StringBuilder();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                while (true) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    returnMessageBuilder.append(line + "\n");
                }
                br.close();
            }

            return returnMessageBuilder.toString();
        } else {
            return getMessageForCode(context, responseCode,
                    context.getResources().getString(R.string.post_completed_properly));
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:com.groupon.odo.controllers.BackupController.java

/**
 * Set client server configuration and overrides according to backup
 *
 * @param fileData File containing profile overrides and server configuration
 * @param profileID Profile to update for client
 * @param clientUUID Client to apply overrides to
 * @param odoImport Param to determine if an odo config will be imported with the overrides import
 * @return// w w  w .  ja va2s .  c  om
 * @throws Exception
 */
@RequestMapping(value = "/api/backup/profile/{profileID}/{clientUUID}", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> processSingleProfileBackup(
        @RequestParam("fileData") MultipartFile fileData, @PathVariable int profileID,
        @PathVariable String clientUUID,
        @RequestParam(value = "odoImport", defaultValue = "false") boolean odoImport) throws Exception {
    if (!fileData.isEmpty()) {
        try {
            // Read in file
            InputStream inputStream = fileData.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String singleLine;
            String fullFileString = "";
            while ((singleLine = bufferedReader.readLine()) != null) {
                fullFileString += singleLine;
            }
            JSONObject fileBackup = new JSONObject(fullFileString);

            if (odoImport) {
                JSONObject odoBackup = fileBackup.getJSONObject("odoBackup");
                byte[] bytes = odoBackup.toString().getBytes();
                // Save to second file to be used in importing odo configuration
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File("backup-uploaded.json")));
                stream.write(bytes);
                stream.close();
                File f = new File("backup-uploaded.json");
                BackupService.getInstance().restoreBackupData(new FileInputStream(f));
            }

            // Get profile backup if json contained both profile backup and odo backup
            if (fileBackup.has("profileBackup")) {
                fileBackup = fileBackup.getJSONObject("profileBackup");
            }

            // Import profile overrides
            BackupService.getInstance().setProfileFromBackup(fileBackup, profileID, clientUUID);
        } catch (Exception e) {
            try {
                JSONArray errorArray = new JSONArray(e.getMessage());
                return new ResponseEntity<>(errorArray.toString(), HttpStatus.BAD_REQUEST);
            } catch (Exception k) {
                // Catch for exceptions other than ones defined in backup service
                return new ResponseEntity<>("[{\"error\" : \"Upload Error\"}]", HttpStatus.BAD_REQUEST);
            }
        }
    }

    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:de.knurt.fam.template.controller.letter.EMailLetterAdapter.java

/**
 * send the email and return an errormessage. if errormessage is empty,
 * sending succeeded.//w  w w.  j  a va 2s. co  m
 * 
 * @param post
 *            getting the input stream from
 * @param customid
 *            for the to send via email
 * @return an errormessage (may empty on success)
 */
public String send(PostMethod post, String customid) {
    String errormessage = "";
    if (this.isValid()) {

        File file = null;
        try {
            file = this.getTmpFile(customid);

        } catch (IOException e) {
            FamLog.exception(e, 201106131728l);
            errormessage += "Fail: Create tmp file [201106131729].";
        }

        try {
            InputStream is = post.getResponseBodyAsStream();

            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            int bite = 0;
            while ((bite = is.read()) >= 0) {
                bos.write(bite);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            errormessage += "Fail: Write pdf to tmp file [201106141055].";
            FamLog.exception(e, 201106131733l);
        }

        Email mail = this.getEMail(file, this);
        if (mail == null) {
            errormessage += "Fail: Create e-mail object. Please check log files [201106141058].";
        }
        boolean succ = UserMailSender.sendWithoutUserBox(mail);
        if (!succ) {
            errormessage += "Fail: Send email through configured server. Please check log files [201106131756].";
        }

    } else {
        if (this.getTo() == null) {
            errormessage += "Fail: Find an recipient - form email_recipient sent? [201106131757]";
        } else {
            errormessage += "Invalid email address. Recheck email recipient.";
        }
    }
    return errormessage;
}