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:com.balero.controllers.UploadController.java

/**
 * Upload file on server/*from  w ww . jav a 2 s  .  c om*/
 *
 * @param file HTML <input type="file"> content
 * @param baleroAdmin Magic cookie
 * @return home view
 */
@RequestMapping(method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file,
        @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin,
        HttpServletRequest request) {

    // Security
    UsersAuth security = new UsersAuth();
    security.setCredentials(baleroAdmin, UsersDAO);
    boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword());
    if (!securityFlag)
        return "hacking";

    String inputFileName = file.getOriginalFilename();

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            //String rootPath = System.getProperty("catalina.home");
            File dir = new File("../webapps/media/uploads");
            if (!dir.exists())
                dir.mkdirs();

            String[] ext = new String[9];
            // Add your extension here
            ext[0] = ".jpg";
            ext[1] = ".png";
            ext[2] = ".bmp";
            ext[3] = ".jpeg";

            for (int i = 0; i < ext.length; i++) {
                int intIndex = inputFileName.indexOf(ext[i]);
                if (intIndex == -1) {
                    System.out.println("File extension is not valid");
                } else {
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                }
            }

            System.out.println("You successfully uploaded file");

        } catch (Exception e) {
            System.out.println("You failed to upload => " + e.getMessage());
        }
    } else {
        System.out.println("You failed to upload because the file was empty.");
    }

    String referer = request.getHeader("Referer");
    return "redirect:" + referer;

}

From source file:org.iti.agrimarket.service.CategoryRestController.java

/**
 * Responsible for adding new category/*from w  w  w.  j  a  va  2s  . c o m*/
 *
 * @param paramJsoncontains Json object of the category's data, and parent
 * category id
 * @param user Name of the user sending the request
 * @param key Encrypted key using the user's key
 * @param file The image of the product
 * @return Json {"success":1} if added successfully or status code with the
 * error
 */
@RequestMapping(value = Constants.ADD_CATEGORY_URL, method = RequestMethod.POST)
public Response addCategory(@RequestBody String paramJson) {

    //Parse the parameter
    Category category = paramExtractor.getParam(paramJson, Category.class);

    //Validate category
    if (category == null
            || ((category.getNameAr() == null || category.getNameAr().isEmpty())
                    && (category.getNameEn() == null || category.getNameEn().isEmpty()))
            || ((category.getNameAr() != null && category.getNameAr().length() > 44)
                    || (category.getNameEn() != null && category.getNameEn().length() > 44))) {
        logger.trace(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }

    //Check parent category
    if (category.getCategory() == null) {
        category.setCategory(category);
    } else {
        Category parent = categoryService.getCategory(category.getCategory().getId());
        if (parent == null) {
            logger.trace(NO_CATEGORY);
            return Response.status(Constants.PARAM_ERROR).entity(NO_CATEGORY).build();
        }

        category.setCategory(parent);
    }

    //Add category
    categoryService.addCategory(category);

    if (category == null || category.getId() == -1) {

        logger.trace(Constants.DB_ERROR);
        return Response.status(Constants.DB_ERROR).build();
    }

    //Use the generated id to form the image name
    String name = category.getId() + String.valueOf(new Date().getTime());

    //Save image if not empty file
    if (category.getImage() != null) {
        try {
            byte[] bytes = category.getImage();
            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 + name)));
            stream.write(bytes);
            stream.close();

            //Set the image url in the db
            category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + name + ext);

            categoryService.updateCategory(category);
        } catch (Exception e) {
            logger.error(e.getMessage());

            categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong
            return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
        }
    } else {
        categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong
        return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
    }

    return Response.ok(Constants.SUCCESS_JSON, MediaType.APPLICATION_JSON).build();
}

From source file:com.balero.controllers.UploadController.java

/**
 * Upload image from CKEDITOR to server// w  w  w  . j a  v a2s . c om
 *
 * Source: http://alfonsoml.blogspot.mx/2013/08/a-basic-
 * upload-script-for-ckeditor.html
 *
 * @param file HTML <input>
 * @param model Framework model layer
 * @param request HTTP headers
 * @param baleroAdmin Magic cookie
 * @return view
 */
