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 testPublishDSW() throws Exception {
    repositoryBase.login(singleTenantAdminUserName, defaultTenant,
            new String[] { repositoryBase.getTenantAdminRoleName(), AUTHENTICATED_ROLE_NAME });

    final String domainID = "test.xmi";
    final FileInputStream metadataFile = new FileInputStream("test-res/test.xmi");
    final boolean overwrite = true;
    final RepositoryFileAclDto acl = generateACL(USERNAME_SUZY, RepositoryFileSid.Type.USER);

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

    WebResource webResource = resource();

    ClientResponse postAnalysis = webResource.path(DATA_ACCESS_API_DATASOURCE_DSW + "import")
            .type(MediaType.MULTIPART_FORM_DATA_TYPE).put(ClientResponse.class, part);
    assertEquals(Response.Status.OK.getStatusCode(), postAnalysis.getStatus());

    final RepositoryFileAclDto savedACL = webResource.path(DATA_ACCESS_API_DATASOURCE_DSW + domainID + "/acl")
            .get(ClientResponse.class).getEntity(RepositoryFileAclDto.class);
    assertNotNull(savedACL);/*from   w  w w.j  a v  a  2 s  .com*/

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

    repositoryBase.login(USERNAME_TIFFANY, defaultTenant, new String[] { AUTHENTICATED_ROLE_NAME });
    checkDSW(webResource, domainID, false);

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

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

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

@Test
public void testPublishMetadata() 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";
    final RepositoryFileAclDto acl = generateACL(USERNAME_SUZY, RepositoryFileSid.Type.USER);

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

    WebResource webResource = resource();

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

    final RepositoryFileAclDto savedACL = webResource
            .path(DATA_ACCESS_API_DATASOURCE_METADATA + domainID + "/acl").get(ClientResponse.class)
            .getEntity(RepositoryFileAclDto.class);
    assertNotNull(savedACL);/*from  w  w  w . j  a v a 2s.co  m*/

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

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

    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(AUTHENTICATED_ROLE_NAME, RepositoryFileSid.Type.ROLE));
    assertEquals(Response.Status.OK.getStatusCode(), changeACL.getStatus());

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

From source file:com.qcloud.PicCloud.java

public ArrayList<PornDetectInfo> pornDetectFile(String[] pornFile) {
    // create sign
    long expired = System.currentTimeMillis() / 1000 + 3600 * 24;
    String sign = getProcessSign(expired);
    if (null == sign) {
        setError(-1, "create app sign failed");
        return null;
    }//from  ww  w  .j av a 2 s .co m

    HashMap<String, String> header = new HashMap<String, String>();
    header.put("Authorization", sign);
    header.put("Host", PROCESS_DOMAIN);
    HashMap<String, Object> body = new HashMap<String, Object>();
    body.put("appid", mAppId);
    body.put("bucket", mBucket);

    byte[][] data = new byte[pornFile.length][];
    for (int i = 0; i < pornFile.length; i++) {
        String fileName = pornFile[i];
        if ("".equals(fileName)) {
            setError(-1, "invalid file name");
            return null;
        }
        FileInputStream fileStream = null;
        try {
            fileStream = new FileInputStream(fileName);
        } catch (FileNotFoundException ex) {
            setError(-1, fileName + " not found");
            return null;
        }
        try {
            data[i] = new byte[fileStream.available()];
            fileStream.read(data[i]);
            fileStream.close();
        } catch (Exception ex) {
            setError(-1, "io exception, e=" + ex.toString());
            return null;
        }
    }
    String reqUrl = "http://" + PROCESS_DOMAIN + "/detection/pornDetect";
    JSONObject rspData;
    try {
        String rsp = mClient.postfiles(reqUrl, header, body, data, pornFile);
        //rspData = getResponse(rsp);
        if ("".equals(rsp)) {
            setError(-1, "empty rsp");
            return null;
        }
        rspData = new JSONObject(rsp);
    } catch (Exception e) {
        setError(-1, "url exception, e=" + e.toString());
        return null;
    }
    if (!rspData.has("result_list")) {
        System.out.println("code = " + rspData.getInt("code"));
        System.out.println("message = " + rspData.getString("message"));
        if (rspData.has("data")) {
            System.out.println("data = " + rspData.getString("data"));
        }
        return null;
    }

    ArrayList<PornDetectInfo> info = new ArrayList<PornDetectInfo>();
    try {
        JSONArray rl;
        rl = rspData.getJSONArray("result_list");

        for (int i = 0; i < rl.length(); i++) {
            PornDetectInfo tmpinfo = new PornDetectInfo();
            JSONObject res = rl.getJSONObject(i);
            tmpinfo.code = res.getInt("code");
            tmpinfo.message = res.getString("message");
            tmpinfo.name = res.getString("filename");
            if (res.has("data")) {
                JSONObject resData = res.getJSONObject("data");
                tmpinfo.data.result = resData.getInt("result");
                tmpinfo.data.confidence = resData.getDouble("confidence");
                tmpinfo.data.pornScore = resData.getDouble("porn_score");
                tmpinfo.data.normalScore = resData.getDouble("normal_score");
                tmpinfo.data.hotScore = resData.getDouble("hot_score");
                tmpinfo.data.forbidStatus = resData.getInt("forbid_status");
            }
            info.add(tmpinfo);
        }
    } catch (JSONException e) {
        setError(-2, "json exception, e=" + e.toString());
        return null;
    }
    setError(0, "success");
    return info;
}

