Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

From source file:BA.Server.FileUpload.java

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request/*w w  w.  j av a2 s.  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    PrintWriter outp = resp.getWriter();

    PrintWriter writer = null;

    try {
        writer = resp.getWriter();
    } catch (IOException ex) {
        log(FileUpload.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    StringBuffer buff = new StringBuffer();

    File file1 = (File) req.getAttribute("file");

    if (file1 == null || !file1.exists()) {
        System.out.println("File does not exist");
    } else if (file1.isDirectory()) {
        System.out.println("File is a directory");
    }

    else {
        File outputFile = new File("/tmp/" + req.getParameter("file"));
        file1.renameTo(outputFile);

        FileInputStream f = new FileInputStream(outputFile);

        // Here BufferedInputStream is added for fast reading.
        BufferedInputStream bis = new BufferedInputStream(f);
        DataInputStream dis = new DataInputStream(bis);
        int i = 0;
        String result = "";

        writer.write("<html>");
        writer.write("<head><script type='text/javascript'>");
        while (dis.available() != 0) {
            String current = dis.readLine();

            if (((String) req.getParameter("uploadType")).equals("equations")) {
                if (FormulaTester.testInput(current) == -1) {
                    writer.write("window.opener.addTabExt(\"" + current + "\" , \"" + req.getParameter("file")
                            + "\");");
                }
            } else {
                writer.write("window.opener.addMacroExt(\"" + current + "\");");
            }
            i++;

        }

        writer.write("this.close();</script></head>");
        writer.write("</script></head>");
        writer.write("<body>");
        writer.write("</body>");
        writer.write("</html>");

        writer.flush();
        writer.close();

        dis.close();
        bis.close();
        f.close();
        outputFile.delete();

    }
}

From source file:Decoder.java

private byte[] checkAndGetLicenseText(String licenseContent) throws Exception {
    byte[] licenseText;
    try {/*from w ww  .  j a v  a 2  s  .  co  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 Exception("Failed to verify the license.");
            }

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

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

    return licenseText;
}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

@SuppressWarnings("deprecation")
public String sendRequest(String payLoad, String authToken) {
    URLConnection conn = null;//from   w w w . j  a v  a2  s  .c  o m
    String strRet = null;
    try {
        URL urlConn = new URL(payLoad);

        conn = null;
        conn = urlConn.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Accept", "application/json");

        DataInputStream dataIn = new DataInputStream(conn.getInputStream());
        String strChunk = "";
        StringBuilder sb = new StringBuilder("");
        while (null != ((strChunk = dataIn.readLine())))
            sb.append(strChunk);

        strRet = sb.toString();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.out.println("MalformedURLException in DSCommHandler");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOException in DSCommHandler: " + conn.getHeaderField(0));
        //         e.printStackTrace();
    }
    return strRet;
}

From source file:com.alphabetbloc.accessmrs.tasks.CheckConnectivityTask.java

protected DataInputStream getServerStream() throws Exception {

    HttpPost request = new HttpPost(mServer);
    request.setEntity(new OdkAuthEntity());
    HttpResponse response = httpClient.execute(request);
    response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    responseEntity.getContentLength();/*ww  w .ja  v  a2 s.  c o  m*/

    DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent()));

    int status = zdis.readInt();
    if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
        zdis.close();
        throw new IOException("Access denied. Check your username and password.");
    } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) {
        zdis.close();
        throw new IOException("Connection Failed. Please Try Again.");
    } else {
        assert (status == HttpURLConnection.HTTP_OK); // success
        return zdis;
    }
}

From source file:com.cloudera.impala.security.DelegationTokenTest.java

