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:com.datos.vfs.provider.http.HttpRandomAccessContent.java

@Override
protected DataInputStream getDataInputStream() throws IOException {
    if (dis != null) {
        return dis;
    }//from w w w  . ja  va2 s.c  om

    final GetMethod getMethod = new GetMethod();
    fileObject.setupMethod(getMethod);
    getMethod.setRequestHeader("Range", "bytes=" + filePointer + "-");
    final int status = fileSystem.getClient().executeMethod(getMethod);
    if (status != HttpURLConnection.HTTP_PARTIAL && status != HttpURLConnection.HTTP_OK) {
        throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(),
                Long.valueOf(filePointer), Integer.valueOf(status));
    }

    mis = new HttpFileObject.HttpInputStream(getMethod);
    // If the range request was ignored
    if (status == HttpURLConnection.HTTP_OK) {
        final long skipped = mis.skip(filePointer);
        if (skipped != filePointer) {
            throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(),
                    Long.valueOf(filePointer), Integer.valueOf(status));
        }
    }
    dis = new DataInputStream(new FilterInputStream(mis) {
        @Override
        public int read() throws IOException {
            final int ret = super.read();
            if (ret > -1) {
                filePointer++;
            }
            return ret;
        }

        @Override
        public int read(final byte[] b) throws IOException {
            final int ret = super.read(b);
            if (ret > -1) {
                filePointer += ret;
            }
            return ret;
        }

        @Override
        public int read(final byte[] b, final int off, final int len) throws IOException {
            final int ret = super.read(b, off, len);
            if (ret > -1) {
                filePointer += ret;
            }
            return ret;
        }
    });

    return dis;
}

From source file:com.cedarsoft.crypt.CertTest.java

@Test
public void testCert() throws Exception {
    DataInputStream inStream = new DataInputStream(getClass().getResource("/test.crt").openStream());

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();/* w w  w.ja v a2  s . c  om*/
    assertNotNull(cert);

    cert.checkValidity();

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, cert);

    byte[] clear = cipher.doFinal(Base64.decodeBase64(SCRAMBLED.getBytes()));
    assertEquals(PLAINTEXT, new String(clear));
}

From source file:eu.cloud4soa.soa.jaxrs.test.ApplicationDeploymentTest.java