From source file:com.linkedin.helix.store.file.FilePropertyStore.java

@Override
public T getProperty(String key, PropertyStat propertyStat) throws PropertyStoreException {

    String path = getPath(key);//from  w w w .j a  v  a2s  . co m
    File file = null;
    // FileLock fLock = null;
    FileInputStream fin = null;

    try {
        // TODO need a timeout on lock operation
        _readWriteLock.readLock().lock();

        file = new File(path);
        if (!file.exists()) {
            return null;
        }

        fin = new FileInputStream(file);
        // FileChannel fChannel = fin.getChannel();
        // fLock = fChannel.lock(0L, Long.MAX_VALUE, true);

        int availableBytes = fin.available();
        if (availableBytes == 0) {
            return null;
        }

        byte[] bytes = new byte[availableBytes];
        fin.read(bytes);

        if (propertyStat != null) {
            propertyStat.setLastModifiedTime(file.lastModified());
        }

        return _serializer.deserialize(bytes);
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        logger.error("fail to get property. key:" + key, e);
    } finally {
        _readWriteLock.readLock().unlock();
        try {
            // if (fLock != null && fLock.isValid())
            //   fLock.release();
            if (fin != null) {
                fin.close();
            }
        } catch (IOException e) {
            logger.error("fail to close file. key:" + key, e);
        }

    }

    return null;
}

From source file:Leitura.Jxr.java

