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:es.mityc.firmaJava.libreria.utilidades.Base64.java

/**
 * Convenience method for decoding data to a file.
 *
 * @param dataToDecode Base64-encoded data as a string
 * @param filename Filename for saving decoded data
 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
 *
 * @since 2.1// ww  w .  j a v  a2  s. c  o m
 */
public static boolean decodeToFile(String dataToDecode, String filename) {
    boolean success = false;
    Base64.OutputStream bos = null;
    BufferedOutputStream bfos = null;
    try {
        bos = new Base64.OutputStream(new FileOutputStream(filename), ConstantesXADES.DECODE);
        bfos = new BufferedOutputStream(bos);
        bfos.write(dataToDecode.getBytes(PREFERRED_ENCODING));
        success = true;
    } // end try
    catch (IOException e) {
        success = false;
    } // end catch: IOException
    finally {
        try {
            bos.close();
            bfos.close();
        } catch (Exception e) {
            log.error(e);
        }
    } // end finally

    return success;
}

From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHanlder.java

/**
 * @param is//from w  w w.j  a v a 2 s  .  c  om
 * @param rootPath
 * @param fileName
 */
@Override
public void createNewTmpFile(InputStream is, int uid, String dir, String fileName, String realFileName) {

    File path = new File(FOLDER_TMP_FOR_ATTACHMENT_FILES + separator() + Database.getDomainName() + separator()
            + uid + separator() + dir);

    if (!path.exists()) {
        try {
            path.mkdirs();
        } catch (Exception e) {
            logger.error("Can't create directory...:" + path);
        }
    }

    // ?START
    try {
        String filepath = path + separator() + fileName;
        File file = new File(filepath);
        file.createNewFile();
        int c;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is, 1024 * 1024);
            bos = new BufferedOutputStream(new FileOutputStream(filepath), 1024 * 1024);

            while ((c = bis.read()) != -1) {
                bos.write(c);
            }
        } catch (IOException e) {
            logger.error("ALDefaultStorageHanlder.createNewTmpFile", e);
        } finally {

            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(bos);
        }
        // ?END

        PrintWriter w = null;
        try {
            w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filepath + EXT_FILENAME), "UTF-8"));
            w.println(realFileName);
        } catch (IOException e) {
            logger.error("ALDefaultStorageHanlder.createNewTmpFile", e);
        } finally {
            if (w != null) {
                try {
                    w.flush();
                    w.close();
                } catch (Throwable e) {
                    // ignore
                }
            }
        }
    } catch (FileNotFoundException e) {
        logger.error("ALDefaultStorageHanlder.createNewTmpFile", e);
    } catch (IOException e) {
        logger.error("ALDefaultStorageHanlder.createNewTmpFile", e);
    }
}

From source file:com.wabacus.config.database.type.Oracle.java

public void setBlobValueInSelectMode(Object value, oracle.sql.BLOB blob) throws SQLException {
    if (blob == null)
        return;/*www .j a  v  a 2s.  com*/
    InputStream in = null;
    if (value == null) {
        blob = null;
        return;
    } else if (value instanceof byte[]) {
        in = Tools.getInputStreamFromBytesArray((byte[]) value);
    } else if (value instanceof InputStream) {
        in = (InputStream) value;
    } else {
        throw new WabacusRuntimeException(
                "" + value + "BLOB?byte[]InputStream");
    }
    BufferedOutputStream out = new BufferedOutputStream(blob.getBinaryOutputStream());
    try {
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.close();
    } catch (IOException e) {
        throw new WabacusRuntimeException("?" + value + "BLOB", e);
    }
}

From source file:es.mityc.firmaJava.libreria.utilidades.Base64.java

/**
 * Convenience method for encoding data to a file.
 *
 * @param dataToEncode byte array of data to encode in base64 form
 * @param filename Filename for saving encoded data
 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
 *
 * @since 2.1//from  w  ww  . j av a2 s  . c  om
 */
