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:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends a string via POST to a given url.
 * //  w w  w  . j  a v a2  s .c  om
 * @param urlStr the url to which to send to.
 * @param string the string to send as post body.
 * @param user the user or <code>null</code>.
 * @param password the password or <code>null</code>.
 * @return the response.
 * @throws Exception
 */
public static String sendPost(String urlStr, String string, String user, String password) throws Exception {
    BufferedOutputStream wr = null;
    HttpURLConnection conn = null;
    try {
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(false);
        if (user != null && password != null) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

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

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

        return returnMessageBuilder.toString();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:ezbake.deployer.impl.LocalFileArtifactWriter.java

@Override
public void writeArtifact(DeploymentMetadata metadata, DeploymentArtifact artifact) throws DeploymentException {
    File directory = new File(buildDirectoryPath(metadata));
    directory.mkdirs();// ww w. j  ava2s .  co  m
    File artifactBinary = new File(buildFilePath(metadata));
    log.info("Writing artifact to {}", artifactBinary.getAbsolutePath());
    try {
        byte[] bytes = serializer.serialize(artifact);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(artifactBinary, false));
        bos.write(bytes);
        bos.close();
    } catch (TException ex) {
        log.error("Failed serialization", ex);
        throw new DeploymentException("Failed to serialize the artifact before writing. " + ex.getMessage());
    } catch (IOException ex) {
        log.error("IO Failure", ex);
        throw new DeploymentException("IO Failure writing artifact. " + ex.getMessage());
    }
}

From source file:com.lin.umws.service.impl.UserServiceImpl.java

public void badUpload(byte[] file) {
    BufferedOutputStream bos = new BufferedOutputStream(System.out);
    try {//from  w  w w . ja v  a  2  s  .c  o m
        bos.write(file);
        bos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

@RequestMapping(value = "/userSignIn", method = RequestMethod.POST)
public ModelAndView addUser(HttpServletRequest request, @ModelAttribute("SpringWeb") User user,
        MultipartFile avatar) {//from   w  w w.  ja  v a2  s.  c  om
    ModelAndView model2 = new ModelAndView("okpage");
    User usertest = pm.findUserByUsername(user.getUsername());
    if (usertest != null && usertest.getUsername().toLowerCase().equals(user.getUsername().toLowerCase())) {
        model2.addObject("err", "Esiste gi un utente con username: " + user.getUsername());
        return model2;
    }
    //HASH PASSWORD
    user.setPassword(crypt(user.getPassword()));
    /*Create Role*/
    Role new_user_role = new Role();
    new_user_role.setRole("ROLE_USER");
    new_user_role.setUser(user);
    ArrayList<Role> new_user_roles = new ArrayList<Role>();
    new_user_roles.add(new_user_role);
    user.setRoles(new_user_roles);
    pm.saveUser(user);

    User user2 = pm.findUserByUsername(user.getUsername());

    MultipartFile file = avatar;

    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 + "user" + File.separator + "img"
                + File.separator + user2.getId());
        if (!dir.exists())
            dir.mkdirs();

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + "avatar.jpg");
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();
    } catch (Exception e) {

    }
    model2.addObject("mess",
            "Registrazione completata con successo!<br><br><center> <a href='page?sec=home' class='btn btn-primary'>Torna alla Home</a></center> ");
    return model2;
}

From source file:de.thb.ue.backend.service.AnswerImageService.java

@Override
public void addAnswerImage(Vote vote, MultipartFile answerImage, String evaluationID) {
    File imageFolder = new File(
            (workingDirectoryPath.isEmpty() ? "" : (workingDirectoryPath + File.separatorChar)) + evaluationID
                    + File.separatorChar + "images");
    try {/* w  w w.j  a  v  a2 s.  c  o m*/
        if (!imageFolder.exists()) {
            FileUtils.forceMkdir(imageFolder);
        }
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(imageFolder, vote.getId() + ".zip")));
        stream.write(answerImage.getBytes());
        stream.close();
    } catch (IOException e) {
        //TODO
        e.printStackTrace();
    }
}

From source file:it.polimi.diceH2020.launcher.controller.FilesController.java