public ArrayList<DadosTeste> leTxt(String classe, String path, FileInputStream reader) throws IOException {
    StringBuffer sbaux = new StringBuffer();
    char corrente;
    int bloco = 0;
    char[] aux;//from  w  w w .  java 2s .  c o  m
    boolean met = false;
    boolean obj = false;
    boolean cod = false;
    boolean ponto = false;
    boolean bClasse = false;
    boolean achei = false;
    boolean statment = false;
    boolean clas = false;
    ArrayList<String> object = new ArrayList<String>();
    ArrayList<String> mChamado = new ArrayList<String>();
    ArrayList<DadosTeste> dados = new ArrayList<>();
    String metodoTeste = null;
    String classeTeste = null;
    String classeObj = null;
    String objeto = null;
    String auxiliar = null;
    DadosTeste dadosTeste = null;

    // System.out.println(reader.available()+"->"+classe);
    while (reader.available() > 0) {
        corrente = (char) reader.read();
        if ((corrente == '\t') || (corrente == '\r')) {
            continue;
        }

        sbaux.append(corrente);
        // verifica abertura de blocos

        if (corrente != '=') {
            auxiliar = sbaux.toString(); // guarda o nome do objeto
        }

        if ((corrente == ' ') && (auxiliar.equals("do") || auxiliar.equals("if") || auxiliar.equals("else")
                || auxiliar.equals("for") || auxiliar.equals("while") || auxiliar.equals("switch")
                || auxiliar.equals("try") || auxiliar.equals("catch"))) {
            statment = true;

        }

        if ((corrente == '{') && (statment == false)) {
            bloco++;
        }

        if ((corrente == '}') && (statment == false)) {
            bloco--;
        } else if ((corrente == '}') && (statment == true)) {
            statment = false;
        }

        //ler os caracteres at formar uma palavra reservada do java
        if ((sbaux.toString().equals("public")) || (sbaux.toString().equals("protected"))
                || (sbaux.toString().equals("private")) || (sbaux.toString().equals("static"))
                || (sbaux.toString().equals("final")) || (sbaux.toString().equals("native"))
                || (sbaux.toString().equals("synchronized")) || (sbaux.toString().equals("abstract"))
                || (sbaux.toString().equals("threadsafe")) || (sbaux.toString().equals("transient"))) {
            met = true; // encontrei palavra reservada
            sbaux.delete(0, sbaux.length());
        }

        if (sbaux.toString().equals("class ") && classeTeste == null) {
            met = false;
            clas = true;
            sbaux.delete(0, sbaux.length());
        }
        if (clas == true && !auxiliar.toString().equals("class ") && corrente == ' ') {
            classeTeste = sbaux.toString();
            clas = false;
            sbaux.delete(0, sbaux.length());
        }

        //verificar se a palavra reservada eh de um mtodo
        if (met == true && corrente == '.') {
            met = false;

            sbaux.delete(0, sbaux.length());
        }
        if (auxiliar.equals("new")) {
            met = false;
        }
        if (met == true && ((corrente == ')') || (corrente == '='))) {
            met = false;
        }
        if ((met == true) && ((corrente == ' ') || (corrente == '('))) {

            aux = sbaux.toString().toCharArray(); // verifica se eh um metoo ou declarao de varivel
            for (int i = 0; i < aux.length; i++) {
                if (aux[i] == '(') {
                    sbaux.deleteCharAt(i);
                    metodoTeste = sbaux.toString(); //encontrei metodo do teste
                    sbaux.delete(0, sbaux.length());
                    met = false;
                    //System.out.println("metodo ->" + metodoTeste);
                    break;
                }
            }
        }
        if (sbaux.toString().equals(classe + " ")) {
            bClasse = true;
        }

        if ((corrente == '{') && (bClasse == true)) {
            bClasse = false;
            obj = false;
        }

        if ((bClasse == true) && (corrente == ' ')) {
            classeObj = classe;
            //System.out.println(classeObj);
            bClasse = false;
            obj = true; // encontrou um objeto
            sbaux.delete(0, sbaux.length());
        }
        if ((corrente == '(') || (corrente == '.') || (corrente == ')')) {
            obj = false; // torna obj falso para no pegar a instanciao do objeto ex: Calculadora calc = new Calculadora()
        }

        if ((obj == true) && ((corrente == '=') || (corrente == ';'))) {
            objeto = auxiliar.replace(';', ' ').trim();
            object.add(objeto);
            obj = false;
            //System.out.println(object);
        }

        // verifica os mtodos do cdigo
        for (int i = 0; i < object.size(); i++) {
            if ((sbaux.toString()).equals(object.get(i))) {
                cod = true; // verifica se encontrou um objeto
            }
        }

        if ((corrente == '.') && (cod == true)) {
            ponto = true; // verifica se o objeto vai chamar um metodo
            sbaux.delete(0, sbaux.length());
        }
        if ((cod == true) && (ponto == true)) {
            if ((corrente == '(') || (corrente == ' ')) {
                if (sbaux.length() != 0) {
                    sbaux.deleteCharAt(sbaux.length() - 1);
                    for (int i = 0; i < mChamado.size(); i++) {
                        if (mChamado.get(i).equals(sbaux.toString()))
                            achei = true;
                    }
                    if (achei != true) {
                        mChamado.add(sbaux.toString()); // metodo do codigo encontrado
                        achei = false;
                    }
                }
                cod = false;
                ponto = false;

            }
        }

        if (StringUtils.isNotBlank(metodoTeste) && StringUtils.isNotBlank(classeObj) && !object.isEmpty()
                && !mChamado.isEmpty() && (bloco % 2 != 0)) {
            // System.out.println("ClasseOBj: "+classeObj+" Objeto: "+object+" MChamado: "+mChamado+" Metodo Teste:"+metodoTeste+" ClasseTeste: "+classeTeste);
            dadosTeste = new DadosTeste(classeObj, object, mChamado, metodoTeste, classeTeste.trim());
            //infJxr.put(metodoTeste + "_" + classeObj, dadosTeste);
            dados.add(dadosTeste);
            classeObj = null;
            object = new ArrayList<>();
            mChamado = new ArrayList<>();
            metodoTeste = null;
            objeto = null;

            met = false;
            obj = false;
            cod = false;
            ponto = false;
            bClasse = false;
            achei = false;
        }
        if ((corrente == '\n') || (corrente == ' ') || (corrente == ',') || auxiliar.equals("")
                || (corrente == '(')) {
            sbaux.delete(0, sbaux.length());
        }
    }

    clas = false;
    classeTeste = null;
    return dados;
}

