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:org.openme.openme.java

public static JSONObject remote_access(JSONObject i) {
    /*/*from w ww  . j a va 2 s  . co  m*/
    Input:  {
      cm_remote_url             - remote URL
      (cm_user_uoa)             -
      (cm_user_password)        -
      (cm_user_password1)       -
      (remote_repo_uoa)
            
      (remote_pre_auth)         - if 'yes', need standard http login/password pre-authentication
      (cm_remote_user_name)     - remote username
      (cm_remote_user_password) - remote password
            
      (cm_web_module_uoa)       - module to run
      (cm_web_action)           - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (cm_save_to_file)         - if cm_web_action==download,
                                  save output to this file
            
      (cm_console)              - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to cm_stdout
            
      ...                       - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      cm_return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (cm_error)  - error text, if cm_return > 0
      (cm_stdout) - if cm_console='txt', output there
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    URL u;
    HttpURLConnection c = null;

    // Prepare request
    String x = "";
    String post = "";

    String con = "";
    x = (String) i.get("cm_console");
    if (x != null && x != "")
        con = x;

    String url = (String) i.get("cm_remote_url");
    if (url == null || url == "") {
        r.put("cm_return", new Long(1));
        r.put("cm_error", "'cm_remote_url is not defined");
        return r;
    }
    i.remove("cm_remote_url");

    x = (String) i.get("cm_user_uoa");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_uoa=" + x;
        i.remove("cm_user_uoa");
    }

    String save_to_file = (String) i.get("cm_save_to_file");
    if (save_to_file != null)
        i.remove("cm_save_to_file");

    x = (String) i.get("cm_user_password");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_password=" + x;
        i.remove("cm_user_password");
    }

    x = (String) i.get("cm_user_password1");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_password1=" + x;
        i.remove("cm_user_password1");
    }

    x = (String) i.get("remote_repo_uoa");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_repo_uoa=" + x;
        i.remove("remote_repo_uoa");
    }

    // Check if needed remote pre-authentication
    String base64string = "";
    x = (String) i.get("remote_pre_auth");
    if (x == "yes") {
        i.remove("remote_pre_auth");

        String username = "";
        String password = "";

        x = (String) i.get("cm_remote_user_name");
        if (x != null && x != "") {
            username = x;
            i.remove("cm_remote_user_name");
        }

        x = (String) i.get("cm_remote_user_password");
        if (x != null && x != "") {
            password = x;
            i.remove("cm_remote_user_password");
        }

        x = username + ":" + password;
        base64string = new String(Base64.encodeBase64(x.replace("\n", "").getBytes()));
    }

    // Check if data download, not json and convert it to download request
    boolean download = false;

    x = (String) i.get("cm_web_action");
    if (x == "download" || x == "show") {
        download = true;
        if (post != "")
            post += "&";
        post += "cm_web_module_uoa=web&cm_web_action=" + x;
        i.remove("cm_web_action");

        if (((String) i.get("cm_web_module_uoa")) != null)
            i.remove("cm_web_module_uoa");
        if (((String) i.get("cm_console")) != null)
            i.remove("cm_console");
    }

    // Prepare array to transfer through Internet
    JSONObject ii = new JSONObject();
    ii.put("cm_array", i);
    JSONObject rx = convert_cm_array_to_uri(ii);
    if ((Long) rx.get("cm_return") > 0)
        return rx;

    if (post != "")
        post += "&";
    post += "cm_json=" + ((String) rx.get("cm_string1"));

    // Prepare URL request
    String s = "";
    try {
        //Connect
        u = new URL(url);
        c = (HttpURLConnection) u.openConnection();

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length));
        if (base64string != "")
            c.setRequestProperty("Authorization", "Basic " + base64string);
        c.setUseCaches(false);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Send request
        DataOutputStream dos = new DataOutputStream(c.getOutputStream());
        dos.writeBytes(post);
        dos.flush();
        dos.close();
    } catch (Exception e) {
        if (c != null)
            c.disconnect();

        r.put("cm_return", new Long(1));
        r.put("cm_error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
        return r;
    }

    r.put("cm_return", new Long(0));

    // Check if download, not json!
    if (download) {
        String name = "default_download_name.dat";

        x = ((String) i.get("cm_web_filename"));
        if (x != null && x != "") {
            File xf = new File(x);
            name = xf.getName();
        }

        if (save_to_file != null && save_to_file != "")
            name = save_to_file;

        //Reading response in binary and at the same time saving to file
        try {
            //Read response
            DataInputStream dis = new DataInputStream(c.getInputStream());
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(name));

            byte[] buf = new byte[16384];

            int len;

            while ((len = dis.read(buf)) != -1)
                dos.write(buf, 0, len);

            dos.close();
            dis.close();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("cm_return", new Long(1));
            r.put("cm_error",
                    "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ...");
            return r;
        }
    } else {
        //Reading response in text
        try {
            //Read response
            InputStream is = c.getInputStream();
            BufferedReader f = new BufferedReader(new InputStreamReader(is));
            StringBuffer ss = new StringBuffer();

            while ((x = f.readLine()) != null) {
                ss.append(x);
                ss.append('\r');
            }

            f.close();
            s = ss.toString();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("cm_return", new Long(1));
            r.put("cm_error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
            return r;
        }

        if (con == "json_after_text") {
            String json_sep = "*** ### --- CM JSON SEPARATOR --- ### ***";
            int li = s.lastIndexOf(json_sep);
            if (li >= 0) {
                s = s.substring(li + json_sep.length());
                s = s.trim();
            }
        }

        if (con == "json_after_text" || con == "json") {
            //Parsing json
            try {
                JSONParser parser = new JSONParser();
                r = (JSONObject) parser.parse(s);
            } catch (ParseException ex) {
                r.put("cm_return", new Long(1));
                r.put("cm_error", "can't parse json output (" + ex + ") ...");
                return r;
            }
        } else
            r.put("cm_stdout", s);
    }

    if (c != null)
        c.disconnect();

    return r;
}

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