public void deployApplication() throws FileNotFoundException {
    //        final String BASE_URI = "http://localhost:8080/frontend-dashboard-0.0.1-SNAPSHOT/services/REST/ApplicationDeploymentRS/deployApplication";
    final String BASE_URI = "http://localhost:8080/cloud4soa.soa/services/REST/ApplicationDeploymentRS/deployApplication";

    WebClient client = WebClient.create(BASE_URI);
    client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN);
    //        ContentDisposition cd = new ContentDisposition("attachment;filename=image.jpg");
    //        Attachment att = new Attachment("root", imageInputStream, cd);

    //        ApplicationDeployment applicationDeploymentRS = (ApplicationDeployment) JAXRSClientFactory.create("http://localhost:8080/books", ApplicationDeployment.class);
    //        WebClient.client(applicationDeploymentRS).type("multipart/mixed");

    URL fileURL = this.getClass().getClassLoader().getResource("SimpleWar.war");
    if (fileURL == null)
        throw new FileNotFoundException("SimpleWar.war");

    ByteArrayOutputStream bas = new ByteArrayOutputStream();

    File file = new File(fileURL.getPath());
    file.length();/*from   w  w  w.  j  a v a  2  s. c om*/
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);

    //Calculate digest from InputStream
    //        InputStream tempIs = new FileInputStream(file);
    String tempFileDigest = null;
    try {
        FileInputStream tempFis = new FileInputStream(file);
        tempFileDigest = DigestUtils.sha256Hex(tempFis);
    } catch (IOException ex) {
        Logger.getLogger(ApplicationDeploymentTest.class.getName()).log(Level.SEVERE, null, ex);
    }

    //        JSONObject applicationInstanceJsonObj=new JSONObject();
    //        try {
    //            applicationInstanceJsonObj.put("acronym","App1");
    //            applicationInstanceJsonObj.put("applicationcode","001");
    //            applicationInstanceJsonObj.put("programminglanguage","Java");
    //        } catch (JSONException ex) {
    //            ex.printStackTrace();
    //        }
    //
    //        System.out.println(applicationInstanceJsonObj);

    JSONObject applicationInstanceJsonObj = new JSONObject();
    try {
        applicationInstanceJsonObj.put("acronym", "SimpleWar");
        applicationInstanceJsonObj.put("archiveFileName", "app");
        applicationInstanceJsonObj.put("archiveExtensionName", ".war");
        applicationInstanceJsonObj.put("digest", tempFileDigest);
        applicationInstanceJsonObj.put("sizeQuantity", file.length());
        applicationInstanceJsonObj.put("version", "2");
        //            applicationInstanceJsonObj.put("","");
    } catch (JSONException ex) {
        Logger.getLogger(ApplicationDeploymentTest.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(applicationInstanceJsonObj);

    JSONObject paaSInstanceJsonObj = new JSONObject();
    try {
        //            paaSInstanceJsonObj.put("providerTitle","CloudBees");
        paaSInstanceJsonObj.put("providerTitle", "Beanstalk");
    } catch (JSONException ex) {
        Logger.getLogger(ApplicationDeploymentTest.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(paaSInstanceJsonObj);

    ProviderFactory.getSharedInstance().registerUserProvider(new JSONProvider());
    // POST the request
    //        Response response = applicationDeploymentRS.deployApplication(dis, applicationInstanceJsonObj, paaSInstanceJsonObj);
    Attachment att1 = new Attachment("applicationInstance", "application/json",
            applicationInstanceJsonObj.toString());
    Attachment att2 = new Attachment("paaSInstance", "application/json", paaSInstanceJsonObj.toString());
    Attachment att3 = new Attachment("applicationArchive", "application/octet-stream", dis);
    List<Attachment> listAttch = new LinkedList<Attachment>();
    listAttch.add(att1);
    listAttch.add(att2);
    listAttch.add(att3);
    Response response = client.post(new MultipartBody(listAttch));
    if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.ACCEPTED)
        try {
            System.out.println(
                    "Response Status : " + IOUtils.readStringFromStream((InputStream) response.getEntity()));
        } catch (IOException ex) {
            Logger.getLogger(ApplicationDeploymentTest.class.getName()).log(Level.SEVERE, null, ex);
        }

    try {
        fis.close();
        bis.close();
        dis.close();
    } catch (IOException ex) {
        Logger.getLogger(ApplicationDeploymentTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:SortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//from   w  ww  . j  a v  a  2  s  .  co  m
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "Mary", "Bob", "Adam" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String[] inputString = new String[3];
            int z = 0;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                comparator.compareClose();
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:brickhouse.udf.bloom.BloomFactory.java

public static Filter ReadBloomFromString(String str) throws IOException {
    if (str != null) {
        Filter filter = NewVesselBloom();
        byte[] decoded = Base64.decodeBase64(str.getBytes());
        DataInputStream dataInput = new DataInputStream(new ByteArrayInputStream(decoded));

        filter.readFields(dataInput);/*from www  . j av  a 2 s  . c  om*/
        return filter;
    } else {
        return NewBloomInstance();
    }
}

From source file:WriteObjectsFromSocket.java

ReaderWriter(Socket rs) {
    // /////////////////////////////////////////////
    // Open a remote stream to the client
    // /////////////////////////////////////////////
    try {// www  .  j a v a  2s  . com
        is = new DataInputStream(rs.getInputStream());
    } catch (Exception e) {
        System.out.println("Unable to get Stream");
        return;
    }
    // /////////////////////////////////////////////
    // Open the file that is to be written to
    // /////////////////////////////////////////////
    try {
        File theFile = new File("/tmp", "Objects");
        System.out.println("The file to be created or overwritten: " + theFile);
        localFile = new FileOutputStream(theFile);
    } catch (IOException e) {
        System.out.println("Open error " + e);
        return;
    }
    // ///////////////////////////////////////////
    // Look for all the double data constantly
    // ///////////////////////////////////////////
    while (writeloop) {
        // Look for data if we get here that is requests
        try {
            inputByte = is.readByte(); // Not the best way to do it
            // Consider looking for available bytes
            // and reading that amount.
        } catch (IOException e) {
            System.out.println("In the read loop:" + e);
            writeloop = false;
        }
        // ///////////////////////////
        // We did get something
        // Write The Data
        // ///////////////////////////
        try {
            localFile.write(inputByte);
        } catch (IOException e) {
            System.out.println("Write failed");
            writeloop = false;
        }
    }
    // ////////////////////////////////
    // Close the connection and file
    // ////////////////////////////////
    try {
        rs.close();
        is.close();
        localFile.close();
    } catch (Exception e) {
        System.out.println("Unable to close ");
    }
    System.out.println("Thread exiting");
}

From source file:org.ala.util.PartialIndex.java

public void process(String args) throws Exception {
    int ctr = 0;/*from w ww. jav a 2s  . com*/
    File file = new File(args);
    FileInputStream fstream = new FileInputStream(file);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String strLine;
    List<String> guidBatch = new java.util.ArrayList<String>(500);
    while ((strLine = br.readLine()) != null) {
        if (guidBatch.size() >= 500) {
            postIndexUpdate(guidBatch.toArray(new String[] {}));
            guidBatch.clear();
        }
        guidBatch.add(strLine);
    }
    if (guidBatch.size() > 0)
        postIndexUpdate(guidBatch.toArray(new String[] {}));

    //      BufferedReader br = new BufferedReader(new InputStreamReader(in));
    ////         loader.cleanIndex();
    //      ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);
    //      IndexingThread[] threads = new IndexingThread[20];
    //      for(int i = 0; i<20;i++){
    //          IndexingThread t = new IndexingThread(i, queue);
    //          threads[i]=t;
    //          t.start();
    //      }
    //      String strLine;
    //      if(solrServer == null){
    //            solrServer = solrUtils.getSolrServer();
    //        }
    //      //Read File Line By Line
    //      while ((strLine = br.readLine()) != null)   {
    //         // Print the content on the console
    //         strLine = strLine.trim();
    //         if(strLine.length() > 0){
    //            //doIndex(strLine);
    //             while(!queue.offer(strLine))
    //                 Thread.currentThread().sleep(50);
    //            ctr++;
    //         }
    //      }
    //      for(IndexingThread t : threads){
    //          t.setCanStop();   
    //          t.join();
    //      }
    //      //Close the input stream
    //      in.close();
    //      
    //      commitIndex();
    //      solrUtils.shutdownSolr();
    logger.info("**** total count: " + ctr);
}

From source file:com.openhr.company.UploadCompLicenseFile.java

@Override
public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();// w ww  .  j  av  a  2 s  .  c  o  m
        return map.findForward("HRHome");
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);

                // Read the file object contents and parse it and store it in the repos
                FileInputStream fstream = new FileInputStream(storeFile);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;

                //Read File Line By Line
                while ((strLine = br.readLine()) != null) {
                    System.out.print("Processing line - " + strLine);

                    String[] lineColumns = strLine.split(COMMA);

                    if (lineColumns.length < 8) {
                        br.close();
                        in.close();
                        fstream.close();
                        throw new Exception("The required columns are missing in the line - " + strLine);
                    }

                    // Format is - CompID,CompName,Branch,Address,From,To,LicenseKey,FinStartMonth
                    String companyId = lineColumns[0];
                    String companyName = lineColumns[1];
                    String branchName = lineColumns[2];
                    String address = lineColumns[3];
                    String fromDateStr = lineColumns[4];
                    String toDateStr = lineColumns[5];
                    String licenseKey = lineColumns[6];
                    String finStartMonthStr = lineColumns[7];

                    Date fromDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH)
                            .parse(fromDateStr);
                    Date toDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH).parse(toDateStr);
                    address = address.replace(";", ",");

                    List<Company> eComp = CompanyFactory.findByName(companyName);
                    if (eComp == null || eComp.isEmpty()) {
                        Company company = new Company();
                        company.setCompanyId(companyId);
                        company.setName(companyName);
                        company.setFystart(Integer.parseInt(finStartMonthStr));

                        Branch branch = new Branch();
                        branch.setAddress(address);
                        branch.setCompanyId(company);
                        branch.setName(branchName);

                        Licenses license = new Licenses();
                        license.setActive(1);
                        license.setCompanyId(company);
                        license.setFromdate(fromDate);
                        license.setTodate(toDate);
                        license.formLicenseKey();

                        System.out.println("License key formed - " + license.getLicensekey());
                        System.out.println("License key given - " + licenseKey);
                        if (license.getLicensekey().equalsIgnoreCase(licenseKey)) {
                            CompanyFactory.insert(company);
                            BranchFactory.insert(branch);
                            LicenseFactory.insert(license);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("License is tampared. Contact Support.");
                        }
                    } else {
                        // Company is present, so update it.
                        Company company = eComp.get(0);
                        List<Licenses> licenses = LicenseFactory.findByCompanyId(company.getId());

                        Licenses newLicense = new Licenses();
                        newLicense.setActive(1);
                        newLicense.setCompanyId(company);
                        newLicense.setFromdate(fromDate);
                        newLicense.setTodate(toDate);
                        newLicense.formLicenseKey();

                        System.out.println("License key formed - " + newLicense.getLicensekey());
                        System.out.println("License key given - " + licenseKey);

                        if (newLicense.getLicensekey().equalsIgnoreCase(licenseKey)) {
                            for (Licenses lic : licenses) {
                                if (lic.getActive().compareTo(1) == 0) {
                                    lic.setActive(0);
                                    LicenseFactory.update(lic);
                                }
                            }

                            LicenseFactory.insert(newLicense);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("License is tampared. Contact Support.");
                        }
                    }
                }

                //Close the input stream
                br.close();
                in.close();
                fstream.close();
            }
        }
        System.out.println("Upload has been done successfully!");
    } catch (Exception ex) {
        System.out.println("There was an error: " + ex.getMessage());
        ex.printStackTrace();
    }

    return map.findForward("CompLicHome");
}