private void testTokenManager(boolean useZK) throws IOException {
    String userName = UserGroupInformation.getCurrentUser().getUserName();
    Configuration config = new Configuration();
    ZooKeeperSession zk = null;/*from   www  .ja  v  a2 s .  c  om*/
    if (useZK) {
        config.set(ZooKeeperSession.ZOOKEEPER_CONNECTION_STRING_CONF, ZOOKEEPER_HOSTPORT);
        config.set(ZooKeeperSession.ZOOKEEPER_STORE_ACL_CONF, ZOOKEEPER_ACL);
        zk = new ZooKeeperSession(config, "test", 1, 1);
    }
    DelegationTokenManager mgr = new DelegationTokenManager(config, true, zk);

    // Create two tokens
    byte[] token1 = mgr.getToken(userName, userName, userName).token;
    byte[] token2 = mgr.getToken(userName, userName, null).token;

    // Retrieve the passwords by token. Although the token contains the
    // password, this retrieves it using just the identifier.
    byte[] password1 = mgr.getPasswordByToken(token1);
    byte[] password2 = mgr.getPasswordByToken(token2);

    // Make sure it matches the password in token and doesn't match the password for
    // the other token.
    Token<DelegationTokenIdentifier> t1 = new Token<DelegationTokenIdentifier>();
    t1.decodeFromUrlString(new String(token1));
    assertTrue(Arrays.equals(t1.getPassword(), password1));
    assertFalse(Arrays.equals(t1.getPassword(), password2));

    // Get the password from just the identifier. This does not contain the password
    // but the server stores it.
    DelegationTokenIdentifier id1 = new DelegationTokenIdentifier();
    id1.readFields(new DataInputStream(new ByteArrayInputStream(t1.getIdentifier())));
    byte[] serializedId1 = Base64.encodeBase64(id1.serialize());
    assertTrue(serializedId1.length < token1.length);

    // Retrieve the password from the manager by serialized id.
    DelegationTokenManager.UserPassword userPw = mgr.retrieveUserPassword(new String(serializedId1));
    assertTrue(Arrays.equals(password1, Base64.decodeBase64(userPw.password)));
    assertEquals(userName, userPw.user);

    // Cancel token2, token1 should continue to work fine.
    mgr.cancelToken(userName, token2);
    assertTrue(Arrays.equals(mgr.getPasswordByToken(token1), password1));

    // Renew token1, should continue to work.
    mgr.renewToken(userName, token1);
    assertTrue(Arrays.equals(mgr.getPasswordByToken(token1), password1));

    // Cancel token1, should fail to get password for it.
    mgr.cancelToken(userName, token1);
    boolean exceptionThrown = false;
    try {
        mgr.getPasswordByToken(token1);
    } catch (IOException e) {
        exceptionThrown = true;
        assertTrue(e.getMessage().contains("can't be found"));
    } catch (TokenStoreException e) {
        exceptionThrown = true;
        assertTrue(e.getMessage(), e.getMessage().contains("Token does not exist"));
    }
    assertTrue(exceptionThrown);

    // Try to renew.
    exceptionThrown = false;
    try {
        mgr.renewToken(userName, token1);
    } catch (IOException e) {
        exceptionThrown = true;
        assertTrue(e.getMessage().contains("Renewal request for unknown token"));
    } catch (TokenStoreException e) {
        exceptionThrown = true;
        assertTrue(e.getMessage(), e.getMessage().contains("Token does not exist"));
    }
    assertTrue(exceptionThrown);

    // Try to cancel.
    try {
        mgr.cancelToken(userName, token1);
    } catch (IOException e) {
        // Depending on the underlying store (ZK vs in mem), we will throw an exception
        // or silently fail. Having cancel be idempotent is reasonable and the ZK
        // behavior.
        assertTrue(e.getMessage().contains("Token not found"));
    }

    // Try a corrupt token.
    exceptionThrown = false;
    try {
        mgr.cancelToken(userName, new byte[100]);
    } catch (IOException e) {
        exceptionThrown = true;
        assertTrue(e.getMessage().contains("Token is corrupt."));
    }
    assertTrue(exceptionThrown);
}

From source file:com.krikelin.spotifysource.AppInstaller.java

public void installJar() throws IOException, SAXException, ParserConfigurationException {

    java.util.jar.JarFile jar = new java.util.jar.JarFile(app_jar);
    // Get manifest
    java.util.Enumeration<JarEntry> enu = jar.entries();
    while (enu.hasMoreElements()) {
        JarEntry elm = enu.nextElement();
        if (elm.getName().equals("SpotifyAppManifest.xml")) {
            DataInputStream dis = new DataInputStream(jar.getInputStream(elm));
            Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(dis);
            dis.close();//from  w w w  .ja v a2s .c o  m
            // Get package name
            String package_name = d.getDocumentElement().getAttribute("package");

            addPackage(package_name, "packages");
            // Get all activities
            NodeList activities = d.getElementsByTagName("activity");
            for (int i = 0; i < activities.getLength(); i++) {
                Element activity = (Element) activities.item(i);
                String name = activity.getAttribute("name"); // Get the name
                // Append the previous name if it starts with .
                if (name.startsWith(".")) {
                    name = name.replace(".", "");

                }
                if (!name.startsWith(package_name)) {
                    name = package_name + "." + name;

                }
                //addPackage(name,"activities");
                NodeList intentFilters = activity.getElementsByTagName("intent-filter");
                for (int j = 0; j < intentFilters.getLength(); j++) {
                    NodeList actions = ((Element) intentFilters.item(0)).getElementsByTagName("action");
                    for (int k = 0; k < actions.getLength(); k++) {
                        String action_name = ((Element) actions.item(k)).getAttribute("name");
                        addPackage(name, "\\activities\\" + action_name);
                    }

                }
            }
            copyFile(app_jar.getAbsolutePath(), SPContainer.EXTENSION_DIR + "\\jar\\" + package_name + ".jar");
            // Runtime.getRuntime().exec("copy \""+app_jar+"\" \""+SPContainer.EXTENSION_DIR+"\\jar\\"+package_name+".jar\"");

        }
    }

}

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletRequest req, HttpServletResponse response,
        String currentFileDownloadPath) {
    DataInputStream in = null;//from  ww  w  .  j a v a 2s.c o m
    ServletOutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = "application/octet-stream";
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        byte[] byteBuffer = new byte[1024];
        in = new DataInputStream(new FileInputStream(file));
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }
    } catch (IOException e) {
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
            }
            try {
                outStream.close();
            } catch (IOException e) {
            }

        }
    }
}

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  w  w  w .  jav  a 2  s  .c  o  m*/
    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.buaa.cfs.security.token.Token.java