public static boolean encodeToFile(byte[] dataToEncode, String filename) {
    boolean success = false;
    Base64.OutputStream bos = null;
    BufferedOutputStream bfos = null;
    try {

        bos = new Base64.OutputStream(new FileOutputStream(filename), ConstantesXADES.ENCODE);

        bfos = new BufferedOutputStream(bos);
        bfos.write(dataToEncode);
        success = true;
    } // end try
    catch (IOException e) {

        success = false;
    } // end catch: IOException
    finally {
        try {
            bos.close();
            bfos.close();
        } catch (Exception e) {
            log.error(e);
        }
    } // end finally

    return success;
}

From source file:energy.usef.environment.tool.GenerateDomains.java

private void generateH2DatabaseSchemas() throws SQLException, IOException, ClassNotFoundException {
    Server server = Server.createTcpServer("-tcpAllowOthers").start();
    for (String nodeName : environmentConfig.getNodeNames()) {
        NodeConfig nodeConfig = environmentConfig.getNodeConfig(nodeName);

        String credentialProperties = ToolConfig.getUsefEnvironmentDomainConfigurationFolder(nodeName)
                + File.separator + ToolConfig.CREDENTIALS;
        if (!FileUtil.isFileExists(credentialProperties)) {
            LOGGER.error("Properties file {} does not exist.", credentialProperties);
            System.exit(1);//w ww  .  j  a v  a2 s  .  co m
        }

        Properties properties = FileUtil.readProperties(credentialProperties);

        Class.forName(ToolConfig.DRIVER_CLASS);

        List<RoleConfig> domains = environmentConfig.getDomainRoleConfig(nodeConfig);
        for (RoleConfig roleConfig : domains) {

            String dbFolder = ToolConfig.getUsefEnvironmentDomainDataFolder(nodeName) + File.separator;

            String dbFilename = dbFolder
                    + (environmentConfig.isDatabasePerParticipant() ? roleConfig.getDomain() : "usef_db");

            LOGGER.info("The location of the database file: " + dbFilename);

            Connection connection = DriverManager.getConnection(ToolConfig.getUsefEnvironmentDbUrl(dbFilename),
                    ToolConfig.USER, properties.getProperty(ToolConfig.DB_PASSWORD_PROPERTY));

            List<String> statements = new ArrayList<>();

            statements.add("drop schema " + roleConfig.getUniqueDbSchemaName() + " if exists;");
            statements.add("create schema " + roleConfig.getUniqueDbSchemaName() + ";");
            statements.add("create sequence " + roleConfig.getUniqueDbSchemaName() + ".HIBERNATE_SEQUENCE;");

            List<String> ddlStatements = FileUtil.readLines(roleConfig.getDdlScript());

            for (String ddlStatement : ddlStatements) {
                statements.add(ddlStatement.replaceAll(roleConfig.getTemplateDbSchemaName(),
                        roleConfig.getUniqueDbSchemaName()) + ";");
            }

            String ddlFile = ToolConfig.getUsefEnvironmentDomainDdlFolder(nodeName) + File.separator
                    + roleConfig.getUniqueName() + File.separator + ToolConfig.DDL_FILENAME;

            BufferedOutputStream bout = null;
            try {
                bout = new BufferedOutputStream(new FileOutputStream(ddlFile));

                for (String line : statements) {
                    line += System.getProperty("line.separator");
                    bout.write(line.getBytes());
                }
            } catch (IOException e) {
            } finally {
                if (bout != null) {
                    try {
                        bout.close();
                    } catch (Exception e) {
                    }
                }
            }

            List<String> ddlLines = FileUtil.readLines(ddlFile);

            for (String statement : ddlLines) {
                executeDdlStatement(connection, statement);
            }

            connection.close();
        }
    }
    LOGGER.info("Closing H2 database.");
    server.stop();
}

From source file:com.itsherpa.andg.imageloader.ImageFetcher.java