@RequestMapping(value = "/picture", method = RequestMethod.POST)
public String uploadPicture(@RequestParam("upload") MultipartFile file, Model model, HttpServletRequest request,
        @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin) {

    // Security
    UsersAuth security = new UsersAuth();
    security.setCredentials(baleroAdmin, UsersDAO);
    boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword());
    if (!securityFlag)
        return "hacking";

    String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");

    String inputFileName = file.getOriginalFilename();

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            //String rootPath = System.getProperty("catalina.home");
            File dir = new File("../webapps/media/pictures");
            if (!dir.exists())
                dir.mkdirs();

            String[] ext = new String[9];
            // Add your extension here
            ext[0] = ".jpg";
            ext[1] = ".png";
            ext[2] = ".bmp";
            ext[3] = ".jpeg";

            for (int i = 0; i < ext.length; i++) {
                int intIndex = inputFileName.indexOf(ext[i]);
                if (intIndex == -1) {
                    System.out.println("File extension is not valid");
                } else {
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                }
            }

            System.out.println("You successfully uploaded file");

        } catch (Exception e) {
            System.out.println("You failed to upload => " + e.getMessage());
        }
    } else {
        System.out.println("You failed to upload because the file was empty.");
    }

    //String url = request.getLocalAddr();

    model.addAttribute("url", "/media/pictures/" + inputFileName);
    model.addAttribute("CKEditorFuncNum", CKEditorFuncNum);

    return "upload";

}

From source file:com.orchestra.portale.controller.EditDeepeningPageController.java

@RequestMapping(value = "/updatedpage", method = RequestMethod.POST)
public ModelAndView updatePoi(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    DeepeningPage poi = pm.findDeepeningPage(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }/*from  w w  w  .jav  a 2s.  co m*/
    }
    ModelAndView model = new ModelAndView("okpageadmin");
    model.addObject("mess", "PAGINA MODIFICATA CORRETTAMENTE!");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));

    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 0) {
        while (i < files.length) {
            ImgGallery img = new ImgGallery();
            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("newcredit" + (i + 1)))
                img.setCredit(params.get("newcredit" + (i + 1)));
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1)))
                img.setCredit(params.get("credit" + (iximg + 1)));
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {

        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    poi.setComponents(listComponent);

    pm.saveDeepeningPage(poi);

    DeepeningPage poi2 = pm.findDeepeningPageByName(poi.getName());

    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.out.println("FILE CREATO IN POSIZIONE:" + serverFile.getAbsolutePath().toString());

        } catch (Exception e) {
            e.printStackTrace();
            return model;
        }
    }
    if (!cover.isEmpty()) {
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE

    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }

    return model;
}

From source file:quanlyhocvu.api.web.controller.staff.ManagementStudentController.java

@RequestMapping(value = "nhap_hocsinh", headers = "content-type=multipart/*", method = RequestMethod.POST)
public @ResponseBody ModelAndView importHocSinh(
        @RequestParam(value = "danhSachHocSinh", required = false) MultipartFile danhSachHocSinh)
        throws IOException {
    Map<String, Object> map = new HashMap<String, Object>();
    //        File file = new File(servletContext.getRealPath("/") + "/"
    //                    + filename);
    //String path = servletContext.getRealPath("/");                
    KhoiLopDTO khoiLop = mongoService.getKhoiLopByName("6");
    //System.out.println(request.getParameter("danhSachHocSinh"));
    //System.out.println(path);
    File temp_file = new File("uploaded.xls");
    byte[] bytes = danhSachHocSinh.getBytes();
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(temp_file));
    stream.write(bytes);
    stream.close();/*from  w  w w .  j  av  a  2 s .  co m*/
    System.out.println(danhSachHocSinh.getOriginalFilename());
    Workbook w;
    try {
        w = Workbook.getWorkbook(temp_file);
        //Get the first sheet
        Sheet sheet = w.getSheet(0);
        for (int i = 1; i < sheet.getRows(); i++) {
            HocSinhDTO hs = new HocSinhDTO();
            //Do columns co 6 cot nen se lay 6 cot
            Cell[] listCell = new Cell[7];
            for (int j = 0; j < 7; j++) {
                listCell[j] = sheet.getCell(j, i);
            }

            String hoTen = listCell[1].getContents();
            hs.sethoTen(hoTen);

            String gioiTinh = listCell[2].getContents();
            if (gioiTinh == "Nam") {
                hs.setgioiTinh(1);
            } else {
                hs.setgioiTinh(0);
            }

            String ngaySinh = listCell[3].getContents();
            Date ngaySinhDate = FunctionService.formatStringDateExcel(ngaySinh);
            hs.setngaySinh(ngaySinhDate);

            String ngayNhapHoc = listCell[4].getContents();
            Date ngayNhapHocDate = FunctionService.formatStringDateExcel(ngayNhapHoc);
            hs.setngayNhapHoc(ngayNhapHocDate);

            String diaChi = listCell[5].getContents();
            hs.setdiaChi(diaChi);

            String moTa = listCell[6].getContents();
            hs.setmoTa(moTa);
            hs.setKhoiLopHienTai(khoiLop);
            mongoService.insertStudent(hs);
        }
    } catch (BiffException ex) {
        java.util.logging.Logger.getLogger(ManagementStudentController.class.getName()).log(Level.SEVERE, null,
                ex);
    }
    return new ModelAndView("redirect:/staff/management/students/index", map);
}

