Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system,
        SecurityService securityService) throws GemFireSecurityException, IOException {

    boolean requireAuthentication = securityService.isClientSecurityRequired();
    Properties credentials = null;
    try {/*from w w w.j a  v a  2  s.  c  om*/
        byte secureMode = dis.readByte();
        throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
        if (secureMode == CREDENTIALS_NORMAL) {
            if (requireAuthentication) {
                credentials = DataSerializer.readProperties(dis);
            } else {
                DataSerializer.readProperties(dis); // ignore the credentials
            }
        } else if (secureMode == CREDENTIALS_DHENCRYPT) {
            boolean sendAuthentication = dis.readBoolean();
            InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
            // Get the symmetric encryption algorithm to be used
            String skAlgo = DataSerializer.readString(dis);
            // Get the public key of the other side
            byte[] keyBytes = DataSerializer.readByteArray(dis);
            byte[] challenge = null;
            PublicKey pubKey = null;
            if (requireAuthentication) {
                // Generate PublicKey from encoded form
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFact = KeyFactory.getInstance("DH");
                pubKey = keyFact.generatePublic(x509KeySpec);

                // Send the public key to other side
                keyBytes = dhPublicKey.getEncoded();
                challenge = new byte[64];
                random.nextBytes(challenge);

                // If the server has to also authenticate itself then
                // sign the challenge from client.
                if (sendAuthentication) {
                    // Get the challenge string from client
                    byte[] clientChallenge = DataSerializer.readByteArray(dis);
                    if (privateKeyEncrypt == null) {
                        throw new AuthenticationFailedException(
                                LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE
                                        .toLocalizedString());
                    }
                    // Sign the challenge from client and send it to the client
                    Signature sig = Signature.getInstance(privateKeySignAlgo);
                    sig.initSign(privateKeyEncrypt);
                    sig.update(clientChallenge);
                    byte[] signedBytes = sig.sign();
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                    // DataSerializer.writeString(privateKeyAlias, dos);
                    DataSerializer.writeString(privateKeySubject, dos);
                    DataSerializer.writeByteArray(signedBytes, dos);
                    securityLogWriter.fine("HandShake: sent the signed client challenge");
                } else {
                    // These two lines should not be moved before the if{} statement in
                    // a common block for both if...then...else parts. This is to handle
                    // the case when an AuthenticationFailedException is thrown by the
                    // if...then part when sending the signature.
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                }
                // Now send the server challenge
                DataSerializer.writeByteArray(challenge, dos);
                securityLogWriter.fine("HandShake: sent the public key and challenge");
                dos.flush();

                // Read and decrypt the credentials
                byte[] encBytes = DataSerializer.readByteArray(dis);
                KeyAgreement ka = KeyAgreement.getInstance("DH");
                ka.init(dhPrivateKey);
                ka.doPhase(pubKey, true);

                Cipher decrypt;

                int keysize = getKeySize(skAlgo);
                int blocksize = getBlockSize(skAlgo);

                if (keysize == -1 || blocksize == -1) {
                    SecretKey sKey = ka.generateSecret(skAlgo);
                    decrypt = Cipher.getInstance(skAlgo);
                    decrypt.init(Cipher.DECRYPT_MODE, sKey);
                } else {
                    String algoStr = getDhAlgoStr(skAlgo);

                    byte[] sKeyBytes = ka.generateSecret();
                    SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
                    IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);

                    decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
                    decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
                }

                byte[] credentialBytes = decrypt.doFinal(encBytes);
                ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
                DataInputStream dinp = new DataInputStream(bis);
                credentials = DataSerializer.readProperties(dinp);
                byte[] challengeRes = DataSerializer.readByteArray(dinp);
                // Check the challenge string
                if (!Arrays.equals(challenge, challengeRes)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT
                                    .toLocalizedString());
                }
                dinp.close();
            } else {
                if (sendAuthentication) {
                    // Read and ignore the client challenge
                    DataSerializer.readByteArray(dis);
                }
                dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
                dos.flush();
            }
        } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) {
            // hitesh there will be no credential CCP will get credential(Principal) using
            // ServerConnection..
            logger.debug("readCredential where multiuser mode creating callback connection");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException(
                LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
    }
    return credentials;
}

From source file:org.apache.hadoop.mapred.TestShuffleHandler.java

/**
 * Validate the ownership of the map-output files being pulled in. The
 * local-file-system owner of the file should match the user component in the
 *
 * @throws Exception exception/* w ww .  j a v a  2 s .  co  m*/
 */
