Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:org.pentaho.platform.dataaccess.datasource.DataSourcePublishACLTest.java

@Test
public void testMetadata_ACL() throws Exception {
    repositoryBase.login(singleTenantAdminUserName, defaultTenant,
            new String[] { repositoryBase.getTenantAdminRoleName(), AUTHENTICATED_ROLE_NAME });

    final String domainID = "domainID";
    final FileInputStream metadataFile = new FileInputStream("test-res/Sample_SQL_Query.xmi");
    final String overwrite = "true";

    MultiPart part = new FormDataMultiPart().field("domainId", domainID)
            .field("overwrite", String.valueOf(overwrite)).bodyPart(
                    new FormDataBodyPart(
                            FormDataContentDisposition.name("metadataFile").fileName("Sample_SQL_Query.xmi")
                                    .size(metadataFile.available()).build(),
                            metadataFile, MediaType.TEXT_XML_TYPE));

    WebResource webResource = resource();

    final ClientResponse noMetadata = webResource.path(DATA_ACCESS_API_DATASOURCE_METADATA + domainID + "/acl")
            .get(ClientResponse.class);
    assertEquals(Response.Status.CONFLICT.getStatusCode(), noMetadata.getStatus());

    ClientResponse postAnalysis = webResource.path("data-access/api/metadata/import")
            .type(MediaType.MULTIPART_FORM_DATA_TYPE).put(ClientResponse.class, part);
    assertEquals(3, postAnalysis.getStatus());

    final ClientResponse noACL = webResource.path(DATA_ACCESS_API_DATASOURCE_METADATA + domainID + "/acl")
            .get(ClientResponse.class);
    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), noACL.getStatus());

    repositoryBase.login(USERNAME_SUZY, defaultTenant, new String[] { AUTHENTICATED_ROLE_NAME });
    checkMetadata(webResource, domainID, true);

    repositoryBase.login(singleTenantAdminUserName, defaultTenant,
            new String[] { repositoryBase.getTenantAdminRoleName(), AUTHENTICATED_ROLE_NAME });
    final ClientResponse changeACL = webResource.path(DATA_ACCESS_API_DATASOURCE_METADATA + domainID + "/acl")
            .put(ClientResponse.class, generateACL(USERNAME_SUZY, RepositoryFileSid.Type.USER));
    assertEquals(Response.Status.OK.getStatusCode(), changeACL.getStatus());

    repositoryBase.login(USERNAME_SUZY, defaultTenant, new String[] { AUTHENTICATED_ROLE_NAME });
    checkMetadata(webResource, domainID, true);

    final ClientResponse noAccessACL = webResource.path(DATA_ACCESS_API_DATASOURCE_METADATA + domainID + "/acl")
            .get(ClientResponse.class);
    assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), noAccessACL.getStatus());

    final ClientResponse noAccessACLNoDS = webResource
            .path(DATA_ACCESS_API_DATASOURCE_METADATA + domainID + "_not_exist/acl").get(ClientResponse.class);
    assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), noAccessACLNoDS.getStatus());
}

From source file:net.potterpcs.recipebook.RecipeData.java

public ArrayList<Recipe> importRecipes(String path) throws IOException {
    File f = new File(URI.create(path));
    FileInputStream fis = new FileInputStream(f);
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);//from   w  w  w. j av  a  2  s  . c om
    String st = new String(buffer);
    return parseJsonRecipes(st);
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.metroE.IntegrationTestsMetroE.java