From source file:com.nkapps.billing.controllers.BankStatementController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadPost(@RequestParam("file") MultipartFile uploadedFile, ModelMap map,
        HttpServletRequest request) {/*from w w  w  . j ava 2s .  c  om*/
    try {
        File file = null;
        /**
         * Upload file
         */
        //            FileItemFactory factory = new DiskFileItemFactory();
        //            ServletFileUpload upload = new ServletFileUpload(factory);
        //            List<FileItem> formItems = upload.parseRequest(request);
        //            Iterator iterator = formItems.iterator();
        //            while(iterator.hasNext()){
        //                FileItem item = (FileItem) iterator.next();
        //                if(!item.isFormField()){
        //                    File uploadedFile = new File(item.getName());
        //                    
        //                    String filePath = bankStatementService.getUploadDir() + File.separator + uploadedFile.getName();
        //                    file = new File(filePath);
        //                    item.write(file);    
        //                    break;
        //                }
        //            }
        String filePath = bankStatementService.getUploadDir() + File.separator
                + uploadedFile.getOriginalFilename();
        file = new File(filePath);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
        stream.write(uploadedFile.getBytes());
        stream.close();

        String messages;
        if (file.getName().endsWith(".xls")) { // for payment manual, excel file

            String ip = authService.getClientIp(request);
            if (!authService.isAllowedByPropertyIp("bank_statement_payment_manual_allowed_ips", ip)) {
                throw new Exception(messageSource.getMessage("upload.you_have_not_privelege_to_upload_excel",
                        null, LocaleContextHolder.getLocale()));
            }
            /**
             * Parse and Save
             */
            Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue();
            String issuerIp = authService.getClientIp(request);
            paymentService.parseAndSavePaymentManual(file, issuerSerialNumber, issuerIp);
            /**
             * Backup and Release uploads
             */
            bankStatementService.backupAndRelease(file, null);
            messages = messageSource.getMessage("upload.file_successfull_uploded", null,
                    LocaleContextHolder.getLocale());

        } else {
            /**
             * Extract file
             */
            File extractedFile = bankStatementService.extractedFile(file);

            /**
             * Parse and Save
             */
            Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue();
            String issuerIp = authService.getClientIp(request);
            messages = bankStatementService.parseAndSave(extractedFile, issuerSerialNumber, issuerIp);

            /**
             * Backup and Release uploads
             */
            bankStatementService.backupAndRelease(file, extractedFile);
            if (messages.isEmpty()) {
                messages = messageSource.getMessage("upload.file_successfull_uploded", null,
                        LocaleContextHolder.getLocale());
            } else {
                messages = messageSource.getMessage("upload.file_successfull_uploded", null,
                        LocaleContextHolder.getLocale()) + "<br/>" + messages;
            }

        }
        map.put("info", messages);

    } catch (Exception e) {
        logger.error(e.getMessage());
        map.put("reason", e.getMessage().replace("\n", ";").replace("\r", ";"));
    }
    return "bankstatement/upload";
}