@Test(timeout = 100000)
public void testMapFileAccess() throws IOException {
    // This will run only in NativeIO is enabled as SecureIOUtils need it
    assumeTrue(NativeIO.isAvailable());
    Configuration conf = new Configuration();
    conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
    conf.setInt(ShuffleHandler.MAX_SHUFFLE_CONNECTIONS, 3);
    conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    UserGroupInformation.setConfiguration(conf);
    File absLogDir = new File("target", TestShuffleHandler.class.getSimpleName() + "LocDir").getAbsoluteFile();
    conf.set(YarnConfiguration.NM_LOCAL_DIRS, absLogDir.getAbsolutePath());
    ApplicationId appId = ApplicationId.newInstance(12345, 1);
    LOG.info(appId.toString());
    String appAttemptId = "attempt_12345_1_m_1_0";
    String user = "randomUser";
    String userFolder = "randomUserFolder";
    String reducerId = "0";
    List<File> fileMap = new ArrayList<File>();
    createShuffleHandlerFiles(absLogDir, userFolder, appId.toString(), appAttemptId, conf, fileMap);
    ShuffleHandler shuffleHandler = new ShuffleHandler() {

        @Override
        protected Shuffle getShuffle(Configuration conf) {
            // replace the shuffle handler with one stubbed for testing
            return new Shuffle(conf) {

                @Override
                protected void verifyRequest(String appid, ChannelHandlerContext ctx, HttpRequest request,
                        HttpResponse response, URL requestUri) throws IOException {
                    // Do nothing.
                }

            };
        }
    };
    shuffleHandler.init(conf);
    try {
        shuffleHandler.start();
        DataOutputBuffer outputBuffer = new DataOutputBuffer();
        outputBuffer.reset();
        Token<JobTokenIdentifier> jt = new Token<JobTokenIdentifier>("identifier".getBytes(),
                "password".getBytes(), new Text(user), new Text("shuffleService"));
        jt.write(outputBuffer);
        shuffleHandler.initializeApplication(new ApplicationInitializationContext(user, appId,
                ByteBuffer.wrap(outputBuffer.getData(), 0, outputBuffer.getLength()), userFolder));
        URL url = new URL(
                "http://127.0.0.1:" + shuffleHandler.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY)
                        + "/mapOutput?job=job_12345_0001&reduce=" + reducerId + "&map=attempt_12345_1_m_1_0");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
        conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
        conn.connect();
        byte[] byteArr = new byte[10000];
        try {
            DataInputStream is = new DataInputStream(conn.getInputStream());
            is.readFully(byteArr);
        } catch (EOFException e) {
            // ignore
        }
        // Retrieve file owner name
        FileInputStream is = new FileInputStream(fileMap.get(0));
        String owner = NativeIO.POSIX.getFstat(is.getFD()).getOwner();
        is.close();

        String message = "Owner '" + owner + "' for path " + fileMap.get(0).getAbsolutePath()
                + " did not match expected owner '" + user + "'";
        Assert.assertTrue((new String(byteArr)).contains(message));
    } finally {
        shuffleHandler.stop();
        FileUtil.fullyDelete(absLogDir);
    }
}

From source file:com.lrodriguez.SVNBrowser.java

private void doGetGetFile2(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    logDebug("dispatching serveFile request");
    if (request.getParameter("serveFile") != null) {
        if (request.getParameter("serveFile").indexOf("..") >= 0) {
            response.sendError(404);//from   w w w. j a  v  a2 s. c  o  m
            System.err.println("******** Invalid serveFile attempt from " + request.getRemoteAddr());
            return;
        }
        String workingCopyDir = webappRoot
                + getInitParameter(REPOSITORY_DIR).replaceAll("[/\\\\]+", "\\" + File.separator);
        String fileName = workingCopyDir
                + request.getParameter("serveFile").replaceAll("[/\\\\]+", "\\" + File.separator);

        File f = new File(fileName);

        try {
            if (f.getCanonicalPath().indexOf(workingCopyDir) != 0 || !f.exists() || !f.isFile()
                    || f.isHidden()) {
                response.sendError(404);
                System.err.println(
                        "******** Invalid serveFile attempt " + fileName + " from " + request.getRemoteAddr());
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.sendError(404);
            System.err.println(
                    "******** Invalid serveFile attempt " + fileName + " from " + request.getRemoteAddr());
            return;
        }
        int length = 0;
        byte[] bbuf = new byte[1024];
        DataInputStream in = new DataInputStream(new FileInputStream(f));
        response.setHeader("Content-disposition", "attachment; filename=\"" + request.getParameter("serveFile")
                .substring(request.getParameter("serveFile").lastIndexOf("/") + 1));
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            response.getOutputStream().write(bbuf, 0, length);
        }
        in.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
        return;
    }
}

