Example usage for java.io DataInputStream read

List of usage examples for java.io DataInputStream read

Introduction

In this page you can find the example usage for java.io DataInputStream read.

Prototype

public final int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the contained input stream and stores them into the buffer array b.

Usage

From source file:jeeves.utils.Xml.java

/**
 * Reads file into byte array, detects charset and converts from this  
   * charset to UTF8//from  w  w  w  .ja  v a  2 s  .  c  om
 *
 * @param file file to decode and convert to UTF8
 * @return
 * @throws IOException
 * @throws CharacterCodingException
 */

public synchronized static byte[] convertFileToUTF8ByteArray(File file)
        throws IOException, CharacterCodingException {
    FileInputStream in = null;
    DataInputStream inStream = null;
    try {
        in = new FileInputStream(file);
        inStream = new DataInputStream(in);
        byte[] buf = new byte[(int) file.length()];
        int nrRead = inStream.read(buf);

        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(buf, 0, nrRead);
        detector.dataEnd();

        String encoding = detector.getDetectedCharset();
        detector.reset();
        if (encoding != null) {
            if (!encoding.equals("UTF-8")) {
                Log.error(Log.JEEVES, "Detected character set " + encoding + ", converting to UTF-8");
                return convertByteArrayToUTF8ByteArray(buf, encoding);
            }
        }
        return buf;
    } finally {
        if (in != null) {
            IOUtils.closeQuietly(in);
        }
        if (inStream != null) {
            IOUtils.closeQuietly(inStream);
        }
    }
}

From source file:com.vimukti.accounter.license.LicenseManager.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    byte[] licenseText;
    try {/*from   w w w.j a  v  a 2s .c o  m*/
        byte[] decodedBytes = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);
        try {
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(PUBLIC_KEY);
            signature.update(licenseText);
            if (!signature.verify(hash)) {
                throw new LicenseException("Failed to verify the license.");
            }

        } catch (InvalidKeyException e) {
            throw new LicenseException(e);
        } catch (SignatureException e) {
            throw new LicenseException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new LicenseException(e);
        }

    } catch (IOException e) {
        throw new LicenseException(e);
    }

    return licenseText;
}

From source file:net.urosk.reportEngine.ReportsServlet.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String reportDesign = request.getParameter("__report");
    String type = request.getParameter("__format");
    String outputFilename = request.getParameter("__filename");
    String attachment = request.getParameter("attachment");

    //check parameters
    StringBuffer msg = new StringBuffer();

    // checkers/*from www .  j  a  va 2  s  . c om*/
    if (isEmpty(reportDesign)) {
        msg.append("<BR>__report can not be empty");
    }

    OutputType outputType = null;

    try {
        outputType = OutputType.valueOf(type.toUpperCase());
    } catch (Exception e) {
        msg.append("Undefined report __format: " + type + ". Set __format=" + OutputType.values());
    }

    // checkers
    if (isEmpty(outputFilename)) {
        msg.append("<BR>__filename can not be empty");
    }

    try {

        ServletOutputStream out = response.getOutputStream();
        ServletContext context = request.getSession().getServletContext();

        // output error
        if (StringUtils.isNotEmpty(msg.toString())) {
            out.print(msg.toString());
            return;
        }

        ReportDef def = new ReportDef();
        def.setDesignFileName(reportDesign);
        def.setOutputType(outputType);

        @SuppressWarnings("unchecked")
        Map<String, String[]> params = request.getParameterMap();
        Iterator<String> i = params.keySet().iterator();

        while (i.hasNext()) {
            String key = i.next();
            String value = params.get(key)[0];
            def.getParameters().put(key, value);
        }

        try {

            String createdFile = birtReportEngine.createReport(def);

            File file = new File(createdFile);

            String mimetype = context.getMimeType(file.getAbsolutePath());

            String inlineOrAttachment = (attachment != null) ? "attachment" : "inline";

            response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition",
                    inlineOrAttachment + "; filename=\"" + outputFilename + "\"");

            DataInputStream in = new DataInputStream(new FileInputStream(file));

            byte[] bbuf = new byte[1024];
            int length;
            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                out.write(bbuf, 0, length);
            }

            in.close();

        } catch (Exception e) {

            logger.error(e, e);
            out.print(e.getMessage());
        } finally {
            out.flush();
            out.close();
        }

        logger.info("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024L * 1024L));

    } catch (Exception e) {
        logger.error(e, e);

    } finally {

    }

}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//from  ww w .j  a va  2s.com
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:org.freeeed.search.web.controller.CaseFileDownloadController.java