private File saveFile(MultipartFile file, String fileName) {
    try {//from   w  w w .  jav  a  2  s .  co  m
        byte[] bytes = file.getBytes();
        File f = fileUtility.provideFile(fileName);
        BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(f));
        buffStream.write(bytes);
        buffStream.close();
        return f;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:ezbake.frack.submitter.util.JarUtilTest.java

@Test
public void addFileToJar() throws IOException {
    File tmpDir = new File("jarUtilTest");
    try {/*from ww w  . j  a  v a  2s  . c  om*/
        tmpDir.mkdirs();

        // Push the example jar to a file
        byte[] testJar = IOUtils.toByteArray(this.getClass().getResourceAsStream("/example.jar"));
        File jarFile = new File(tmpDir, "example.jar");
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(jarFile));
        os.write(testJar);
        os.close();

        // Push the test content to a file
        byte[] testContent = IOUtils.toByteArray(this.getClass().getResourceAsStream("/test.txt"));
        String stringTestContent = new String(testContent);
        File testFile = new File(tmpDir, "test.txt");
        os = new BufferedOutputStream(new FileOutputStream(testFile));
        os.write(testContent);
        os.close();

        assertTrue(jarFile.exists());
        assertTrue(testFile.exists());

        // Add the new file to the jar
        File newJar = JarUtil.addFilesToJar(jarFile, Lists.newArrayList(testFile));
        assertTrue("New jar file exists", newJar.exists());
        assertTrue("New jar is a file", newJar.isFile());

        // Roll through the entries of the new jar and
        JarInputStream is = new JarInputStream(new FileInputStream(newJar));
        JarEntry entry = is.getNextJarEntry();
        boolean foundNewFile = false;
        String content = "";
        while (entry != null) {
            String name = entry.getName();
            if (name.endsWith("test.txt")) {
                foundNewFile = true;
                byte[] buffer = new byte[1];
                while ((is.read(buffer)) > 0) {
                    content += new String(buffer);
                }
                break;
            }
            entry = is.getNextJarEntry();
        }
        is.close();
        assertTrue("New file was in repackaged jar", foundNewFile);
        assertEquals("Content of added file is the same as the retrieved new file", stringTestContent, content);
    } finally {
        FileUtils.deleteDirectory(tmpDir);
    }
}

From source file:com.parse.ParseFileUtilsTest.java

@Test
public void testReadFileToString() throws Exception {
    File file = temporaryFolder.newFile("file.txt");
    BufferedOutputStream out = null;
    try {//  w w w .  j a va2s .  co m
        out = new BufferedOutputStream(new FileOutputStream(file));
        out.write(TEST_STRING.getBytes("UTF-8"));
    } finally {
        ParseIOUtils.closeQuietly(out);
    }

    assertEquals(TEST_STRING, ParseFileUtils.readFileToString(file, "UTF-8"));
}

From source file:com.parse.ParseFileUtilsTest.java

@Test
public void testReadFileToJSONObject() throws Exception {
    File file = temporaryFolder.newFile("file.txt");
    BufferedOutputStream out = null;
    try {/*from  ww w. j ava2s . com*/
        out = new BufferedOutputStream(new FileOutputStream(file));
        out.write(TEST_JSON.getBytes("UTF-8"));
    } finally {
        ParseIOUtils.closeQuietly(out);
    }

    JSONObject json = ParseFileUtils.readFileToJSONObject(file);
    assertNotNull(json);
    assertEquals("bar", json.getString("foo"));
}

From source file:com.camel.action.base.MerchantAction.java

public void handleFileUpload(FileUploadEvent event) {
    try {/*  w ww  .  j a v  a2s. c  o m*/
        String fileName = event.getFile().getFileName();
        UploadedFile source = event.getFile();

        String folderPath = "/opt/merchant/" + Helper.getCurrentUserMerchant().getId();
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String filePath = folderPath + "/" + fileName;
        byte[] bytes = null;
        if (null != source) {
            bytes = source.getContents();

            File newFile = new File(filePath);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
            stream.write(bytes);
            stream.close();
            System.out.println("FilenameUtils.getExtension(filePath).toUpperCase()..:"
                    + FilenameUtils.getExtension(filePath).toUpperCase());
            System.out.println("source.getContentType()...:" + source.getContentType());

            MerchantFile mfile = new MerchantFile();
            mfile.setMerchantFileType(MerchantFileType.CUSTOMEROFFERTEMPLATE);
            mfile.setMerchant(getInstance());
            mfile.setFileName(fileName);
            mfile.setFilePath(filePath);
            mfile.setFileType(FilenameUtils.getExtension(filePath).toUpperCase());
            mfile.setFileMimeType(source.getContentType());
            mfile.setStatus(Status.ACTIVE);
            getCrud().createObject(mfile);

            merchantFiles = new ArrayList<MerchantFile>();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, message);
}