From source file:org.apache.hadoop.hbase.util.RegionMover.java

private List<HRegionInfo> readRegionsFromFile(String filename) throws IOException {
    List<HRegionInfo> regions = new ArrayList<HRegionInfo>();
    File f = new File(filename);
    if (!f.exists()) {
        return regions;
    }/*from w  w w.  ja  v a2s . co  m*/
    FileInputStream fis = null;
    DataInputStream dis = null;
    try {
        fis = new FileInputStream(f);
        dis = new DataInputStream(fis);
        int numRegions = dis.readInt();
        int index = 0;
        while (index < numRegions) {
            regions.add(HRegionInfo.parseFromOrNull(Bytes.readByteArray(dis)));
            index++;
        }
    } catch (IOException e) {
        LOG.error("Error while reading regions from file:" + filename, e);
        throw e;
    } finally {
        if (dis != null) {
            dis.close();
        }
        if (fis != null) {
            fis.close();
        }
    }
    return regions;
}

From source file:com.openhr.UploadFile.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 w  w . j ava 2  s  .co  m
        return map.findForward("masteradmin");
    }

    // 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;
                Company comp = null;
                Branch branch = null;
                Calendar currDtCal = Calendar.getInstance();

                // Zero out the hour, minute, second, and millisecond
                currDtCal.set(Calendar.HOUR_OF_DAY, 0);
                currDtCal.set(Calendar.MINUTE, 0);
                currDtCal.set(Calendar.SECOND, 0);
                currDtCal.set(Calendar.MILLISECOND, 0);

                Date now = currDtCal.getTime();

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

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

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

                    // Format is - 
                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,BankName,BankBranch,RoutingNo,AccountNo,NetPay,Currency,
                    // residenttype,TaxAmount,EmployerSS,EmployeeSS
                    if (comp == null || comp.getId() != Integer.parseInt(lineColumns[0])) {
                        List<Company> comps = CompanyFactory.findById(Integer.parseInt(lineColumns[0]));

                        if (comps != null && comps.size() > 0) {
                            comp = comps.get(0);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("Unable to get the details of the company");
                        }

                        // Check for licenses
                        List<Licenses> compLicenses = LicenseFactory.findByCompanyId(comp.getId());
                        for (Licenses lis : compLicenses) {
                            if (lis.getActive() == 1) {
                                Date endDate = lis.getTodate();
                                if (!isLicenseActive(now, endDate)) {
                                    br.close();
                                    in.close();
                                    fstream.close();

                                    // License has expired and throw an error
                                    throw new Exception("License has expired");

                                    //TODO remove the below code and enable above
                                    /*List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                    String branchName = lineColumns[1];
                                    if(branches != null && !branches.isEmpty()) {
                                      for(Branch bb: branches) {
                                         if(branchName.equalsIgnoreCase(bb.getName())) {
                                            branch = bb;
                                            break;
                                         }
                                      }
                                              
                                      if(branch == null) {
                                         Branch bb = new Branch();
                                    bb.setName(branchName);
                                    bb.setAddress("NA");
                                    bb.setCompanyId(comp);
                                            
                                    BranchFactory.insert(bb);
                                            
                                    List<Branch> lbranches = BranchFactory.findByName(branchName);
                                    branch = lbranches.get(0);
                                      }
                                    }*/
                                    //TODO
                                } else {
                                    // License enddate is valid, so lets check the key.
                                    String compName = comp.getName();
                                    String licenseKeyStr = LicenseValidator.formStringToEncrypt(compName,
                                            endDate);
                                    if (LicenseValidator.encryptAndCompare(licenseKeyStr,
                                            lis.getLicensekey())) {
                                        // License key is valid, so proceed.
                                        List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                        String branchName = lineColumns[1];
                                        if (branches != null && !branches.isEmpty()) {
                                            for (Branch bb : branches) {
                                                if (branchName.equalsIgnoreCase(bb.getName())) {
                                                    branch = bb;
                                                    break;
                                                }
                                            }

                                            if (branch == null) {
                                                Branch bb = new Branch();
                                                bb.setName(branchName);
                                                bb.setAddress("NA");
                                                bb.setCompanyId(comp);

                                                BranchFactory.insert(bb);

                                                List<Branch> lbranches = BranchFactory.findByName(branchName);
                                                branch = lbranches.get(0);
                                            }
                                        }
                                        break;
                                    } else {
                                        br.close();
                                        in.close();
                                        fstream.close();

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

                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,DeptName,BankName,BankBranch,RoutingNo,AccountNo,NetPay,currency,TaxAmt,emprSS,empess,basesalary                       
                    CompanyPayroll compPayroll = new CompanyPayroll();
                    compPayroll.setBranchId(branch);
                    compPayroll.setEmployeeId(lineColumns[2]);
                    compPayroll.setEmpFullName(lineColumns[3]);
                    compPayroll.setEmpNationalID(lineColumns[4]);
                    compPayroll.setDeptName(lineColumns[5]);
                    compPayroll.setBankName(lineColumns[6]);
                    compPayroll.setBankBranch(lineColumns[7]);
                    compPayroll.setRoutingNo(lineColumns[8]);
                    compPayroll.setAccountNo(lineColumns[9]);
                    compPayroll.setNetPay(Double.parseDouble(lineColumns[10]));
                    compPayroll.setCurrencySym(lineColumns[11]);
                    compPayroll.setResidentType(lineColumns[12]);
                    compPayroll.setTaxAmount(Double.parseDouble(lineColumns[13]));
                    compPayroll.setEmprSocialSec(Double.parseDouble(lineColumns[14]));
                    compPayroll.setEmpeSocialSec(Double.parseDouble(lineColumns[15]));
                    compPayroll.setBaseSalary(Double.parseDouble(lineColumns[16]));
                    compPayroll.setProcessedDate(now);
                    CompanyPayrollFactory.insert(compPayroll);
                }

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

From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletResponse response, String currentFileDownloadPath) {
    LOG.info(DOWNLOADING_FILE_FROM_PATH + currentFileDownloadPath);
    DataInputStream inputStream = null;
    ServletOutputStream outStream = null;
    try {//from w  ww .  j av a 2s  .c  o  m
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = APPLICATION_OCTET_STREAM;
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName + CLOSING_QUOTES);
        byte[] byteBuffer = new byte[1024];
        inputStream = new DataInputStream(new FileInputStream(file));
        length = inputStream.read(byteBuffer);
        while ((inputStream != null) && (length != -1)) {
            outStream.write(byteBuffer, 0, length);
            length = inputStream.read(byteBuffer);
        }
        LOG.info(DOWNLOAD_COMPLETED_FOR_FILEPATH + currentFileDownloadPath);
    } catch (IOException e) {
        LOG.error(EXCEPTION_OCCURED_WHILE_DOWNLOADING_A_FILE_FROM_THE_FILE_PATH + currentFileDownloadPath);
        LOG.error(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_INPUT_STREAM_FOR_FILE_DOWNLOAD);
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_FLUSH_OUTPUT_STREAM_FOR_DOWNLOAD);
            }
            try {
                outStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_OUTPUT_STREAM_FOR_DOWNLOAD);
            }

        }
    }
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadData(File f, boolean clearData) throws IOException {
    BufferedInputStream inReader = new BufferedInputStream(new FileInputStream(f), 1000000);// RandomAccessFile in = new
    // RandomAccessFile(f, "r");
    DataInputStream in = new DataInputStream(inReader);
    int tot = in.readInt();
    wide = in.readInt();/* w w w. j  av  a2 s  .  c  om*/
    high = in.readInt();

    short[][][] holder = new short[tot][wide][high];

    byte[] inputHolder = new byte[high * 2];
    for (int i = 0; i < tot; i++) {
        Date d = new Date(in.readLong());
        for (int x = 0; x < wide; x++) {
            in.read(inputHolder);
            for (int y = 0; y < high; y++) {
                holder[i][wide - 1 - x][high - y - 1] = BinaryToolkit.readShort(inputHolder, y * 2);
            }
            // for (int y = 0; y < high; y++)
            // {
            // holder[i][x][y] = in.readShort();
            // }
        }
        addData(d, holder[i]);
    }
    ((SpinnerNumberModel) currentValue.getModel()).setMaximum(imageData.size() - 1);
    in.close();
    setCurrentImage(0);
    image.updateMaxMin();
}