@Override
public ModelAndView execute() {
    HttpSession session = this.request.getSession(true);
    SolrSessionObject solrSession = (SolrSessionObject) session
            .getAttribute(WebConstants.WEB_SESSION_SOLR_OBJECT);

    if (solrSession == null || solrSession.getSelectedCase() == null) {
        return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
    }/*from www . ja v  a2  s . c o m*/

    Case selectedCase = solrSession.getSelectedCase();

    String action = (String) valueStack.get("action");

    log.debug("Action called: " + action);

    File toDownload = null;
    boolean htmlMode = false;

    String docPath = (String) valueStack.get("docPath");
    String uniqueId = (String) valueStack.get("uniqueId");

    try {
        if ("exportNative".equals(action)) {
            toDownload = caseFileService.getNativeFile(selectedCase.getName(), docPath, uniqueId);

        } else if ("exportImage".equals(action)) {
            toDownload = caseFileService.getImageFile(selectedCase.getName(), docPath, uniqueId);
        } else if ("exportHtml".equals(action)) {
            toDownload = caseFileService.getHtmlFile(selectedCase.getName(), docPath, uniqueId);
            htmlMode = true;
        } else if ("exportHtmlImage".equals(action)) {
            toDownload = caseFileService.getHtmlImageFile(selectedCase.getName(), docPath);
            htmlMode = true;
        } else if ("exportNativeAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            toDownload = caseFileService.getNativeFiles(selectedCase.getName(), docs);

        } else if ("exportNativeAllFromSource".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            String source = (String) valueStack.get("source");
            try {
                source = URLDecoder.decode(source, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            }

            toDownload = caseFileService.getNativeFilesFromSource(source, docs);
        } else if ("exportImageAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);
            toDownload = caseFileService.getImageFiles(selectedCase.getName(), docs);
        }
    } catch (Exception e) {
        log.error("Problem sending cotent", e);
        valueStack.put("error", true);
    }

    if (toDownload != null) {
        try {
            int length = 0;
            ServletOutputStream outStream = response.getOutputStream();
            String mimetype = "application/octet-stream";
            if (htmlMode) {
                mimetype = "text/html";
            }

            response.setContentType(mimetype);
            response.setContentLength((int) toDownload.length());
            String fileName = toDownload.getName();

            if (!htmlMode) {
                // sets HTTP header
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            }

            byte[] byteBuffer = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(toDownload));

            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }

            in.close();
            outStream.close();
        } catch (Exception e) {
            log.error("Problem sending cotent", e);
            valueStack.put("error", true);
        }
    } else {
        valueStack.put("error", true);
    }

    return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
}

From source file:ub.botiga.ServletDispatcher.java

private void controlProduct(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String location = request.getRequestURI();
    String prod = URLDecoder.decode(location.split("/")[3], "UTF-8");
    Product p = data.getProductes().get(prod);

    User u = (User) request.getSession().getAttribute("user");
    if (u == null || p == null) {
        response.sendRedirect("/Botiga");
        return;/*from w  ww. j a v  a  2s  . c  om*/
    }

    if (!u.getProducts().containsKey(p.getName())) {
        showPage(request, response, "error403.jsp");
        return;
    }

    ServletContext context = getServletContext();
    String realpath = context.getRealPath("/WEB-INF/products" + p.getPath());

    File file = new File(realpath);
    int length;
    ServletOutputStream outStream = response.getOutputStream();
    String mimetype = context.getMimeType(realpath);

    if (mimetype == null) {
        mimetype = "application/octet-stream";
    }

    response.setContentType(mimetype);
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    byte[] byteBuffer = new byte[1024];
    DataInputStream in = new DataInputStream(new FileInputStream(file));

    while ((length = in.read(byteBuffer)) != -1) {
        outStream.write(byteBuffer, 0, length);
    }

    in.close();
    outStream.close();

}

From source file:org.apache.apex.malhar.stream.api.operator.FunctionOperator.java

@SuppressWarnings("unchecked")
private void readFunction() {
    try {/*  w w w. ja  v a  2 s  .  c om*/
        if (statelessF != null || statefulF != null) {
            return;
        }
        DataInputStream input = new DataInputStream(new ByteArrayInputStream(annonymousFunctionClass));
        byte[] classNameBytes = new byte[input.readInt()];
        input.read(classNameBytes);
        String className = new String(classNameBytes);
        byte[] classData = new byte[input.readInt()];
        input.read(classData);
        Map<String, byte[]> classBin = new HashMap<>();
        classBin.put(className, classData);
        ByteArrayClassLoader byteArrayClassLoader = new ByteArrayClassLoader(classBin,
                Thread.currentThread().getContextClassLoader());
        statelessF = ((Class<FUNCTION>) byteArrayClassLoader.findClass(className)).newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.xenei.compressedgraph.SerializableNode.java

private String read(DataInputStream is) throws IOException {
    int n = is.readInt();
    if (n == -1) {
        return null;
    }/* w ww.  j a  v  a  2 s  .  co m*/
    byte[] b = new byte[n];
    if (n > 0) {
        is.read(b);
    }
    return decodeString(b);
}

From source file:org.apache.apex.malhar.lib.function.FunctionOperator.java

@SuppressWarnings("unchecked")
private void readFunction() {
    try {/*from ww w.j  ava2 s.  com*/
        if (statelessF != null || statefulF.getValue() != null) {
            return;
        }
        DataInputStream input = new DataInputStream(new ByteArrayInputStream(annonymousFunctionClass));
        byte[] classNameBytes = new byte[input.readInt()];
        input.read(classNameBytes);
        String className = new String(classNameBytes);
        byte[] classData = new byte[input.readInt()];
        input.read(classData);
        Map<String, byte[]> classBin = new HashMap<>();
        classBin.put(className, classData);
        ByteArrayClassLoader byteArrayClassLoader = new ByteArrayClassLoader(classBin,
                Thread.currentThread().getContextClassLoader());
        statelessF = ((Class<FUNCTION>) byteArrayClassLoader.findClass(className)).newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ZipExploder.java

/** Read all the bytes in a ZIPed file */
protected byte[] readAllBytes(DataInputStream is) throws IOException {
    byte[] bytes = new byte[0];
    for (int len = is.available(); len > 0; len = is.available()) {
        byte[] xbytes = new byte[len];
        int count = is.read(xbytes);
        if (count > 0) {
            byte[] nbytes = new byte[bytes.length + count];
            System.arraycopy(bytes, 0, nbytes, 0, bytes.length);
            System.arraycopy(xbytes, 0, nbytes, bytes.length, count);
            bytes = nbytes;//from w w  w.j  a  v a 2  s. c om
        } else if (count < 0) {
            // accommodate apparent bug in IBM JVM where
            // available() always returns positive value on some files
            break;
        }
    }
    return bytes;
}