@Test
public void testM38_deviceData() {
    Map<String, String> resourceParams = new HashMap<String, String>();
    //        Resource resource = new Resource("R1", "10.17.1.13", resourceParams);
    //        resource.setDeviceType("CISCO");

    FileInputStream is = null;
    try {/*from w w w .  j  a v  a  2  s .  c o  m*/
        is = new FileInputStream(
                "iDiscover/netDiscoverer/src/test/resources/raw-data-metroE/raw-data-M-238.xml");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    byte[] data = null;
    try {
        data = new byte[is.available()];
        is.read(data);

    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    rawDeviceData.setData(data);
    DiscoveryHelper discoveryHelper = discoveryHelperFactory.createDiscoveryHelper("CISCO");
    resourceParams.put("neighbourIPDryRun", "true");

    DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawDeviceData,
            discoveryTypes, resourceParams);
    Map<String, HashMap<String, String>> discoveredDevices = new HashMap<String, HashMap<String, String>>();
    OutputStream os = null;
    try {
        os = new FileOutputStream("iDiscover/netDiscoverer/src/test/resources/test-device-data-M-238.xml");
        JaxbMarshalar.marshal(discoveredDeviceData, os, "DiscoveredDevice");
    } catch (FileNotFoundException e) {
    } catch (JAXBException e) {
        e.printStackTrace();
        Assert.fail();

    } finally {
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
                Assert.fail();

            }
    }
    try {
        String deviceDataGenerated = FileUtils.readFileToString(new File(
                "iDiscover/netDiscoverer/src/test/resources/device-data-metro-E/test-device-data-M-238.xml"));
        String expected = FileUtils.readFileToString(new File(
                "iDiscover/netDiscoverer/src/test/resources/device-data-metro-E/device-data-M-238.xml"));
        Assert.assertEquals(expected, deviceDataGenerated);
    } catch (IOException e) {
        e.printStackTrace();
        Assert.fail();
    }

}

From source file:org.talend.mdm.repository.utils.RepositoryResourceUtilTest.java

@Test
public void testGetTextFileContent() throws Exception {
    String encode = "UTF-8";
    String filePath = "testfile.txt";//

    IFile mockFile = mock(IFile.class);
    IPath mockPath = mock(IPath.class);
    when(mockFile.getLocation()).thenReturn(mockPath);
    when(mockFile.getLocation().toOSString()).thenReturn(filePath);
    when(mockFile.exists()).thenReturn(true);

    File file = mock(File.class);
    when(file.exists()).thenReturn(true);
    PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(file);
    PowerMockito.doNothing().when(mockFile).refreshLocal(0, null);

    String textContent = "this is the test content!";
    byte[] buf = textContent.getBytes(encode);
    FileInputStream mockFileInputStream = PowerMockito.mock(FileInputStream.class);
    PowerMockito.whenNew(FileInputStream.class).withArguments(file).thenReturn(mockFileInputStream);
    PowerMockito.when(mockFileInputStream.available()).thenReturn(0);

    ByteArrayOutputStream spyOutputStream = Mockito.spy(new ByteArrayOutputStream());
    PowerMockito.whenNew(ByteArrayOutputStream.class).withNoArguments().thenReturn(spyOutputStream);
    spyOutputStream.write(buf);//from  ww  w  .j av a2 s.co  m

    String content = RepositoryResourceUtil.getTextFileContent(mockFile, encode);
    assertEquals(textContent, content);

    verify(mockFileInputStream, Mockito.atLeastOnce()).read(Matchers.<byte[]>any());
    verify(mockFileInputStream, Mockito.atLeastOnce()).close();
    verify(spyOutputStream, Mockito.atLeastOnce()).close();
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.metroE.IntegrationTestsMetroE.java

@Test
public void testM38() {
    Map<String, String> resourceParams = new HashMap<String, String>();
    //        Resource resource = new Resource("R1", "10.17.1.13", resourceParams);
    //        resource.setDeviceType("CISCO");

    FileInputStream is = null;
    try {/*from  w  ww  . jav a2 s.c om*/
        is = new FileInputStream(
                "iDiscover/netDiscoverer/src/test/resources/raw-data-metroE/raw-data-M-238.xml");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Assert.fail();

    }
    byte[] data = null;
    try {
        data = new byte[is.available()];
        is.read(data);

    } catch (IOException e) {
        e.printStackTrace();
        Assert.fail();

    }

    rawDeviceData.setData(data);
    DiscoveryHelper discoveryHelper = discoveryHelperFactory.createDiscoveryHelper("CISCO");
    resourceParams.put("neighbourIPDryRun", "true");

    DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawDeviceData,
            discoveryTypes, resourceParams);
    Map<String, HashMap<String, String>> discoveredDevices = new HashMap<String, HashMap<String, String>>();

    SnmpForXslt.setDiscoveredIPs(discoveredDevices);

    resourceParams.put("neighbourIPDryRun", "false");
    discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawDeviceData, discoveryTypes, resourceParams);
    Map<String, Integer> neighbourTypeCounts = fillInNeighbourTree(discoveredDeviceData.getObject());
    Assert.assertEquals((Object) 2, neighbourTypeCounts.get("CDP"));
    Assert.assertEquals((Object) 1, neighbourTypeCounts.get("MAC"));
    Assert.assertEquals((Object) 3, neighbourTypeCounts.get("UNKNOWN"));

}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * upload multipart/* w  w  w  .j a va  2 s  .  com*/
 * this method receive the file to be uploaded
 * */