From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

private void dumpToFile(URL url) {
    File externalStorage = Environment.getExternalStorageDirectory();
    if (!externalStorage.canWrite())
        return;/*w  w w.j a  v  a2s  .  c  o m*/

    String fn = null;

    String[] f = url.toString().split("/");
    fn = f[f.length - 1].split("\\?")[0];
    Log.w("--------------", fn);

    String base = String.format("%s/dreamDroid/xml", externalStorage);
    File file = new File(String.format("%s/%s", base, fn));
    BufferedOutputStream bos = null;
    try {
        (new File(base)).mkdirs();
        file.createNewFile();
        bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(mBytes);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody/*from   w  w  w . j  av  a  2  s .c  om*/
public String upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException {
    if (file == null) {
        file = new Files();
        file.setSizeInBytes(0L);
    }

    Integer docId = null;
    String docPath = null;
    String responseString = RESP_SUCCESS;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = x.parseRequest(request);

            for (FileItem item : items) {
                InputStream input = item.getInputStream();

                // Handle a form field.
                if (item.isFormField()) {
                    String attribute = item.getFieldName();
                    String value = Streams.asString(input);

                    switch (attribute) {
                    case "chunks":
                        this.chunks = Integer.parseInt(value);
                        break;
                    case "chunk":
                        this.chunk = Integer.parseInt(value);
                        break;
                    case "filename":
                        file.setName(value);
                        break;
                    case "docId":
                        if (value.isEmpty()) {
                            throw new org.apache.commons.fileupload.FileUploadException(
                                    "No foi informado o id do documento.");
                        }
                        docId = Integer.parseInt(value);
                        docPath = Config.FILE_PATH + "/" + docId;
                        File documentPath = new File(docPath);
                        // cria o diretorio
                        documentPath.mkdirs();

                        break;
                    default:
                        break;
                    }

                } // Handle a multi-part MIME encoded file.
                else {
                    try {

                        File uploadFile = new File(docPath, item.getName());
                        BufferedOutputStream bufferedOutput;
                        bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true));

                        byte[] data = item.get();
                        bufferedOutput.write(data);
                        bufferedOutput.close();
                    } catch (Exception e) {
                        LOG.error("Erro ao salvar o arquivo.", e);
                        file = null;
                        throw e;
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                LOG.error("Erro ao fechar o ImputStream", e);
                            }
                        }

                        file.setName(item.getName());
                        file.setContentType(item.getContentType());
                        file.setPartialSize(item.getSize());
                    }
                }
            }

            if ((this.chunk == this.chunks - 1) || this.chunks == 0) {
                file.setLocation(docPath + "/" + file.getName());
                if (docId != null) {
                    file.setDocument(documentsService.get(docId));
                }
                fileService.save(file);
                file = null;
            }
        } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) {
            responseString = RESP_ERROR;
            LOG.error("Erro ao salvar o arquivo", e);
            file = null;
            throw e;
        }
    } // Not a multi-part MIME request.
    else {
        responseString = RESP_ERROR;
    }

    response.setContentType("application/json");
    byte[] responseBytes = responseString.getBytes();
    response.setContentLength(responseBytes.length);
    ServletOutputStream output = response.getOutputStream();
    output.write(responseBytes);
    output.flush();
    return responseString;
}

From source file:mamo.vanillaVotifier.JsonConfig.java