public boolean downloadUrlToStream2(String urlString, OutputStream outputStream) {
    disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;

    try {//from ww w. ja  v  a 2 s . co m
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (final IOException e) {
        LogUtils.e(TAG, "Error in downloadBitmap - " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (final IOException e) {
        }
    }
    return false;
}

From source file:com.ichi2.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;// w  ww .j a  v  a 2  s  .  c o m
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // compression flag and session key as post vars
        buf.write(bdry + "\r\n");
        buf.write("Content-Disposition: form-data; name=\"c\"\r\n\r\n" + (comp != 0 ? 1 : 0) + "\r\n");
        if (hkey) {
            buf.write(bdry + "\r\n");
            buf.write("Content-Disposition: form-data; name=\"k\"\r\n\r\n" + mHKey + "\r\n");
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersion());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:eu.planets_project.tb.gui.backing.DownloadManager.java

/**
 * /*w ww .j  ava 2 s  . co  m*/
 * @return
 * @throws IOException
 */
public String downloadExportedExperiment(String expExportID, String downloadName) {
    FacesContext ctx = FacesContext.getCurrentInstance();

    // Decode the file name (might contain spaces and on) and prepare file object.
    try {
        expExportID = URLDecoder.decode(expExportID, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    File file = expCache.getExportedFile(expExportID);

    HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();

    // Check if file exists and can be read:
    if (!file.exists() || !file.isFile() || !file.canRead()) {
        return "fileNotFound";
    }

    // Get content type by filename.
    String contentType = new MimetypesFileTypeMap().getContentType(file);

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open the file:
        input = new BufferedInputStream(new FileInputStream(file));
        int contentLength = input.available();

        // Initialise the servlet response:
        response.reset();
        response.setContentType(contentType);
        response.setContentLength(contentLength);
        response.setHeader("Content-disposition", "attachment; filename=\"" + downloadName + ".xml\"");
        output = new BufferedOutputStream(response.getOutputStream());

        // Write file out:
        for (int data; (data = input.read()) != -1;) {
            output.write(data);
        }

        // Flush the stream:
        output.flush();

        // Tell Faces that we're finished:
        ctx.responseComplete();

    } catch (IOException e) {
        // Something went wrong?
        e.printStackTrace();

    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
    return "success";
}

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

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

    CompletePOI poi = new CompletePOI();
    CompletePOI poitest = new CompletePOI();

    ModelAndView model = new ModelAndView("insertpoi");
    ModelAndView model2 = new ModelAndView("errorViewPoi");
    poitest = pm.findOneCompletePoiByName(params.get("name"));
    if (poitest != null && poitest.getName().toLowerCase().equals(params.get("name").toLowerCase())) {

        model2.addObject("err", "Esiste gi un poi chiamato " + params.get("name"));
        return model2;
    } else {//from  ww  w.j a  v a2s.c  om
        poi.setName(params.get("name"));
        poi.setVisibility(params.get("visibility"));
        poi.setAddress(params.get("address"));
        double lat = Double.parseDouble(params.get("latitude"));
        double longi = Double.parseDouble(params.get("longitude"));
        poi.setLocation(new double[] { lat, longi });
        poi.setShortDescription(params.get("shortd"));
        int i = 1;
        ArrayList<String> categories = new ArrayList<String>();
        while (params.containsKey("category" + i)) {

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

            i = i + 1;
        }
        poi.setCategories(categories);

        ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();

        //componente cover
        if (!cover.isEmpty()) {
            CoverImgComponent coverimg = new CoverImgComponent();
            coverimg.setLink("cover.jpg");
            listComponent.add(coverimg);
        }
        //componente galleria immagini
        ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
        if (files.length > 0) {
            ImgGalleryComponent img_gallery = new ImgGalleryComponent();

            i = 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("credit" + (i + 1)))
                    img.setCredit(params.get("credit" + (i + 1)));

                i = i + 1;
                links.add(img);
            }
            img_gallery.setLinks(links);
            listComponent.add(img_gallery);
        }
        //componente contatti
        ContactsComponent contacts_component = new ContactsComponent();
        //Recapiti telefonici
        i = 1;
        boolean contacts = false;
        if (params.containsKey("tel" + i)) {
            ArrayList<PhoneContact> phoneList = new ArrayList<PhoneContact>();

            while (params.containsKey("tel" + i)) {
                PhoneContact phone = new PhoneContact();
                if (params.containsKey("tel" + i)) {
                    phone.setLabel(params.get("desctel" + i));
                }
                phone.setNumber(params.get("tel" + i));
                phoneList.add(phone);
                i = i + 1;
            }
            contacts = true;
            contacts_component.setPhoneList(phoneList);
        }
        //Recapiti mail
        i = 1;
        if (params.containsKey("email" + i)) {
            ArrayList<EmailContact> emailList = new ArrayList<EmailContact>();

            while (params.containsKey("email" + i)) {
                EmailContact email = new EmailContact();
                if (params.containsKey("email" + i)) {
                    email.setLabel(params.get("descemail" + i));
                }
                email.setEmail(params.get("email" + i));
                emailList.add(email);
                i = i + 1;
            }
            contacts = true;
            contacts_component.setEmailsList(emailList);
        }
        //Recapiti fax
        i = 1;
        if (params.containsKey("fax" + i)) {
            ArrayList<FaxContact> faxList = new ArrayList<FaxContact>();

            while (params.containsKey("fax" + i)) {
                FaxContact fax = new FaxContact();
                if (params.containsKey("fax" + i)) {
                    fax.setLabel(params.get("descfax" + i));
                }
                fax.setFax(params.get("fax" + i));
                faxList.add(fax);
                i = i + 1;
            }
            contacts = true;
            contacts_component.setFaxList(faxList);
        }
        //Social predefiniti
        i = 1;
        if (params.containsKey("SN" + i)) {

            while (params.containsKey("SN" + i)) {
                if (params.get("SN" + i).equals("facebook")) {
                    contacts = true;
                    contacts_component.setFacebook(params.get("LSN" + i));
                }
                if (params.get("SN" + i).equals("twitter")) {
                    contacts = true;
                    contacts_component.setTwitter(params.get("LSN" + i));
                }
                if (params.get("SN" + i).equals("google")) {
                    contacts = true;
                    contacts_component.setGoogle(params.get("LSN" + i));
                }
                if (params.get("SN" + i).equals("skype")) {
                    contacts = true;
                    contacts_component.setSkype(params.get("LSN" + i));
                }
                i = i + 1;
            }
        }
        //Social personalizzati
        i = 1;
        if (params.containsKey("CSN" + i)) {
            ArrayList<GenericSocial> customsocial = new ArrayList<GenericSocial>();

            while (params.containsKey("CSN" + i)) {
                GenericSocial social = new GenericSocial();
                contacts = true;
                social.setLabel(params.get("CSN" + i));
                social.setSocial(params.get("LCSN" + i));
                customsocial.add(social);
                i = i + 1;
            }
            contacts_component.setSocialList(customsocial);
        }
        if (contacts == true) {
            listComponent.add(contacts_component);
        }
        //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);
        }
        //Orari
        i = 1;
        int k = 1;
        boolean ok = false;
        String gg = "";
        boolean[] aperto = new boolean[8];
        for (int z = 1; z <= 7; z++) {
            aperto[z] = false;
        }
        WorkingTimeComponent workingtime = new WorkingTimeComponent();
        if (params.containsKey("WD" + i + "start" + k + "H")) {

            ok = true;
            ArrayList<CompactWorkingDays> workingdays = new ArrayList<CompactWorkingDays>();

            while (params.containsKey("WD" + i)) {
                ArrayList<WorkingHours> Listwh = new ArrayList<WorkingHours>();
                k = 1;
                while (params.containsKey("WD" + i + "start" + k + "H")) {
                    WorkingHours wh = new WorkingHours();
                    wh.setStart(params.get("WD" + i + "start" + k + "H") + ":"
                            + params.get("WD" + i + "start" + k + "M"));
                    wh.setEnd(params.get("WD" + i + "end" + k + "H") + ":"
                            + params.get("WD" + i + "end" + k + "M"));
                    Listwh.add(wh);
                    k = k + 1;
                }
                CompactWorkingDays cwd = new CompactWorkingDays();
                cwd.setDays(params.get("WD" + i));
                cwd.setWorkinghours(Listwh);
                workingdays.add(cwd);
                i = i + 1;
            }
            int grn = 1;
            ArrayList<CompactWorkingDays> wdef = new ArrayList<CompactWorkingDays>();

            for (int z = 1; z <= 7; z++) {
                aperto[z] = false;
            }
            while (grn <= 7) {

                for (CompactWorkingDays g : workingdays) {

                    if (grn == 1 && g.getDays().equals("Luned")) {
                        aperto[1] = true;
                        wdef.add(g);
                    }
                    if (grn == 2 && g.getDays().equals("Marted")) {
                        aperto[2] = true;
                        wdef.add(g);
                    }
                    if (grn == 3 && g.getDays().equals("Mercoled")) {
                        aperto[3] = true;
                        wdef.add(g);
                    }
                    if (grn == 4 && g.getDays().equals("Gioved")) {
                        aperto[4] = true;
                        wdef.add(g);
                    }
                    if (grn == 5 && g.getDays().equals("Venerd")) {
                        aperto[5] = true;
                        wdef.add(g);
                    }
                    if (grn == 6 && g.getDays().equals("Sabato")) {
                        aperto[6] = true;
                        wdef.add(g);
                    }
                    if (grn == 7 && g.getDays().equals("Domenica")) {
                        aperto[7] = true;
                        wdef.add(g);
                    }

                }
                grn++;
            }
            workingtime.setWorkingdays(wdef);
            for (int z = 1; z <= 7; z++) {
                if (aperto[z] == false && z == 1)
                    gg = gg + " " + "Luned";
                if (aperto[z] == false && z == 2)
                    gg = gg + " " + "Marted";
                if (aperto[z] == false && z == 3)
                    gg = gg + " " + "Mercoled";
                if (aperto[z] == false && z == 4)
                    gg = gg + " " + "Gioved";
                if (aperto[z] == false && z == 5)
                    gg = gg + " " + "Venerd";
                if (aperto[z] == false && z == 6)
                    gg = gg + " " + "Sabato";
                if (aperto[z] == false && z == 7)
                    gg = gg + " " + "Domenica";
            }

            if (!gg.equals("")) {
                ok = true;
                workingtime.setWeekly_day_of_rest(gg);
            }
        }

        i = 1;
        String ggs = "";
        while (params.containsKey("RDA" + i)) {
            ggs = ggs + " " + params.get("RDA" + i);
            i = i + 1;
        }
        if (!ggs.equals("")) {
            ok = true;
            workingtime.setDays_of_rest(ggs);
        }
        if (ok) {
            listComponent.add(workingtime);
        }

        i = 1;
        if (params.containsKey("type" + i)) {

            PricesComponent pc = new PricesComponent();
            ArrayList<TicketPrice> tpList = new ArrayList<TicketPrice>();
            while (params.containsKey("type" + i)) {
                TicketPrice tp = new TicketPrice();
                tp.setType(params.get("type" + i));
                double dp = Double.parseDouble(params.get("price" + i));
                tp.setPrice(dp);
                tp.setType_description(params.get("typedesc" + i));
                tpList.add(tp);
                i = i + 1;
            }
            pc.setPrices(tpList);
            listComponent.add(pc);
        }

        i = 1;
        if (params.containsKey("SERV" + i)) {
            ArrayList<String> servList = new ArrayList<String>();
            while (params.containsKey("SERV" + i)) {
                servList.add(params.get("SERV" + i));
                i = i + 1;
            }
            ServicesComponent servicescomponent = new ServicesComponent();
            servicescomponent.setServicesList(servList);
            listComponent.add(servicescomponent);
        }
        poi.setComponents(listComponent);

        pm.savePoi(poi);

        CompletePOI poi2 = (CompletePOI) pm.findOneCompletePoiByName(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 + "poi" + 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();

            } catch (Exception e) {
                return model;
            }
        }
        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 + "poi" + 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;
        }

        return model;
    }
}

From source file:com.hichinaschool.flashcards.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;//from   www.ja va  2s. c o m
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        HashMap<String, Object> vars = new HashMap<String, Object>();
        // compression flag and session key as post vars
        vars.put("c", comp != 0 ? 1 : 0);
        if (hkey) {
            vars.put("k", mHKey);
            vars.put("s", mSKey);
        }
        for (String key : vars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    vars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}