@SuppressWarnings("deprecation")
public String uploadMultiPart(Map<String, File> files) throws Exception {
    disableSSLCertificateChecking();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    try {
        URL endpoint = new URL(url);
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        String post = "";

        //WRITE ALL THE PARAMS
        for (NameValuePair p : params)
            post += writeMultipartParam(p);
        dos.flush();
        //END WRITE ALL THE PARAMS

        //BEGIN THE UPLOAD
        ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>();
        for (Entry<String, File> entry : files.entrySet()) {
            post += lineEnd;
            post += twoHyphens + boundary + lineEnd;
            String NameParamImage = entry.getKey();
            File file = entry.getValue();
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            FileInputStream fileInputStream = new FileInputStream(file);

            post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\""
                    + file.getName() + "\"" + lineEnd;
            String mimetype = getMimeType(file.getName());
            post += "Content-Type: " + mimetype + lineEnd;
            post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

            dos.write(post.toString().getBytes("UTF-8"));

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                inputStreams.add(fileInputStream);
            }

            Log.d("Test", post);
            dos.flush();
            post = "";
        }

        //END THE UPLOAD

        dos.writeBytes(lineEnd);

        dos.writeBytes(twoHyphens + boundary + twoHyphens);
        //            for(FileInputStream inputStream: inputStreams){
        //               inputStream.close();
        //            }
        dos.flush();
        dos.close();
        conn.connect();
        Log.d("upload", "finish flush:" + conn.getResponseCode());
    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
        String response_data = "";
        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            response_data += str;
        }
        inStream.close();
        return response_data;
    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
    return null;
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.metroE.IntegrationTestsMetroE.java

@Test
public void testR112() {

    Map<String, String> resourceParams = new HashMap<String, String>();
    //        Resource resource = new Resource("R1", "10.17.1.13", resourceParams);
    //        resource.setDeviceType("CISCO");

    FileInputStream is = null;
    try {//from  w  w  w  .  j  av a  2s.  c  o  m
        is = new FileInputStream(
                "iDiscover/netDiscoverer/src/test/resources/raw-data-metroE/raw-data-R-112.xml");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    byte[] data = null;
    try {
        data = new byte[is.available()];
        is.read(data);

    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    rawDeviceData.setData(data);
    DiscoveryHelper discoveryHelper = discoveryHelperFactory.createDiscoveryHelper("CISCO");
    resourceParams.put("neighbourIPDryRun", "true");

    DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawDeviceData,
            discoveryTypes, resourceParams);

    Map<String, HashMap<String, String>> discoveredDevices = new HashMap<String, HashMap<String, String>>();
    HashMap<String, String> s11218 = new HashMap<String, String>();
    s11218.put("snmp", "S-112-18");
    s11218.put("deviceType", "CISCO");
    discoveredDevices.put("10.32.249.87", s11218);

    HashMap<String, String> s11227 = new HashMap<String, String>();
    s11227.put("snmp", "S-112-27");
    s11227.put("deviceType", "CISCO");
    discoveredDevices.put("10.32.249.119", s11227);

    HashMap<String, String> s1120 = new HashMap<String, String>();
    s1120.put("snmp", "S-112-0");
    s1120.put("deviceType", "CISCO");
    discoveredDevices.put("10.32.250.51", s1120);
    // S-112-3
    HashMap<String, String> s1123 = new HashMap<String, String>();
    s1123.put("snmp", "S-112-3");
    s1123.put("deviceType", "CISCO");
    discoveredDevices.put("10.32.250.56", s1123);
    //M-321
    HashMap<String, String> m321 = new HashMap<String, String>();
    m321.put("snmp", "M-321");
    m321.put("deviceType", "CISCO");
    discoveredDevices.put("10.32.219.53", m321);
    //172.16.2.98
    HashMap<String, String> n17216298 = new HashMap<String, String>();
    n17216298.put("snmp", "");
    n17216298.put("deviceType", "UNKNOWN");
    discoveredDevices.put("172.16.2.98", n17216298);
    //212.248.1.126

    //SnmpForXslt.resolveIPAddresses(discoveryResource,);
    SnmpForXslt.setDiscoveredIPs(discoveredDevices);

    resourceParams.put("neighbourIPDryRun", "false");

    OutputStream os = null;

    discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawDeviceData, discoveryTypes, resourceParams);

    try {
        os = new ByteArrayOutputStream();
        JaxbMarshalar.marshal(discoveredDeviceData, os, "DiscoveredDevice");
        String str = os.toString();
        System.out.println(str);
    } catch (JAXBException e) {
        e.printStackTrace();
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
            }
    }

    Map<String, Integer> neighbourTypeCounts = fillInNeighbourTree(discoveredDeviceData.getObject());
    System.out.println(neighbourTypeCounts);
    //Assert.assertEquals((Object) 53,neighbourTypeCounts.get("c_OSPF"));
    Assert.assertEquals((Object) 7, neighbourTypeCounts.get("CDP"));
    Assert.assertEquals((Object) 6, neighbourTypeCounts.get("Slash30"));
    Assert.assertEquals((Object) 7, neighbourTypeCounts.get("c_OSPF"));
    Assert.assertEquals((Object) 1, neighbourTypeCounts.get("Slash31"));
    Assert.assertEquals((Object) 16, neighbourTypeCounts.get("UNKNOWN"));
    Assert.assertEquals((Object) 5, neighbourTypeCounts.get("CISCO"));

}

