Example usage for java.io BufferedOutputStream close

List of usage examples for java.io BufferedOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:au.org.ala.layers.grid.GridClassBuilder.java

public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException {
    File wktDir = new File(filePath);
    wktDir.mkdirs();//w w  w .j  a  v  a  2 s  . c  o  m

    int[] wktMap = null;

    //track values for the SLD
    ArrayList<Integer> maxValues = new ArrayList<Integer>();
    ArrayList<String> labels = new ArrayList<String>();

    HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>();
    Properties p = new Properties();
    p.load(new FileReader(filePath + ".txt"));

    boolean mergeProperties = false;

    Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>();
    Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>();
    Map<String, Integer> translateValues = new HashMap<String, Integer>();
    ArrayList<Integer> keys = new ArrayList<Integer>();
    for (String key : p.stringPropertyNames()) {
        try {
            int k = Integer.parseInt(key);
            keys.add(k);

            //grouping of property file keys by value
            String value = p.getProperty(key);
            Set<Integer> klist = groupedKeys.get(value);
            if (klist == null)
                klist = new HashSet<Integer>();
            else
                mergeProperties = true;
            klist.add(k);
            groupedKeys.put(value, klist);

            if (!translateValues.containsKey(value))
                translateValues.put(value, translateValues.size() + 1);
            translateKeys.put(k, translateValues.get(value));

        } catch (NumberFormatException e) {
            logger.info("Excluding shape key '" + key + "'");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    java.util.Collections.sort(keys);

    Grid g = new Grid(filePath);
    boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE;

    if (mergeProperties) {
        g.replaceValues(translateKeys);

        if (!new File(filePath + ".txt.old").exists())
            FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old"));

        StringBuilder sb = new StringBuilder();
        for (String value : translateValues.keySet()) {
            sb.append(translateValues.get(value)).append("=").append(value).append('\n');
        }
        FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString());

        return buildFromGrid(filePath);
    }

    if (generateWkt) {
        for (String name : groupedKeys.keySet()) {
            try {
                Set<Integer> klist = groupedKeys.get(name);

                String key = klist.iterator().next().toString();
                int k = Integer.parseInt(key);

                GridClass gc = new GridClass();
                gc.setName(name);
                gc.setId(k);

                if (klist.size() == 1)
                    klist = null;

                logger.info("getting wkt for " + filePath + " > " + key);

                Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed(
                        filePath + "," + key + "," + key, klist, wktMap);

                //write class wkt
                File zipFile = new File(filePath + File.separator + key + ".wkt.zip");
                ZipOutputStream zos = null;
                try {
                    zos = new ZipOutputStream(new FileOutputStream(zipFile));
                    zos.putNextEntry(new ZipEntry(key + ".wkt"));
                    zos.write(((String) wktIndexed.get("wkt")).getBytes());
                    zos.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (zos != null) {
                        try {
                            zos.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                BufferedOutputStream bos = null;
                try {
                    bos = new BufferedOutputStream(
                            new FileOutputStream(filePath + File.separator + key + ".wkt"));
                    bos.write(((String) wktIndexed.get("wkt")).getBytes());
                    bos.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (bos != null) {
                        try {
                            bos.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                logger.info("wkt written to file");
                gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0);

                //store map
                wktMap = (int[]) wktIndexed.get("map");

                //write wkt index
                FileWriter fw = null;
                try {
                    fw = new FileWriter(filePath + File.separator + key + ".wkt.index");
                    fw.append((String) wktIndexed.get("index"));
                    fw.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (fw != null) {
                        try {
                            fw.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km)
                int minPolygonNumber = 0;
                int maxPolygonNumber = 0;

                RandomAccessFile raf = null;
                try {
                    raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw");

                    String[] index = ((String) wktIndexed.get("index")).split("\n");

                    for (int i = 0; i < index.length; i++) {
                        if (index[i].length() > 1) {
                            String[] cells = index[i].split(",");
                            int polygonNumber = Integer.parseInt(cells[0]);
                            raf.writeInt(polygonNumber); //polygon number
                            int polygonStart = Integer.parseInt(cells[1]);
                            raf.writeInt(polygonStart); //character offset

                            if (i == 0) {
                                minPolygonNumber = polygonNumber;
                            } else if (i == index.length - 1) {
                                maxPolygonNumber = polygonNumber;
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (raf != null) {
                        try {
                            raf.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }

                //for SLD
                maxValues.add(gc.getMaxShapeIdx());
                labels.add(name.replace("\"", "'"));
                gc.setMinShapeIdx(minPolygonNumber);
                gc.setMaxShapeIdx(maxPolygonNumber);

                logger.info("getting multipolygon for " + filePath + " > " + key);
                MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key);
                gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ","));

                classes.put(k, gc);

                try {
                    //write class kml
                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".kml.zip"));

                        zos.putNextEntry(new ZipEntry(key + ".kml"));
                        Encoder encoder = new Encoder(new KMLConfiguration());
                        encoder.setIndenting(true);
                        encoder.encode(mp, KML.Geometry, zos);
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("kml written to file");

                    final SimpleFeatureType TYPE = DataUtilities.createType("class",
                            "the_geom:MultiPolygon,id:Integer,name:String");
                    FeatureJSON fjson = new FeatureJSON();
                    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
                    SimpleFeature sf = featureBuilder.buildFeature(null);

                    //write class geojson
                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".geojson.zip"));
                        zos.putNextEntry(new ZipEntry(key + ".geojson"));
                        featureBuilder.add(mp);
                        featureBuilder.add(k);
                        featureBuilder.add(name);

                        fjson.writeFeature(sf, zos);
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("geojson written to file");

                    //write class shape file
                    File newFile = new File(filePath + File.separator + key + ".shp");
                    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
                    Map<String, Serializable> params = new HashMap<String, Serializable>();
                    params.put("url", newFile.toURI().toURL());
                    params.put("create spatial index", Boolean.FALSE);
                    ShapefileDataStore newDataStore = null;
                    try {
                        newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
                        newDataStore.createSchema(TYPE);
                        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
                        Transaction transaction = new DefaultTransaction("create");
                        String typeName = newDataStore.getTypeNames()[0];
                        SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
                        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
                        featureStore.setTransaction(transaction);
                        List<SimpleFeature> features = new ArrayList<SimpleFeature>();

                        DefaultFeatureCollection collection = new DefaultFeatureCollection();
                        collection.addAll(features);
                        featureStore.setTransaction(transaction);

                        features.add(sf);
                        featureStore.addFeatures(collection);
                        transaction.commit();
                        transaction.close();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (newDataStore != null) {
                            try {
                                newDataStore.dispose();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }

                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".shp.zip"));
                        //add .dbf .shp .shx .prj
                        String[] exts = { ".dbf", ".shp", ".shx", ".prj" };
                        for (String ext : exts) {
                            zos.putNextEntry(new ZipEntry(key + ext));
                            FileInputStream fis = null;
                            try {
                                fis = new FileInputStream(filePath + File.separator + key + ext);
                                byte[] buffer = new byte[1024];
                                int size;
                                while ((size = fis.read(buffer)) > 0) {
                                    zos.write(buffer, 0, size);
                                }
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            } finally {
                                if (fis != null) {
                                    try {
                                        fis.close();
                                    } catch (Exception e) {
                                        logger.error(e.getMessage(), e);
                                    }
                                }
                            }
                            //remove unzipped files
                            new File(filePath + File.separator + key + ext).delete();
                        }
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("shape file written to zip");
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

        //write polygon mapping
        g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres,
                g.yres, g.nrows, g.ncols);

        //copy the header file to get it exactly the same, but change the data type
        copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd");
    } else {
        //build classes without generating polygons
        Map<Float, float[]> info = new HashMap<Float, float[]>();
        for (int j = 0; j < keys.size(); j++) {
            info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN });
        }

        g.getClassInfo(info);

        for (int j = 0; j < keys.size(); j++) {
            int k = keys.get(j);
            String key = String.valueOf(k);

            String name = p.getProperty(key);

            GridClass gc = new GridClass();
            gc.setName(name);
            gc.setId(k);

            //for SLD
            maxValues.add(Integer.valueOf(key));
            labels.add(name.replace("\"", "'"));
            gc.setMinShapeIdx(Integer.valueOf(key));
            gc.setMaxShapeIdx(Integer.valueOf(key));

            float[] stats = info.get(keys.get(j).floatValue());

            //only include if area > 0
            if (stats[0] > 0) {
                gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + ","
                        + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " "
                        + stats[2] + "))");

                gc.setArea_km((double) stats[0]);
                classes.put(k, gc);
            }
        }
    }

    //write sld
    exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues,
            labels);

    writeProjectionFile(filePath + File.separator + "polygons.prj");

    //write .classes.json
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(new File(filePath + ".classes.json"), classes);

    return classes;
}

From source file:com.boxupp.utilities.PuppetUtilities.java

private void extrectFile(String saveFilePath, String moduleDirPath, String moduleName) {
    try {/* w  w  w . j av  a 2  s .  c  o  m*/
        File file = new File(saveFilePath);
        FileInputStream fin = new FileInputStream(file);
        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);
        TarArchiveEntry entry = null;
        int length = 0;
        File unzipFile = null;
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                if (length == 0) {
                    File f = new File(moduleDirPath + entry.getName());
                    f.mkdirs();
                    unzipFile = f;
                    length++;
                } else {
                    File f = new File(moduleDirPath + entry.getName());
                    f.mkdirs();
                }
            } else {
                int count;
                byte data[] = new byte[4096];
                FileOutputStream fos;
                fos = new FileOutputStream(moduleDirPath + entry.getName());
                BufferedOutputStream dest = new BufferedOutputStream(fos, 4096);
                while ((count = tarIn.read(data, 0, 4096)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.close();
            }

        }
        File renamedFile = new File(moduleDirPath + "/" + moduleName);
        if (unzipFile.isDirectory()) {
            unzipFile.renameTo(renamedFile);
        }
        tarIn.close();

    } catch (IOException e) {
        logger.error("Error in unzip the module file :" + e.getMessage());
    }
}

From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpResponseModel responseModel = new HttpResponseModel();
    try {//from   w  w  w  . j  a  v  a 2s  .c  om
        boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ???
        if (isMultipart) {
            Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ??
            List<String> fileList = new ArrayList<String>();// 

            // DiskFileItemFactory??
            // ????List
            // list???
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();
                if (item.isFormField()) {
                    // ?
                    String sFieldName = item.getFieldName();
                    String sFieldValue = item.getString("UTF-8");
                    htSubmitParam.put(sFieldName, sFieldValue);
                } else {
                    // ,???
                    String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString()
                            + ".jpg";
                    File filePath = new File(
                            getServletConfig().getServletContext().getRealPath(Constants.File_Upload));
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    File file = new File(filePath, newFileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //?
                    BufferedInputStream bis = new BufferedInputStream(item.getInputStream());
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] b = new byte[1024];
                    int length = 0;
                    while ((length = bis.read(b)) > 0) {
                        bos.write(b, 0, length);
                    }
                    bos.close();
                    bis.close();
                    //?url
                    String fileUrl = request.getRequestURL().toString();
                    fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL
                    fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName;
                    /**/
                    fileList.add(fileUrl);
                }
            }

            //
            String unlockInfoId = htSubmitParam.get("UnlockInfoId");
            String imgType = htSubmitParam.get("ImgType");
            String newFileUrl = fileList.get(0);

            UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService");
            UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId));
            if (imgType.equals("customerIdImg")) {
                unlockInfo.setCustomerIdImg(newFileUrl);
            } else if (imgType.equals("customerDrivingLicenseImg")) {
                unlockInfo.setCustomerDrivingLicenseImg(newFileUrl);
            } else if (imgType.equals("customerVehicleLicenseImg")) {
                unlockInfo.setCustomerVehicleLicenseImg(newFileUrl);
            } else if (imgType.equals("customerBusinessLicenseImg")) {
                unlockInfo.setCustomerBusinessLicenseImg(newFileUrl);
            } else if (imgType.equals("customerIntroductionLetterImg")) {
                unlockInfo.setCustomerIntroductionLetterImg(newFileUrl);
            } else if (imgType.equals("unlockWorkOrderImg")) {
                unlockInfo.setUnlockWorkOrderImg(newFileUrl);
            }
            /**/
            unlockInfoService.update(unlockInfo);
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseModel.responseCode = "0";
        responseModel.responseMessage = e.toString();
    }
    /* ??? */
    response.setHeader("content-type", "text/json;charset=utf-8");
    response.getOutputStream().write(responseModel.toByteArray());
}

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

