Example usage for org.apache.commons.io FileUtils readFileToByteArray

List of usage examples for org.apache.commons.io FileUtils readFileToByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToByteArray.

Prototype

public static byte[] readFileToByteArray(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a byte array.

Usage

From source file:jetbrains.buildServer.torrent.TorrentTransportTest.java

@BeforeMethod
public void setUp() throws Exception {
    super.setUp();
    myServer = new Server(12345);
    WebAppContext handler = new WebAppContext();
    handler.setResourceBase("/");
    handler.setContextPath(CONTEXT_PATH);
    myDownloadMap = new HashMap<String, File>();
    myDownloadAttempts = new ArrayList<String>();
    myDownloadHonestly = true;/*  ww  w.j  a v  a2s .  c  o  m*/
    myDownloadHacks = new HashMap<String, byte[]>();
    myDownloadHackAttempts = new ArrayList<String>();
    handler.addServlet(new ServletHolder(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            myDownloadAttempts.add(req.getPathInfo());
            final ServletOutputStream os = resp.getOutputStream();
            final File file = myDownloadMap.get(req.getPathInfo());
            final byte[] bytes = FileUtils.readFileToByteArray(file);
            os.write(bytes);
            os.close();
        }
    }), "/*");
    myServer.setHandler(handler);
    myServer.start();

    myAgentParametersMap = new HashMap<String, String>();

    Mockery m = new Mockery();
    myBuild = m.mock(AgentRunningBuild.class);
    final BuildProgressLogger myLogger = new BaseServerLoggerFacade() {
        @Override
        public void flush() {
        }

        @Override
        protected void log(final BuildMessage1 message) {

        }
    };

    m.checking(new Expectations() {
        {
            allowing(myBuild).getSharedConfigParameters();
            will(returnValue(myAgentParametersMap));
            allowing(myBuild).getBuildTypeId();
            will(returnValue("TC_Gaya80x_BuildDist"));
            allowing(myBuild).getBuildLogger();
            will(returnValue(myLogger));
        }
    });

    myDirectorySeeder = new TorrentsDirectorySeeder(createTempDir(), -1, 1);

    myTorrentTransport = new TorrentTransportFactory.TorrentTransport(myDirectorySeeder, new HttpClient(),
            myBuild.getBuildLogger()) {
        @Override
        protected byte[] download(@NotNull String urlString) throws IOException {
            if (myDownloadHonestly) {
                return super.download(urlString);
            } else {
                myDownloadHackAttempts.add(urlString);
                return myDownloadHacks.get(urlString);
            }
        }
    };

    myTempDir = createTempDir();
}

From source file:it.smartcommunitylab.parking.management.web.manager.MarkerIconStorage.java

private byte[] getTemplateMarker(String basePath, String company, String entity) throws IOException {
    String filename = getIconFolder(basePath, ICON_FOLDER_TEMPLATE);
    List<String> markerDetails = getMarkerIconDetails(company, entity);
    if (markerDetails == null) {
        String templateIcon = TEMPLATE_PREFIX + entity + TEMPLATE_EXT;
        if (!new File(filename + templateIcon).exists()) {
            filename += TEMPLATE_FILE;/*from   ww w.  j av a  2 s. co  m*/
        } else {
            filename += templateIcon;
        }
    } else {
        filename += markerDetails.get(0);
    }

    return FileUtils.readFileToByteArray(new File(filename));
}

From source file:com.chiorichan.http.UploadedFile.java

public byte[] readToBytes() throws IOException {
    if (isInMemory() || file == null)
        return cachedFileUpload.content().array();
    else/*www.ja v a2 s.  c  o m*/
        return FileUtils.readFileToByteArray(file);
}

From source file:com.tangfan.test.UserServiceTest.java

/**
 * testUpload webservice?/*from  www. j  av a2  s .  c  o m*/
 */