From source file:org.pluroid.pluroium.PlurkHelper.java

private void writeFileField(ByteArrayOutputStream baos, String fieldName, String fileName, String contentType,
        FileInputStream fis) throws IOException {

    baos.write((twoHyphens + boundary + CRLF).getBytes());
    baos.write(//from w ww.java2  s  .c  o  m
            ("Content-Disposition: form-data;name=\"" + fieldName + "\";filename=\"" + fileName + "\"" + CRLF)
                    .getBytes("UTF-8"));

    baos.write(("Content-Type: " + contentType + CRLF + CRLF).getBytes());

    int ba = fis.available();
    int maxSize = 8192;
    int bufSize = Math.min(ba, maxSize);
    byte[] buf = new byte[bufSize];

    while (fis.read(buf, 0, bufSize) > 0) {
        baos.write(buf);
        ba = fis.available();
        bufSize = Math.min(ba, maxSize);
    }

    baos.write(CRLF.getBytes());
}

From source file:org.wso2.iot.agent.services.FileUploadService.java

/**
 * This method is used to upload the using HTTP client , this supports BASIC authentication,
 * if user name is provided./*from   www.j a  v  a 2 s  .c o m*/
 *
 * @param operation    - Operation object
 * @param uploadURL    - HTTP POST endpoint url
 * @param userName     - username (can be empty)
 * @param password     - password (can be empty)
 * @param fileLocation - local location of the file in device
 * @throws AndroidAgentException - Android agent exception
 */
private void uploadFileUsingHTTPClient(Operation operation, String uploadURL, final String userName,
        final String password, String fileLocation) throws AndroidAgentException {

    int serverResponseCode;
    HttpURLConnection connection = null;
    DataOutputStream dataOutputStream = null;
    final String lineEnd = "\r\n";
    final String twoHyphens = "--";
    final String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1024 * 1024; // 1 MB
    File selectedFile = new File(fileLocation);
    final String fileName = selectedFile.getName();
    FileInputStream fileInputStream = null;

    try {
        fileInputStream = new FileInputStream(selectedFile);
        URL url = new URL(uploadURL);
        connection = getHttpConnection(url, userName, password);
        connection.setRequestProperty("uploaded_file", fileLocation);

        dataOutputStream = new DataOutputStream(connection.getOutputStream());
        dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
        dataOutputStream.writeBytes(
                "Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);
        dataOutputStream.writeBytes(lineEnd);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        //loop repeats till bytesRead = -1, i.e., no bytes are left to read
        while (bytesRead > 0) {
            //write the bytes read from inputStream
            dataOutputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        serverResponseCode = connection.getResponseCode();
        if (Constants.DEBUG_MODE_ENABLED) {
            Log.d(TAG, "Server Response is: " + connection.getResponseMessage() + ": " + serverResponseCode);
        }
        if (serverResponseCode == 200) {
            operation.setStatus(resources.getString(R.string.operation_value_completed));
            operation.setOperationResponse("File uploaded from the device completed ( " + fileName + " ).");
        }
    } catch (IOException e) {
        handleOperationError(operation, fileTransferExceptionCause(e, fileName), e, resources);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        cleanupStreams(null, null, fileInputStream, null, null, null, null, dataOutputStream);
    }
}