/**
 * Get the token identifier object, or null if it could not be constructed (because the class could not be loaded,
 * for example).// w  w w.ja  v  a2 s  . co m
 *
 * @return the token identifier, or null
 *
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public T decodeIdentifier() throws IOException {
    Class<? extends TokenIdentifier> cls = getClassForIdentifier(getKind());
    if (cls == null) {
        return null;
    }
    TokenIdentifier tokenIdentifier = ReflectionUtils.newInstance(cls, null);
    ByteArrayInputStream buf = new ByteArrayInputStream(identifier);
    DataInputStream in = new DataInputStream(buf);
    tokenIdentifier.readFields(in);
    in.close();
    return (T) tokenIdentifier;
}

From source file:com.jfolson.hive.serde.RTypedBytesRecordReader.java

public void initialize(InputStream in, Configuration conf, Properties tbl) throws IOException {
    din = new DataInputStream(in);
    tbIn = new RTypedBytesWritableInput(din);
    tbOut = new RTypedBytesWritableOutput(barrStr);
    String columnTypeProperty = tbl.getProperty(Constants.LIST_COLUMN_TYPES);
    //columnTypes = Arrays.asList(columnTypeProperty.split(","));

    // Read the configuration parameters
    columnTypes = null;/*from   w  w w . j av  a  2s . c  o m*/
    if (columnTypeProperty.length() == 0) {
        columnTypes = new ArrayList<TypeInfo>();
    } else {
        columnTypes = TypeInfoUtils.getTypeInfosFromTypeString(columnTypeProperty);
    }

    numColumns = columnTypes.size();

    // All columns have to be primitive.
    /*for (int c = 0; c < numColumns; c++) {
      if (columnTypes.get(c).getCategory() != Category.PRIMITIVE) {
        throw new RuntimeException(getClass().getName()
    + " only accepts primitive columns, but column[" + c + "] "
    + " has category "
    + columnTypes.get(c).getCategory());
      }
    }*/

    isBinary = new boolean[numColumns];
    useNative = Boolean
            .parseBoolean(tbl.getProperty(RTypedBytesSerDe.NATIVE_PROPERTY, RTypedBytesSerDe.NATIVE_DEFAULT));

    // Constructing the row ObjectInspector:
    // The row consists of some string columns, each column will be a java
    // String object.
    dstOIns.ensureCapacity(columnTypes.size());
    for (int c = 0; c < numColumns; c++) {
        ObjectInspector oi = TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo(columnTypes.get(c));
        dstOIns.add(oi);
        isBinary[c] = false;
        if (oi instanceof PrimitiveObjectInspector) {
            PrimitiveObjectInspector poi = ((PrimitiveObjectInspector) oi);
            if (poi.getPrimitiveCategory() == PrimitiveCategory.BINARY) {
                isBinary[c] = true;
            }
        }
        if (!isBinary[c] && useNative) {
            throw new RuntimeException(
                    "Cannot only load native R serialized objects as Binary type, not: " + oi.getTypeName());
        }
    }
    /*for (String columnType : columnTypes) {
      PrimitiveTypeEntry dstTypeEntry = PrimitiveObjectInspectorUtils
          .getTypeEntryFromTypeName(columnType);
      dstOIns.add(PrimitiveObjectInspectorFactory
          .getPrimitiveWritableObjectInspector(dstTypeEntry.primitiveCategory));
    }*/

}