From source file:org.red5.server.persistence.FilePersistence.java

/**
 * Load resource with given name and attaches to persistable object
 * @param name             Resource name
 * @param object           Object to attach to
 * @return                 Persistable object
 *///from   www  .j av  a 2  s .  c om
private IPersistable doLoad(String name, IPersistable object) {
    IPersistable result = object;
    Resource data = resources.getResource(name);
    if (data == null || !data.exists()) {
        // No such file
        return null;
    }

    FileInputStream input;
    String filename;
    try {
        File fp = data.getFile();
        if (fp.length() == 0) {
            // File is empty
            log.error("The file at " + data.getFilename() + " is empty.");
            return null;
        }

        filename = fp.getAbsolutePath();
        input = new FileInputStream(filename);
    } catch (FileNotFoundException e) {
        log.error("The file at " + data.getFilename() + " does not exist.");
        return null;
    } catch (IOException e) {
        log.error("Could not load file from " + data.getFilename() + '.', e);
        return null;
    }

    try {
        ByteBuffer buf = ByteBuffer.allocate(input.available());
        try {
            ServletUtils.copy(input, buf.asOutputStream());
            buf.flip();
            Input in = new Input(buf);
            Deserializer deserializer = new Deserializer();
            String className = (String) deserializer.deserialize(in);
            if (result == null) {
                // We need to create the object first
                try {
                    Class theClass = Class.forName(className);
                    Constructor constructor = null;
                    try {
                        // Try to create object by calling constructor with Input stream as
                        // parameter.
                        for (Class interfaceClass : in.getClass().getInterfaces()) {
                            constructor = theClass.getConstructor(new Class[] { interfaceClass });
                            if (constructor != null) {
                                break;
                            }
                        }
                        if (constructor == null) {
                            throw new NoSuchMethodException();
                        }

                        result = (IPersistable) constructor.newInstance(in);
                    } catch (NoSuchMethodException err) {
                        // No valid constructor found, use empty
                        // constructor.
                        result = (IPersistable) theClass.newInstance();
                        result.deserialize(in);
                    } catch (InvocationTargetException err) {
                        // Error while invoking found constructor, use empty
                        // constructor.
                        result = (IPersistable) theClass.newInstance();
                        result.deserialize(in);
                    }
                } catch (ClassNotFoundException cnfe) {
                    log.error("Unknown class " + className);
                    return null;
                } catch (IllegalAccessException iae) {
                    log.error("Illegal access.", iae);
                    return null;
                } catch (InstantiationException ie) {
                    log.error("Could not instantiate class " + className);
                    return null;
                }

                // Set object's properties
                result.setName(getObjectName(name));
                result.setPath(getObjectPath(name, result.getName()));
            } else {
                // Initialize existing object
                String resultClass = result.getClass().getName();
                if (!resultClass.equals(className)) {
                    log.error("The classes differ: " + resultClass + " != " + className);
                    return null;
                }

                result.deserialize(in);
            }
        } finally {
            buf.release();
            buf = null;
        }
        if (result.getStore() != this) {
            result.setStore(this);
        }
        super.save(result);
        if (log.isDebugEnabled()) {
            log.debug("Loaded persistent object " + result + " from " + filename);
        }
    } catch (IOException e) {
        log.error("Could not load file at " + filename);
        return null;
    }

    return result;
}