public LicensePair(String contactLicenseText) throws LicenseException {
    this.originalLicenseString = contactLicenseText;
    if (!new LicenseManager().canDecode(contactLicenseText)) {
        return;// w  w  w . java2  s .  co m
    }

    try {
        byte[] decodedBytes = Base64.decodeBase64(contactLicenseText.getBytes());

        ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
        DataInputStream dIn = new DataInputStream(in);

        int textLength = dIn.readInt();
        this.licenseText = new byte[textLength];
        dIn.read(licenseText);

        this.hash = new byte[dIn.available()];
        dIn.read(hash);
    } catch (IOException e) {
        throw new LicenseException(e);
    }

}

From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileDownloadServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String operationId = req.getParameter("operationid");

    if (user != null && operationId != null && !operationId.isEmpty()) {

        try {//from   w  w w  . j av  a  2  s .  c o m
            GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient();
            Operation operation = client.getOperationById(operationId);

            File file = new File(operation.getDest());
            if (file.isDirectory()) {
                file = new File(operation.getDest() + "/" + FilenameUtils.getName(operation.getSource()));
            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

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

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (GRIDAClientException ex) {
            logger.error(ex);
        }
    }
}

From source file:fr.insalyon.creatis.vip.core.server.rpc.GetFileServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from www. jav a  2 s.  com
        User user = CoreDAOFactory.getDAOFactory().getUserDAO()
                .getUserBySession(req.getParameter(CoreConstants.COOKIES_SESSION));

        String filepath = req.getParameter("filepath");

        if (filepath != null && !filepath.isEmpty()) {

            File file = new File(Server.getInstance().getWorkflowsPath() + filepath);

            boolean isDir = false;
            if (file.isDirectory()) {
                String zipName = file.getAbsolutePath() + ".zip";
                FolderZipper.zipFolder(file.getAbsolutePath(), zipName);
                filepath = zipName;
                file = new File(zipName);
                isDir = true;
            }

            logger.info("(" + user.getEmail() + ") Downloading file '" + filepath + "'.");
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

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

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();

            if (isDir) {
                FileUtils.deleteQuietly(file);
            }
        }

    } catch (DAOException ex) {
        throw new ServletException(ex);
    }
}

From source file:com.eufar.asmm.server.DownloadFunction.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("DownloadFunction - the function started");
    ServletContext context = getServletConfig().getServletContext();
    request.setCharacterEncoding("UTF-8");
    String dir = context.getRealPath("/tmp");
    ;/*from  w w  w . j  av  a 2  s. co m*/
    String filename = "";
    File fileDir = new File(dir);
    try {
        System.out.println("DownloadFunction - create the file on server");
        filename = request.getParameterValues("filename")[0];
        String xmltree = request.getParameterValues("xmltree")[0];

        // format xml code to pretty xml code
        Document doc = DocumentHelper.parseText(xmltree);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        format.setIndentSize(4);
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);

        Writer out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(dir + "/" + filename), "UTF-8"));
        out.append(sw.toString());
        out.flush();
        out.close();
    } catch (Exception ex) {
        System.out.println("ERROR during rendering: " + ex);
    }
    try {
        System.out.println("DownloadFunction - send file to user");
        ServletOutputStream out = response.getOutputStream();
        File file = new File(dir + "/" + filename);
        String mimetype = context.getMimeType(filename);
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-Control", "private, must-revalidate");
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int length;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            out.write(bbuf, 0, length);
        }
        in.close();
        out.flush();
        out.close();
        FileUtils.cleanDirectory(fileDir);
    } catch (Exception ex) {
        System.out.println("ERROR during downloading: " + ex);
    }
    System.out.println("DownloadFunction - file ready to be donwloaded");
}

From source file:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

    if (user != null && queryId != null && !queryId.isEmpty()) {

        try {/* w  w w.j  a  v a 2s .  com*/

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (Exception ex) {
            logger.error(ex);
        }

    }
}

From source file:org.freeeed.ep.web.controller.FileDownloadController.java

@Override
public ModelAndView execute() {
    String result = (String) valueStack.get("file");
    String resultFile = workDir + File.separator + result;

    File toDownload = new File(resultFile);

    try {/*from  w w  w . j  av a 2s.com*/
        int length = 0;
        ServletOutputStream outStream = response.getOutputStream();
        String mimetype = "application/octet-stream";

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

        // 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);
    }

    return new ModelAndView(WebConstants.DOWNLOAD_RESULT);
}

From source file:net.brtly.monkeyboard.plugin.core.panel.PluginDockableLayout.java

@Override
public void readStream(DataInputStream in) throws IOException {
    _id = in.readUTF(); // get the plugin ID
    int bs = in.readInt(); // get the size, in bytes, of the Bundle

    byte[] b = new byte[bs]; // read the Bundle
    in.read(b);
}

From source file:com.fabernovel.alertevoirie.data.CategoryProvider.java

@Override
public boolean onCreate() {
    // load json data
    DataInputStream in = new DataInputStream(getContext().getResources().openRawResource(R.raw.categories));
    try {/*from   w ww.j  av a  2s. c o m*/
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
        categories = (JSONObject) new JSONTokener(new String(buffer)).nextValue();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e("Alerte Voirie", "JSON error", e);
    }
    return true;
}

From source file:Decoder.java

private byte[] checkAndGetLicenseText(String licenseContent) throws Exception {
    byte[] licenseText;
    try {/* www .  j  av a  2s  . 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;
}