@Test
public void testUpload() {
    try {
        byte[] file = FileUtils
                .readFileToByteArray(new File("C:/Users/Administrator/Pictures/QQ20150206132707.jpg"));
        port.upload(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sangupta.shire.util.WebResponseCacheInterceptor.java

/**
 * Get {@link WebResponse} as previously saved from the cache dir, if
 * available/* w  w  w  .j av  a 2s  .  c o  m*/
 * 
 * @param url
 *            the URL that needs to be hit
 * 
 * @return the response as available
 */
private WebResponse getFromCache(String url) {
    File cache = getCacheFile(url);
    if (cache == null || !cache.exists()) {
        return null;
    }

    try {
        WebResponse response = (WebResponse) SerializationUtils
                .deserialize(FileUtils.readFileToByteArray(cache));
        return response;
    } catch (IOException e) {
        // eat up
    }

    return null;
}

From source file:com.nubits.nubot.utils.Utils.java

/**
 * @param pathToFile//from   w  w  w .  java 2  s .c  o m
 * @param passphrase
 * @return
 */
public static String decode(String pathToFile, String passphrase) {
    String clearString = null;
    MessageDigest digest;
    try {
        //Encapsule the passphrase in a 16bit SecretKeySpec key
        digest = MessageDigest.getInstance("SHA");
        digest.update(passphrase.getBytes());
        SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES");

        Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
        aes.init(Cipher.DECRYPT_MODE, key);

        byte[] ciphertextBytes = FileUtils.readFileToByteArray(new File(pathToFile));
        clearString = new String(aes.doFinal(ciphertextBytes));

    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | BadPaddingException | IllegalBlockSizeException ex) {
        LOG.error(ex.toString());
        return "-1";
    }
    return clearString;
}

From source file:io.appium.java_client.ComparesImages.java

/**
 * Performs images matching by features. Read
 * https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html
 * for more details on this topic.//  w w w.j a  va  2  s  .c  om
 *
 * @param image1 The location of the first image
 * @param image2 The location of the second image
 * @param options comparison options
 * @return The matching result. The configuration of fields in the result depends on comparison options.
 */
default FeaturesMatchingResult matchImagesFeatures(File image1, File image2,
        @Nullable FeaturesMatchingOptions options) throws IOException {
    return matchImagesFeatures(Base64.encodeBase64(FileUtils.readFileToByteArray(image1)),
            Base64.encodeBase64(FileUtils.readFileToByteArray(image2)), options);
}

From source file:eionet.webq.converter.MultipartFileToUserFileConverterTest.java

@Test
public void whenConvertingMultipartFile_ifAttachmentTypeIsZipFile_unpackAllFiles() throws Exception {
    Collection<UserFile> files = fileConverter.convert(createMultipartFile(ZIP_ATTACHMENT_MEDIA_TYPE,
            FileUtils.readFileToByteArray(new File(TEST_XML_FILES_ZIP))));

    verifyContentExtractedFromTestZipFile(files);
}

From source file:com.oneis.utils.ImageColouring.java

/**
 * Rewrite colours in GIF colour table without decoding and recoding the
 * image.//from  w w  w .  j  a v a  2  s .c  o  m
 */
static private boolean colourImageGIF(String Filename, ColouringInfo colouringInfo, OutputStream Output)
        throws IOException {
    byte[] gif = FileUtils.readFileToByteArray(new File(Filename));

    if (gif.length < GIF_GLOBAL_COLOUR_TABLE_OFFSET) {
        return false;
    }
    if (gif[0] != (byte) 'G' || gif[1] != (byte) 'I' || gif[2] != (byte) 'F') {
        // Bad header
        return false;
    }
    if ((((int) gif[GIF_FLAGS_OFFSET]) & GIF_FLAGS_HAS_GLOBAL_COLOUR_TABLE) == 0) {
        // No global colour table to change
        return false;
    }
    int SizeOfGlobalColourTable = (((int) gif[GIF_FLAGS_OFFSET]) & GIF_FLAGS_GLOBAL_COLOUR_TABLE_SIZE_MASK);
    int entriesInColourTable = 1 << (SizeOfGlobalColourTable + 1);
    if (gif.length < (GIF_GLOBAL_COLOUR_TABLE_OFFSET + (entriesInColourTable * 3))) {
        // Not enough space for the advertised colour table
        return false;
    }
    if (entriesInColourTable > 1000) {
        // safety
        return false;
    }

    // Turn the entries into RGB ints
    int[] colourTable = new int[entriesInColourTable];
    for (int e = 0; e < entriesInColourTable; ++e) {
        // Where does the entry start?
        int s = GIF_GLOBAL_COLOUR_TABLE_OFFSET + (e * 3);
        colourTable[e] = ((((int) gif[s + RED]) << 16) & 0xff0000) | ((((int) gif[s + GREEN]) << 8) & 0xff00)
                | (((int) gif[s + BLUE]) & 0xff);
    }

    doColouring(colourTable, colouringInfo);

    // Write the entiries back
    for (int e = 0; e < entriesInColourTable; ++e) {
        // Where does the entry start?
        int s = GIF_GLOBAL_COLOUR_TABLE_OFFSET + (e * 3);
        int r = (colourTable[e] >> 16) & 0xff;
        int g = (colourTable[e] >> 8) & 0xff;
        int b = colourTable[e] & 0xff;
        gif[s + RED] = (byte) r;
        gif[s + GREEN] = (byte) g;
        gif[s + BLUE] = (byte) b;
    }

    Output.write(gif);

    return true;
}

From source file:com.igormaznitsa.jcp.expression.functions.FunctionBINFILE.java

@Nonnull
private static String convertTo(@Nonnull final File file, @Nonnull final Type type, final boolean deflate,
        final int lineLength, @Nonnull final String endOfLine) throws IOException {
    final StringBuilder result = new StringBuilder(512);
    byte[] array = FileUtils.readFileToByteArray(file);

    if (deflate) {
        array = deflate(array);// w  ww . ja  va 2s  .  c  o m
    }

    int endLinePos = lineLength;
    boolean addNextLine = false;

    switch (type) {
    case BASE64: {
        final String baseEncoded = new Base64(lineLength, endOfLine.getBytes("UTF-8"), false)
                .encodeAsString(array);
        result.append(baseEncoded.trim());
    }
        break;
    case BYTEARRAY:
    case INT8:
    case UINT8: {
        for (final byte b : array) {
            if (result.length() > 0) {
                result.append(',');
            }

            if (addNextLine) {
                addNextLine = false;
                result.append(endOfLine);
            }

            switch (type) {
            case BYTEARRAY: {
                result.append("(byte)0x").append(Integer.toHexString(b & 0xFF).toUpperCase(Locale.ENGLISH));
            }
                break;
            case UINT8: {
                result.append(Integer.toString(b & 0xFF).toUpperCase(Locale.ENGLISH));
            }
                break;
            case INT8: {
                result.append(Integer.toString(b).toUpperCase(Locale.ENGLISH));
            }
                break;
            default:
                throw new Error("Unexpected type : " + type);
            }

            if (lineLength > 0 && result.length() >= endLinePos) {
                addNextLine = true;
                endLinePos = result.length() + lineLength;
            }
        }

    }
        break;
    default:
        throw new Error("Unexpected type : " + type);
    }

    return result.toString();
}