From source file:org.mobile.mpos.action.manager.BannerController.java

@RequestMapping(value = Mapping.INTERFACE_URL_DOWNLOADBANNER)
public void downloadBanner(HttpServletRequest request, HttpServletResponse response) {
    FileInputStream fis = null;
    File file = managerService.downloadImg(request, response);
    try {// ww  w .  j ava2  s.c  om
        if (file == null || !file.exists()) {
            response.setContentType("application/json;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("isSuccess", false);
            result.put("respTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            result.put("respCode", "FILE_NOT_EXIST");
            result.put("respMsg", "?:" + request.getParameter("fileName"));
            log.info("file not exist,return :" + JSONObject.fromObject(result).toString(4));
            out.write(JSONObject.fromObject(result).toString().getBytes("UTF-8"));
            out.flush();
        } else {
            log.info("return image:" + file.getAbsolutePath());
            response.setContentType("image/jpeg");
            OutputStream out = response.getOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        }
    } catch (IOException e) {
        log.error("exception:" + e.getMessage(), e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException e) {
            log.error("exception:" + e.getMessage(), e);
        }
    }
}

From source file:com.pari.nm.utils.backup.BackupRestore.java

private void copyFile(FileInputStream fin, FileOutputStream fout) throws Exception {
    byte[] inbuf = new byte[2048];

    do {/*ww  w. ja  v  a2 s  . c  o m*/
        int nCount = fin.read(inbuf);

        if (nCount > 0) {
            fout.write(inbuf, 0, nCount);
        }
    } while (fin.available() > 0);
}

From source file:net.sf.firemox.DeckBuilder.java

/**
 * Read available cards from file and add them to the specified
 * <code>cardNames</code>//w  w  w  .ja  va2s  .  c  o  m
 * 
 * @param cardNames
 *          to this list method add card names
 */
protected void readAvailableCards(MListModel<MCardCompare> cardNames) {
    final FileInputStream dbStream = MdbLoader.resetMdb();
    listScrollerLeft.setVisible(false);
    try {
        cardNames.clear();
        while (dbStream.available() > 2) {
            // reads card name
            final String cardName = MToolKit.readString(dbStream);

            // reads card offset
            final long offset = MToolKit.readInt24(dbStream);
            final MCardCompare cardCompare = new MCardCompare(cardName, offset);
            cardNames.add(cardCompare);
        }
    } catch (IOException ex2) {
        // Ignore this error
        ex2.printStackTrace();
    } finally {
        listScrollerLeft.setVisible(true);
        cardNames.refresh();
    }
}

From source file:DataAn.reportManager.service.impl.ReportServiceImpl.java

private List<Map<String, Object>> getImgTab(List<ParamImgDataDto> paramImgDatas, String parName, String parImg)
        throws Exception {
    List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
    if (paramImgDatas != null && paramImgDatas.size() > 0) {
        byte[] image = null;
        for (ParamImgDataDto param : paramImgDatas) {
            if (StringUtils.isNotBlank(parImg) && StringUtils.isNotBlank(param.getParImg())) {
                FileInputStream fis = new FileInputStream(param.getParImg());
                image = new byte[fis.available()];
                fis.read(image);/*w ww.  ja v  a  2 s . c  om*/
                fis.close();
            }
            Map<String, Object> record = new HashMap<String, Object>();
            record.put(parName, param.getParName());
            record.put(parImg, image);
            dataList.add(record);
        }
    }
    return dataList;
}