@Override
public synchronized void load() throws IOException, InvalidKeySpecException {
    if (!configFile.exists()) {
        BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
        StringBuilder stringBuilder = new StringBuilder();
        int i;/*ww w.  jav a 2s .  c o  m*/
        while ((i = in.read()) != -1) {
            stringBuilder.append((char) i);
        }
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(configFile));
        for (char c : stringBuilder.toString()
                .replaceAll("\\u000D\\u000A|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]",
                        System.getProperty("line.separator"))
                .toCharArray()) {
            out.write((int) c);
        }
        out.flush();
        out.close();
    }
    BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
    JSONObject defaultConfig = new JSONObject(new JSONTokener(in));
    in.close();
    JSONObject config = new JSONObject(
            new JSONTokener(new BufferedInputStream(new FileInputStream(configFile))));
    boolean save = JsonUtils.merge(defaultConfig, config);
    configVersion = config.getInt("config-version");
    if (configVersion == 2) {
        v2ToV3(config);
        configVersion = 3;
        save = true;
    }
    logFile = new File(config.getString("log-file"));
    inetSocketAddress = new InetSocketAddress(config.getString("ip"), config.getInt("port"));
    publicKeyFile = new File(config.getJSONObject("key-pair-files").getString("public"));
    privateKeyFile = new File(config.getJSONObject("key-pair-files").getString("private"));
    if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
        KeyPair keyPair = RsaUtils.genKeyPair();
        PemWriter publicPemWriter = new PemWriter(new BufferedWriter(new FileWriter(publicKeyFile)));
        publicPemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
        publicPemWriter.flush();
        publicPemWriter.close();
        PemWriter privatePemWriter = new PemWriter(new BufferedWriter(new FileWriter(privateKeyFile)));
        privatePemWriter.writeObject(new PemObject("RSA PRIVATE KEY", keyPair.getPrivate().getEncoded()));
        privatePemWriter.flush();
        privatePemWriter.close();
    }
    if (!publicKeyFile.exists()) {
        throw new PublicKeyFileNotFoundException();
    }
    if (!privateKeyFile.exists()) {
        throw new PrivateKeyFileNotFoundException();
    }
    PemReader publicKeyPemReader = new PemReader(new BufferedReader(new FileReader(publicKeyFile)));
    PemReader privateKeyPemReader = new PemReader(new BufferedReader(new FileReader(privateKeyFile)));
    PemObject publicPemObject = publicKeyPemReader.readPemObject();
    if (publicPemObject == null) {
        throw new InvalidPublicKeyFileException();
    }
    PemObject privatePemObject = privateKeyPemReader.readPemObject();
    if (privatePemObject == null) {
        throw new InvalidPrivateKeyFileException();
    }
    keyPair = new KeyPair(RsaUtils.bytesToPublicKey(publicPemObject.getContent()),
            RsaUtils.bytesToPrivateKey(privatePemObject.getContent()));
    publicKeyPemReader.close();
    privateKeyPemReader.close();
    rconConfigs = new ArrayList<RconConfig>();
    for (int i = 0; i < config.getJSONArray("rcon-list").length(); i++) {
        JSONObject jsonObject = config.getJSONArray("rcon-list").getJSONObject(i);
        RconConfig rconConfig = new RconConfig(
                new InetSocketAddress(jsonObject.getString("ip"), jsonObject.getInt("port")),
                jsonObject.getString("password"));
        for (int j = 0; j < jsonObject.getJSONArray("commands").length(); j++) {
            rconConfig.getCommands().add(jsonObject.getJSONArray("commands").getString(j));
        }
        rconConfigs.add(rconConfig);
    }
    loaded = true;
    if (save) {
        save();
    }
}

From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Get a JHOVE Document from a {@link URL} source
 * @param _uri  a resource URL/*  w w  w  . java  2 s .  c om*/
 * @param _stream an input stream code
 * @return a JDOM Document
 * @throws IOException 
 * @throws JDOMException 
 */
public Document getDocument(InputStream _stream, String _uri) throws IOException, JDOMException {
    RepInfo representation = new RepInfo(_uri);

    File file = File.createTempFile("vtls-jhove-", "");
    file.deleteOnExit();

    BufferedOutputStream output_stream = new BufferedOutputStream(new FileOutputStream(file));
    BufferedInputStream input_stream = new BufferedInputStream(_stream);

    int stream_byte;
    while ((stream_byte = input_stream.read()) != -1) {
        output_stream.write(stream_byte);
    }

    output_stream.flush();
    output_stream.close();
    input_stream.close();

    representation.setSize(file.length());
    representation.setLastModified(new Date());
    populateRepresentation(representation, file);

    file.delete();

    return getDocumentFromRepresentation(representation);
}