From source file:org.apache.hadoop.hbase.rest.TestTableScan.java

/**
 * Read protobuf stream./*  w w w .  j a  va  2  s.c  o  m*/
 * @param inputStream the input stream
 * @return The number of rows in the cell set model.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public int readProtobufStream(InputStream inputStream) throws IOException {
    DataInputStream stream = new DataInputStream(inputStream);
    CellSetModel model = null;
    int rowCount = 0;
    try {
        while (true) {
            byte[] lengthBytes = new byte[2];
            int readBytes = stream.read(lengthBytes);
            if (readBytes == -1) {
                break;
            }
            assertEquals(2, readBytes);
            int length = Bytes.toShort(lengthBytes);
            byte[] cellset = new byte[length];
            stream.read(cellset);
            model = new CellSetModel();
            model.getObjectFromMessage(cellset);
            checkRowsNotNull(model);
            rowCount = rowCount + TestScannerResource.countCellSet(model);
        }
    } catch (EOFException exp) {
        exp.printStackTrace();
    } finally {
        stream.close();
    }
    return rowCount;
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileUploader.java

/**
 * ????//from   www.  ja  v  a  2 s . c  o m
 *
 * @param httpConnection
 *            :http
 * @return 1?? 0? -1??
 */
private int getResultCode(HttpURLConnection httpConnection) {
    DataInputStream dataInputStream = null;
    try {
        if (HttpURLConnection.HTTP_OK != httpConnection.getResponseCode()) {
            return RESULT_CODE_ERROR;
        }
        // ??RETURN_CODE:1
        dataInputStream = new DataInputStream(httpConnection.getInputStream());
        // ???response?
        String data = dataInputStream.readLine();
        int resultCode = Integer.valueOf(data.substring(data.indexOf(":") + 1));
        return (resultCode == RESULT_CODE_CHUNK_RECEIVED || resultCode == RESULT_CODE_FILE_RECEIVED)
                ? resultCode
                : RESULT_CODE_ERROR;
    } catch (Exception e) {
        e.printStackTrace();
        return RESULT_CODE_ERROR;
    } finally {
        try {
            if (null != dataInputStream) {
                dataInputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:net.jradius.packet.attribute.AttributeFactory.java

/**
 * Creates a new RadiusAttribute/*from  w  w w  .  ja  v  a 2  s  . c o  m*/
 * @param vendor The VendorID of the attribute (if one)
 * @param type The Attribute Type
 * @param value The Attribute Value
 * @param op The Attribute Operator
 * @return Returns the newly created RadiusAttribute
 */
public static RadiusAttribute newAttribute(long vendor, long type, byte[] value, int op, boolean pool) {
    RadiusAttribute attr = null;

    try {
        if (vendor > 1 || type == 26) {
            boolean onWire = (vendor < 1);
            DataInputStream input = null;

            if (onWire) {
                /*
                 *  We are parsing an off-the-wire packet
                 */
                ByteArrayInputStream bais = new ByteArrayInputStream(value);
                input = new DataInputStream(bais);

                vendor = RadiusFormat.readUnsignedInt(input);
                type = RadiusFormat.readUnsignedByte(input);
            }

            Long key = new Long(vendor << 16 | type);

            if (pool) {
                attr = borrow(key);
            }

            if (attr == null) {
                attr = vsa(vendor, type);
            }

            if (onWire) {
                VSAttribute vsa = (VSAttribute) attr;
                int vsaLength = 0;
                int vsaHeaderLen = 2;
                switch (vsa.getLengthLength()) {
                case 1:
                    vsaLength = RadiusFormat.readUnsignedByte(input);
                    break;
                case 2:
                    vsaLength = RadiusFormat.readUnsignedShort(input);
                    vsaHeaderLen++;
                    break;
                case 4:
                    vsaLength = (int) RadiusFormat.readUnsignedInt(input);
                    vsaHeaderLen += 3;
                    break;
                }
                if (vsa.hasContinuationByte) {
                    vsa.continuation = (short) RadiusFormat.readUnsignedByte(input);
                    vsaHeaderLen++;
                }
                byte[] newValue = new byte[vsaLength - vsaHeaderLen];
                input.readFully(newValue);
                input.close();
                value = newValue;
            }
        } else {
            if (pool) {
                attr = borrow(type);
            }

            if (attr == null) {
                attr = attr(type);
            }
        }

        if (value != null)
            attr.setValue(value);
        else
            attr.setValue(new byte[] {});
        if (op > -1)
            attr.setAttributeOp(op);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return attr;
}