From source file:io.dacopancm.socketdcm.net.StreamSocket.java

public ObservableList<StreamFile> getStreamList() {
    ObservableList<StreamFile> list = FXCollections.observableArrayList();
    try {/*from  w  w  w.  ja  va2 s .  c  o m*/

        if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) {
            logger.log(Level.INFO, "get stream list call");
            sock = new Socket(ip, port);

            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            dOut.writeUTF(ConectType.STREAM.name());//send stream type
            dOut.writeUTF("uncompressed");//send comprimido o no

            dOut.writeUTF(ConectType.GET_STREAMLIST.toString()); //send type
            dOut.writeUTF("mayra");
            dOut.flush(); // Send off the data
            System.out.println("Request list send");
            String resp = dIn.readUTF();
            dOut.close();
            logger.log(Level.INFO, "resp get streamlist: {0}", resp);
            List<StreamFile> files = HelperUtil.fromJSON(resp);
            list.addAll(files);

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        logger.log(Level.INFO, "get streamlist error no connect:{0}", ex.getMessage());
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }

    }
    return list;
}

From source file:edu.cornell.med.icb.goby.counts.TestCountsReader.java

@Before
public void createCounts() throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream(100000);
    ByteArrayOutputStream indexByteArrayOutputStream = new ByteArrayOutputStream(100000);
    DataOutput indexOutput = new DataOutputStream(indexByteArrayOutputStream);
    CountsWriterI writerI = new CountsWriter(stream);
    writerI.appendCount(0, 10); // before- Position=0  count-after=0
    writerI.appendCount(1, 10); // before- Position=10
    writerI.appendCount(2, 10); // before- Position=20
    writerI.appendCount(3, 10); // before- Position=30    count-after=3
    writerI.appendCount(10, 10); // before- Position=40   count-after=10
    writerI.appendCount(11, 10); // before- Position=50   count-after=11
    writerI.appendCount(9, 10); // before- Position=60
    writerI.appendCount(7, 10); // before- Position=70
    writerI.close();//from w w w  .j  a  v  a 2s.c  o  m

    byte[] bytes = stream.toByteArray();
    CountIndexBuilder indexBuilder = new CountIndexBuilder(1);
    indexBuilder.buildIndex(bytes, indexOutput);
    byte[] bytes1 = indexByteArrayOutputStream.toByteArray();

    reader = new CountsReader(new FastByteArrayInputStream(bytes),
            new DataInputStream(new ByteArrayInputStream(bytes1)));

}