/**
 * @author Amr//from w w  w. ja v  a2 s  .  c om
 * @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.gsr.myschool.server.reporting.excel.ExcelController.java

@RequestMapping(method = RequestMethod.GET, value = "/excel/multidossier", produces = "application/vnd.ms-excel")
public void generateMultiDossierExcel(@RequestParam String q, @RequestParam String annee,
        HttpServletResponse response) {/*  w  w  w.j  av a2  s  .  c o m*/
    DossierStatus status = Strings.isNullOrEmpty(q) ? null : DossierStatus.valueOf(q);
    List<DossierMultiple> dossierMultiples = dossierService.findMultipleDossierByStatus(status, annee);

    try {
        response.addHeader("Content-Disposition",
                "attachment; filename=multidossier_" + System.currentTimeMillis() + ".xls");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        xlsExportService.saveSpreadsheetRecords(DossierMultiple.class, dossierMultiples, outputStream);

        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.iti.agrimarket.view.SignUpController.java

/**
 * Amr/*from www .  j a  v a 2  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/*from w  w  w.java  2  s. c  o m*/
 * @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:com.wavemaker.StudioInstallService.java

public static File unzipFile(File zipfile) {
    int BUFFER = 2048;

    String zipname = zipfile.getName();
    int extindex = zipname.lastIndexOf(".");

    try {/*from w  w  w  . ja va2s .co  m*/
        File zipFolder = new File(zipfile.getParentFile(), zipname.substring(0, extindex));
        if (zipFolder.exists())
            org.apache.commons.io.FileUtils.deleteDirectory(zipFolder);
        zipFolder.mkdir();

        File currentDir = zipFolder;
        //File currentDir = zipfile.getParentFile();

        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream(zipfile.toString());
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                File f = new File(currentDir, entry.getName());
                if (f.exists())
                    f.delete(); // relevant if this is the top level folder
                f.mkdir();
            } else {
                int count;
                byte data[] = new byte[BUFFER];
                //needed for non-dir file ace/ace.js created by 7zip
                File destFile = new File(currentDir, entry.getName());
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(currentDir.toString() + "/" + entry.getName());
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
        zis.close();

        return currentDir;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (File) null;

}

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   w  w 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: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   www  .j ava2 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();
}