Example usage for java.io RandomAccessFile write

List of usage examples for java.io RandomAccessFile write

Introduction

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

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

Usage

From source file:org.red5.server.service.ShutdownServer.java

/**
 * Starts internal server listening for shutdown requests.
 *///from   w w  w.  j a  va2 s  .  c om
public void start() {
    // dump to stdout
    System.out.printf("Token: %s%n", token);
    // write out the token to a file so that red5 may be shutdown external to this VM instance.
    try {
        // delete existing file
        Files.deleteIfExists(Paths.get(shutdownTokenFileName));
        // write to file
        Path path = Files.createFile(Paths.get(shutdownTokenFileName));
        File tokenFile = path.toFile();
        RandomAccessFile raf = new RandomAccessFile(tokenFile, "rws");
        raf.write(token.getBytes());
        raf.close();
    } catch (Exception e) {
        log.warn("Exception handling token file", e);
    }
    while (!shutdown.get()) {
        try (ServerSocket serverSocket = new ServerSocket(port);
                Socket clientSocket = serverSocket.accept();
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {
            log.info("Connected - local: {} remote: {}", clientSocket.getLocalSocketAddress(),
                    clientSocket.getRemoteSocketAddress());
            String inputLine = in.readLine();
            if (inputLine != null && token.equals(inputLine)) {
                log.info("Shutdown request validated using token");
                out.println("Ok");
                shutdownOrderly();
            } else {
                out.println("Bye");
            }
        } catch (BindException be) {
            log.error("Cannot bind to port: {}, ensure no other instances are bound or choose another port",
                    port, be);
            shutdownOrderly();
        } catch (IOException e) {
            log.warn("Exception caught when trying to listen on port {} or listening for a connection", port,
                    e);
        }
    }
}

From source file:org.ofbiz.product.imagemanagement.ImageManagementServices.java

public static Map<String, Object> addMultipleuploadForProduct(DispatchContext dctx,
        Map<String, ? extends Object> context) throws IOException, JDOMException {

    Map<String, Object> result = FastMap.newInstance();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String productId = (String) context.get("productId");
    productId = productId.trim();//  w  w  w .  j  av a2 s.  com
    String productContentTypeId = (String) context.get("productContentTypeId");
    ByteBuffer imageData = (ByteBuffer) context.get("uploadedFile");
    String uploadFileName = (String) context.get("_uploadedFile_fileName");
    String imageResize = (String) context.get("imageResize");
    Locale locale = (Locale) context.get("locale");

    if (UtilValidate.isNotEmpty(uploadFileName)) {
        String imageFilenameFormat = UtilProperties.getPropertyValue("catalog", "image.filename.format");
        String imageServerPath = FlexibleStringExpander
                .expandString(UtilProperties.getPropertyValue("catalog", "image.management.path"), context);
        String imageServerUrl = FlexibleStringExpander
                .expandString(UtilProperties.getPropertyValue("catalog", "image.management.url"), context);
        String rootTargetDirectory = imageServerPath;
        File rootTargetDir = new File(rootTargetDirectory);
        if (!rootTargetDir.exists()) {
            boolean created = rootTargetDir.mkdirs();
            if (!created) {
                String errMsg = "Cannot create the target directory";
                Debug.logFatal(errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
        }

        String sizeType = null;
        if (UtilValidate.isNotEmpty(imageResize)) {
            sizeType = imageResize;
        }

        Map<String, Object> contentCtx = FastMap.newInstance();
        contentCtx.put("contentTypeId", "DOCUMENT");
        contentCtx.put("userLogin", userLogin);
        Map<String, Object> contentResult = FastMap.newInstance();
        try {
            contentResult = dispatcher.runSync("createContent", contentCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }

        String contentId = (String) contentResult.get("contentId");
        result.put("contentFrameId", contentId);
        result.put("contentId", contentId);

        // File to use for original image
        FlexibleStringExpander filenameExpander = FlexibleStringExpander.getInstance(imageFilenameFormat);
        String fileLocation = filenameExpander
                .expandString(UtilMisc.toMap("location", "products", "type", sizeType, "id", contentId));
        String filenameToUse = fileLocation;
        if (fileLocation.lastIndexOf("/") != -1) {
            filenameToUse = fileLocation.substring(fileLocation.lastIndexOf("/") + 1);
        }

        String fileContentType = (String) context.get("_uploadedFile_contentType");
        if (fileContentType.equals("image/pjpeg")) {
            fileContentType = "image/jpeg";
        } else if (fileContentType.equals("image/x-png")) {
            fileContentType = "image/png";
        }

        List<GenericValue> fileExtension = FastList.newInstance();
        try {
            fileExtension = delegator.findByAnd("FileExtension", UtilMisc.toMap("mimeTypeId", fileContentType));
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }

        GenericValue extension = EntityUtil.getFirst(fileExtension);
        if (extension != null) {
            filenameToUse += "." + extension.getString("fileExtensionId");
        }

        // Create folder product id.
        String targetDirectory = imageServerPath + "/" + productId;
        File targetDir = new File(targetDirectory);
        if (!targetDir.exists()) {
            boolean created = targetDir.mkdirs();
            if (!created) {
                String errMsg = "Cannot create the target directory";
                Debug.logFatal(errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
        }

        File file = new File(imageServerPath + "/" + productId + "/" + uploadFileName);
        String imageName = null;
        imagePath = imageServerPath + "/" + productId + "/" + uploadFileName;
        file = checkExistsImage(file);
        if (UtilValidate.isNotEmpty(file)) {
            imageName = file.getPath();
            imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1);
        }

        if (UtilValidate.isEmpty(imageResize)) {
            // Create image file original to folder product id.
            try {
                RandomAccessFile out = new RandomAccessFile(file, "rw");
                out.write(imageData.array());
                out.close();
            } catch (FileNotFoundException e) {
                Debug.logError(e, module);
                return ServiceUtil
                        .returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteFile",
                                UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
            } catch (IOException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "ProductImageViewUnableWriteBinaryData",
                                UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
            }
        }
        // Scale Image in different sizes 
        if (UtilValidate.isNotEmpty(imageResize)) {
            File fileOriginal = new File(imageServerPath + "/" + productId + "/" + imageName);
            fileOriginal = checkExistsImage(fileOriginal);
            uploadFileName = fileOriginal.getName();

            try {
                RandomAccessFile outFile = new RandomAccessFile(fileOriginal, "rw");
                outFile.write(imageData.array());
                outFile.close();
            } catch (FileNotFoundException e) {
                Debug.logError(e, module);
                return ServiceUtil
                        .returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteFile",
                                UtilMisc.toMap("fileName", fileOriginal.getAbsolutePath()), locale));
            } catch (IOException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "ProductImageViewUnableWriteBinaryData",
                                UtilMisc.toMap("fileName", fileOriginal.getAbsolutePath()), locale));
            }

            Map<String, Object> resultResize = FastMap.newInstance();
            try {
                resultResize.putAll(ImageManagementServices.scaleImageMangementInAllSize(context, imageName,
                        sizeType, productId));
            } catch (IOException e) {
                String errMsg = "Scale additional image in all different sizes is impossible : " + e.toString();
                Debug.logError(e, errMsg, module);
                return ServiceUtil.returnError(errMsg);
            } catch (JDOMException e) {
                String errMsg = "Errors occur in parsing ImageProperties.xml : " + e.toString();
                Debug.logError(e, errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
        }

        Map<String, Object> contentThumbnail = createContentThumbnail(dctx, context, userLogin, imageData,
                productId, imageName);
        String filenameToUseThumb = (String) contentThumbnail.get("filenameToUseThumb");
        String contentIdThumb = (String) contentThumbnail.get("contentIdThumb");

        String imageUrl = imageServerUrl + "/" + productId + "/" + imageName;
        String imageUrlThumb = imageServerUrl + "/" + productId + "/" + filenameToUseThumb;

        createContentAndDataResource(dctx, userLogin, imageName, imageUrl, contentId, fileContentType);
        createContentAndDataResource(dctx, userLogin, filenameToUseThumb, imageUrlThumb, contentIdThumb,
                fileContentType);

        Map<String, Object> createContentAssocMap = FastMap.newInstance();
        createContentAssocMap.put("contentAssocTypeId", "IMAGE_THUMBNAIL");
        createContentAssocMap.put("contentId", contentId);
        createContentAssocMap.put("contentIdTo", contentIdThumb);
        createContentAssocMap.put("userLogin", userLogin);
        createContentAssocMap.put("mapKey", "100");
        try {
            dispatcher.runSync("createContentAssoc", createContentAssocMap);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }

        Map<String, Object> productContentCtx = FastMap.newInstance();
        productContentCtx.put("productId", productId);
        productContentCtx.put("productContentTypeId", productContentTypeId);
        productContentCtx.put("fromDate", UtilDateTime.nowTimestamp());
        productContentCtx.put("userLogin", userLogin);
        productContentCtx.put("contentId", contentId);
        productContentCtx.put("statusId", "IM_PENDING");
        try {
            dispatcher.runSync("createProductContent", productContentCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }

        Map<String, Object> contentApprovalCtx = FastMap.newInstance();
        contentApprovalCtx.put("contentId", contentId);
        contentApprovalCtx.put("userLogin", userLogin);
        try {
            dispatcher.runSync("createImageContentApproval", contentApprovalCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }

        String autoApproveImage = UtilProperties.getPropertyValue("catalog",
                "image.management.autoApproveImage");
        if (autoApproveImage.equals("Y")) {
            Map<String, Object> autoApproveCtx = FastMap.newInstance();
            autoApproveCtx.put("contentId", contentId);
            autoApproveCtx.put("userLogin", userLogin);
            autoApproveCtx.put("checkStatusId", "IM_APPROVED");
            try {
                dispatcher.runSync("updateStatusImageManagement", autoApproveCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        }
    }
    return result;
}

From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java

private static void encryptFile(File file, EncryptedFormInformation formInfo)
        throws IOException, EncryptionException {
    File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc");

    if (encryptedFile.exists() && !encryptedFile.delete()) {
        throw new IOException(
                "Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?");
    }/*  w  w  w  .j  av  a 2  s . c  o  m*/

    // add elementSignatureSource for this file...
    formInfo.appendFileSignatureSource(file);

    RandomAccessFile randomAccessFile = null;
    CipherOutputStream cipherOutputStream = null;
    try {
        Cipher c = formInfo.getCipher();

        randomAccessFile = new RandomAccessFile(encryptedFile, "rws");
        ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
        cipherOutputStream = new CipherOutputStream(encryptedData, c);
        InputStream fin = new FileInputStream(file);
        byte[] buffer = new byte[2048];
        int len = fin.read(buffer);
        while (len != -1) {
            cipherOutputStream.write(buffer, 0, len);
            len = fin.read(buffer);
        }
        fin.close();
        cipherOutputStream.flush();
        cipherOutputStream.close();

        randomAccessFile.write(encryptedData.toByteArray());

        Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName());
    } catch (Exception e) {
        String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName();
        Log.e(t, msg, e);
        e.printStackTrace();
        throw new EncryptionException(msg, e);
    } finally {
        IOUtils.closeQuietly(cipherOutputStream);

        if (randomAccessFile != null) {
            randomAccessFile.close();
        }
    }
}

From source file:com.ibm.watson.developer_cloud.android.text_to_speech.v1.TTSUtility.java

private byte[] analyzeOpusData(InputStream is) {
    String inFilePath = getBaseDir() + "Watson.opus";
    String outFilePath = getBaseDir() + "Watson.pcm";
    File inFile = new File(inFilePath);
    File outFile = new File(outFilePath);
    outFile.deleteOnExit();/*from   w  w  w . j av  a2  s .co m*/
    inFile.deleteOnExit();

    try {
        RandomAccessFile inRaf = new RandomAccessFile(inFile, "rw");
        byte[] opus = IOUtils.toByteArray(is);
        inRaf.write(opus);

        sampleRate = OggOpus.decode(inFilePath, outFilePath, sampleRate); // zero means to detect the sample rate by decoder

        RandomAccessFile outRaf = new RandomAccessFile(outFile, "r");

        byte[] data = new byte[(int) outRaf.length()];

        int outLength = outRaf.read(data);

        inRaf.close();
        outRaf.close();
        if (outLength == 0) {
            throw new IOException("Data reading failed");
        }
        return data;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new byte[0];
}

From source file:org.apache.bookkeeper.bookie.EntryLogTest.java

/**
 * Explicitely try to recover using the ledgers map index at the end of the entry log
 *//*  www . j  a  va  2  s . c  om*/
@Test(timeout = 60000)
public void testRecoverFromLedgersMapOnV0EntryLog() throws Exception {
    File tmpDir = createTempDir("bkTest", ".dir");
    File curDir = Bookie.getCurrentDirectory(tmpDir);
    Bookie.checkDirectoryStructure(curDir);

    int gcWaitTime = 1000;
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();
    conf.setGcWaitTime(gcWaitTime);
    conf.setLedgerDirNames(new String[] { tmpDir.toString() });
    Bookie bookie = new Bookie(conf);

    // create some entries
    EntryLogger logger = ((InterleavedLedgerStorage) bookie.ledgerStorage).entryLogger;
    logger.addEntry(1, generateEntry(1, 1));
    logger.addEntry(3, generateEntry(3, 1));
    logger.addEntry(2, generateEntry(2, 1));
    logger.addEntry(1, generateEntry(1, 2));
    logger.rollLog();

    // Rewrite the entry log header to be on V0 format
    File f = new File(curDir, "0.log");
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(EntryLogger.HEADER_VERSION_POSITION);
    // Write zeros to indicate V0 + no ledgers map info
    raf.write(new byte[4 + 8]);
    raf.close();

    // now see which ledgers are in the log
    logger = new EntryLogger(conf, bookie.getLedgerDirsManager());

    try {
        logger.extractEntryLogMetadataFromIndex(0L);
        fail("Should not be possible to recover from ledgers map index");
    } catch (IOException e) {
        // Ok
    }

    // Public method should succeed by falling back to scanning the file
    EntryLogMetadata meta = logger.getEntryLogMetadata(0L);
    LOG.info("Extracted Meta From Entry Log {}", meta);
    assertEquals(60, meta.getLedgersMap().get(1L).longValue());
    assertEquals(30, meta.getLedgersMap().get(2L).longValue());
    assertEquals(30, meta.getLedgersMap().get(3L).longValue());
    assertNull(meta.getLedgersMap().get(4L));
    assertEquals(120, meta.getTotalSize());
    assertEquals(120, meta.getRemainingSize());
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException/* w  ww. java  2 s .  com*/
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware.
    // see here:
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}

From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java

private void writeTo(File proFile, ProcessInstance pi) {
    LOGGER.debug("write process instance {} to {}", pi.getId(), proFile.getName());
    RandomAccessFile raf = null;
    try {/*from w ww.  j ava  2 s  .com*/
        raf = new RandomAccessFile(proFile, "rw");
        long position = findLastProcess(raf);
        raf.seek(position);
        String s = marshal(pi);
        raf.writeBytes(s);
        raf.write(0x0A);
        raf.writeBytes(ENDDOC);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            raf.close();
        } catch (IOException e) {
        }
    }
}

From source file:name.martingeisse.stackd.server.section.storage.FolderBasedSectionStorage.java

/**
 * // w w  w. j a  v  a 2  s . c o m
 */
private void saveSectionToFile(final InputStream in, final RandomAccessFile access, final int tocIndex)
        throws IOException {

    // write the section to the end of the file
    final int dataAddress = (int) access.length();
    access.seek(dataAddress);
    final byte[] compressedCubeData = IOUtils.toByteArray(in);
    access.write(compressedCubeData);

    // update the ToC entry
    access.seek(tocIndex * 12);
    access.writeInt(dataAddress);
    access.writeInt(compressedCubeData.length);
    access.writeInt(0);

}

From source file:TestFuseDFS.java

/**
 * Test random access to a file// www .j a  v a2s .  c  o  m
 */
@Test
public void testRandomAccess() throws IOException {
    final String contents = "hello world";
    File f = new File(mountPoint, "file1");

    createFile(f, contents);

    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(f.length());
    try {
        raf.write('b');
    } catch (IOException e) {
        // Expected: fuse-dfs not yet support append
        assertEquals("Operation not supported", e.getMessage());
    } finally {
        raf.close();
    }

    raf = new RandomAccessFile(f, "rw");
    raf.seek(0);
    try {
        raf.write('b');
        fail("Over-wrote existing bytes");
    } catch (IOException e) {
        // Expected: can-not overwrite a file
        assertEquals("Invalid argument", e.getMessage());
    } finally {
        raf.close();
    }
    execAssertSucceeds("rm " + f.getAbsolutePath());
}

From source file:edu.umass.cs.gigapaxos.AbstractPaxosLogger.java

/**
 * @param strID//from w w w .  j av a 2  s .  c  o m
 */
public static final void fileLock(Object strID) {
    RandomAccessFile raf = null;
    try {
        String logdir = getLocksDir();
        (new File(logdir)).mkdirs();
        String filename = logdir + "/" + strID;
        File file = new File(filename);
        boolean created = file.createNewFile();
        FileLock lock = (raf = new RandomAccessFile(file, "rw")).getChannel().tryLock();
        if (lock == null)
            throw new RuntimeException("Unable to start node " + strID + " likely because node " + strID
                    + " from " + Util.readFileAsString(filename).split("\n")[0].trim().replaceAll("#", "")
                    + " is already running");
        // lock!=null
        if (created && PaxosConfig.getPropertiesFile() != null) {
            raf.write(("#" + PaxosConfig.getPropertiesFile() + "\n").getBytes());
            raf.write(Util.readFileAsString(PaxosConfig.getPropertiesFile()).getBytes());
        }

    } catch (IOException e) {
        e.printStackTrace();
        if (raf != null)
            try {
                raf.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    }
}