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.alfresco.repo.search.impl.lucene.index.IndexInfo.java

/**
 * Get the deletions for a given index (there is no check if they should be applied that is up to the calling layer)
 * /*from  ww w  . j ava  2 s.co m*/
 * @param id String
 * @param fileName String
 * @return Set<String>
 * @throws IOException
 */
private Set<String> getDeletions(String id, String fileName) throws IOException {
    if (id == null) {
        throw new IndexerException("\"null\" is not a valid identifier for a transaction");
    }
    // Check state
    Set<String> deletions = new HashSet<String>();
    File location = new File(indexDirectory, id).getCanonicalFile();
    File file = new File(location, fileName).getCanonicalFile();
    if (!file.exists()) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("No deletions for " + id);
        }
        return Collections.<String>emptySet();
    }
    DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
    int size = is.readInt();
    for (int i = 0; i < size; i++) {
        String ref = is.readUTF();
        deletions.add(ref);
    }
    is.close();
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("There are " + deletions.size() + " deletions for " + id);
    }
    return deletions;

}

From source file:com.cardio3g.MainActivity.java

/**
 * Go through each of the Expansion APK files and open each as a zip file.
 * Calculate the CRC for each file and return false if any fail to match.
 *
 * @return true if XAPKZipFile is successful
 *///from   ww w . ja  v  a  2  s .  co  m
void validateXAPKZipFiles() {
    AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() {

        @Override
        protected void onPreExecute() {
            mDownloadViewGroup.setVisibility(View.VISIBLE);
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Object... params) {
            for (XAPKFile xf : xAPKS) {
                String fileName = Helpers.getExpansionAPKFileName(MainActivity.this, xf.mIsMain,
                        xf.mFileVersion);
                if (!Helpers.doesFileExist(MainActivity.this, fileName, xf.mFileSize, false))
                    return false;
                fileName = Helpers.generateSaveFileName(MainActivity.this, fileName);
                ZipResourceFile zrf;
                byte[] buf = new byte[1024 * 256];
                try {
                    zrf = new ZipResourceFile(fileName);
                    ZipResourceFile.ZipEntryRO[] entries = zrf.getAllEntries();
                    /**
                     * First calculate the total compressed length
                     */
                    long totalCompressedLength = 0;
                    for (ZipResourceFile.ZipEntryRO entry : entries) {
                        totalCompressedLength += entry.mCompressedLength;
                    }
                    float averageVerifySpeed = 0;
                    long totalBytesRemaining = totalCompressedLength;
                    long timeRemaining;
                    /**
                     * Then calculate a CRC for every file in the Zip file,
                     * comparing it to what is stored in the Zip directory.
                     * Note that for compressed Zip files we must extract
                     * the contents to do this comparison.
                     */
                    for (ZipResourceFile.ZipEntryRO entry : entries) {
                        if (-1 != entry.mCRC32) {
                            long length = entry.mUncompressedLength;
                            CRC32 crc = new CRC32();
                            DataInputStream dis = null;
                            try {
                                dis = new DataInputStream(zrf.getInputStream(entry.mFileName));

                                long startTime = SystemClock.uptimeMillis();
                                while (length > 0) {
                                    int seek = (int) (length > buf.length ? buf.length : length);
                                    dis.readFully(buf, 0, seek);
                                    crc.update(buf, 0, seek);
                                    length -= seek;
                                    long currentTime = SystemClock.uptimeMillis();
                                    long timePassed = currentTime - startTime;
                                    if (timePassed > 0) {
                                        float currentSpeedSample = (float) seek / (float) timePassed;
                                        if (0 != averageVerifySpeed) {
                                            averageVerifySpeed = SMOOTHING_FACTOR * currentSpeedSample
                                                    + (1 - SMOOTHING_FACTOR) * averageVerifySpeed;
                                        } else {
                                            averageVerifySpeed = currentSpeedSample;
                                        }
                                        totalBytesRemaining -= seek;
                                        timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed);
                                        this.publishProgress(new DownloadProgressInfo(totalCompressedLength,
                                                totalCompressedLength - totalBytesRemaining, timeRemaining,
                                                averageVerifySpeed));
                                    }
                                    startTime = currentTime;
                                    if (mCancelValidation)
                                        return true;
                                }
                                if (crc.getValue() != entry.mCRC32) {
                                    Log.e("EXPANSION ERROR",
                                            "CRC does not match for entry: " + entry.mFileName);
                                    Log.e("EXPANSION ERROR", "In file: " + entry.getZipFileName());
                                    return false;
                                }
                            } finally {
                                if (null != dis) {
                                    dis.close();
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return true;
        }

        @Override
        protected void onProgressUpdate(DownloadProgressInfo... values) {
            onDownloadProgress(values[0]);
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                mDownloadViewGroup.setVisibility(View.GONE);
            } else {
                mDownloadViewGroup.setVisibility(View.VISIBLE);
            }
            super.onPostExecute(result);
        }

    };
    validationTask.execute(new Object());
}

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

/**
 * upload multipart/*from   ww w .j a  v  a 2s .co  m*/
 * 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:android.core.SSLSocketTest.java

/**
 * Does a number of HTTPS requests on some host and consumes the response.
 * We don't use the HttpsUrlConnection class, but do this on our own
 * with the SSLSocket class. This gives us a chance to test the basic
 * behavior of SSL./*  ww  w.j  a  va  2s . com*/
 *
 * @param host      The host name the request is being sent to.
 * @param port      The port the request is being sent to.
 * @param path      The path being requested (e.g. "/index.html").
 * @param outerLoop The number of times we reconnect and do the request.
 * @param innerLoop The number of times we do the request for each
 *                  connection (using HTTP keep-alive).
 * @param delay     The delay after each request (in seconds).
 * @throws IOException When a problem occurs.
 */
private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path,
        int outerLoop, int innerLoop, int delay, int timeout) throws IOException {
    InetSocketAddress address = new InetSocketAddress(host, port);

    for (int i = 0; i < outerLoop; i++) {
        // Connect to the remote host
        Socket socket = secure ? socketFactory.createSocket() : new Socket();
        if (timeout >= 0) {
            socket.setKeepAlive(true);
            socket.setSoTimeout(timeout * 1000);
        }
        socket.connect(address);

        // Get the streams
        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output);

        try {
            DataInputStream input = new DataInputStream(socket.getInputStream());
            try {
                for (int j = 0; j < innerLoop; j++) {
                    android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1");

                    // Send a request
                    writer.println("GET https://" + host + path + " HTTP/1.1\r");
                    writer.println("Host: " + host + "\r");
                    writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r");
                    writer.println("\r");
                    writer.flush();

                    int length = -1;
                    boolean chunked = false;

                    String line = input.readLine();

                    if (line == null) {
                        throw new IOException("No response from server");
                        // android.util.Log.d("SSLSocketTest", "No response from server");
                    }

                    // Consume the headers, check content length and encoding type
                    while (line != null && line.length() != 0) {
                        //                    System.out.println(line);
                        int dot = line.indexOf(':');
                        if (dot != -1) {
                            String key = line.substring(0, dot).trim();
                            String value = line.substring(dot + 1).trim();

                            if ("Content-Length".equalsIgnoreCase(key)) {
                                length = Integer.valueOf(value);
                            } else if ("Transfer-Encoding".equalsIgnoreCase(key)) {
                                chunked = "Chunked".equalsIgnoreCase(value);
                            }

                        }
                        line = input.readLine();
                    }

                    assertTrue("Need either content length or chunked encoding", length != -1 || chunked);

                    // Consume the content itself
                    if (chunked) {
                        length = Integer.parseInt(input.readLine(), 16);
                        while (length != 0) {
                            byte[] buffer = new byte[length];
                            input.readFully(buffer);
                            input.readLine();
                            length = Integer.parseInt(input.readLine(), 16);
                        }
                        input.readLine();
                    } else {
                        byte[] buffer = new byte[length];
                        input.readFully(buffer);
                    }

                    // Sleep for the given number of seconds
                    try {
                        Thread.sleep(delay * 1000);
                    } catch (InterruptedException ex) {
                        // Shut up!
                    }
                }
            } finally {
                input.close();
            }
        } finally {
            writer.close();
        }
        // Close the connection
        socket.close();
    }
}

From source file:com.impetus.kundera.configure.MetamodelConfiguration.java

/**
 * Scan class and put metadata.//from  w w  w  .ja  v  a 2  s  . c  o  m
 * 
 * @param bits
 *            the bits
 * @param reader
 *            the reader
 * @param entityMetadataMap
 *            the entity metadata map
 * @param entityNameToClassMap
 *            the entity name to class map
 * @param keyDiscriptor
 * @param persistence
 *            unit the persistence unit.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws RuleValidationException
 */
private List<Class<?>> scanClassAndPutMetadata(InputStream bits, Reader reader,
        Map<String, EntityMetadata> entityMetadataMap, Map<String, Class<?>> entityNameToClassMap,
        String persistenceUnit, String client, Map<String, List<String>> clazzToPuMap,
        Map<String, IdDiscriptor> entityNameToKeyDiscriptorMap) throws IOException {
    DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
    ClassFile cf = null;
    String className = null;

    List<Class<?>> classes = new ArrayList<Class<?>>();

    try {
        cf = new ClassFile(dstream);

        className = cf.getName();

        List<String> annotations = new ArrayList<String>();

        reader.accumulateAnnotations(annotations,
                (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag));
        reader.accumulateAnnotations(annotations,
                (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag));

        // iterate through all valid annotations
        for (String validAnn : reader.getValidAnnotations()) {

            // check if the current class has one?
            if (annotations.contains(validAnn)) {

                Class<?> clazz = this.getClass().getClassLoader().loadClass(className);
                this.factory.validate(clazz);

                // get the name of entity to be used for entity to class map
                // if or not annotated with name
                String entityName = getEntityName(clazz);

                if ((entityNameToClassMap.containsKey(entityName)
                        && !entityNameToClassMap.get(entityName).getName().equals(clazz.getName()))) {
                    throw new MetamodelLoaderException("Name conflict between classes "
                            + entityNameToClassMap.get(entityName).getName() + " and " + clazz.getName()
                            + ". Make sure no two entity classes with the same name "
                            + " are specified for persistence unit " + persistenceUnit);
                }
                entityNameToClassMap.put(entityName, clazz);

                EntityMetadata metadata = entityMetadataMap.get(clazz);
                if (null == metadata) {
                    log.debug("Metadata not found in cache for " + clazz.getName());
                    // double check locking.
                    synchronized (clazz) {
                        if (null == metadata) {
                            MetadataBuilder metadataBuilder = new MetadataBuilder(persistenceUnit, client,
                                    KunderaCoreUtils.getExternalProperties(persistenceUnit, externalPropertyMap,
                                            persistenceUnits),
                                    kunderaMetadata);
                            metadata = metadataBuilder.buildEntityMetadata(clazz);

                            // in case entity's pu does not belong to parse
                            // persistence unit, it will be null.
                            if (metadata != null) {
                                entityMetadataMap.put(clazz.getName(), metadata);
                                mapClazztoPu(clazz, persistenceUnit, clazzToPuMap);
                                processGeneratedValueAnnotation(clazz, persistenceUnit, metadata,
                                        entityNameToKeyDiscriptorMap);
                            }
                        }
                    }
                }

                // TODO :
                onValidateClientProperties(classes, clazz, persistenceUnit);
            }
        }
    } catch (ClassNotFoundException e) {
        log.error("Class " + className + " not found, it won't be loaded as entity");
    }

    finally {
        if (dstream != null) {
            dstream.close();
        }
        if (bits != null) {
            bits.close();
        }
    }

    return classes;
}

From source file:com.lines.activitys.SettingsActivity.java

/**
 * Delete the databases that already exist, and populate a new one with the
 * user's selected script/*w w w  .j  a va  2  s. c  o  m*/
 * 
 * @param script
 *            - script file we are populating the database with
 * @throws IOException
 */
private void loadScript(String script) throws IOException {

    // Get adapters
    mDbAdapter = app.getPlayAdapter();
    mNDbAdapter = app.getNoteAdapter();

    // Reset tables for Script and Notes
    mDbAdapter.deleteTable();
    mNDbAdapter.deleteTable();

    String text = "";
    InputStream is;
    BufferedInputStream bis;
    DataInputStream dis;
    String line = null;
    int lineNo = -1;
    int actNo = 0;
    int pageNo = 1;

    // Add file extension back on
    script = script + ".txt";
    File file = new File(Environment.getExternalStorageDirectory() + "/learnyourlines/scripts/" + script);

    // Try to open the file, and alert the user if file doesn't exist
    try {
        is = new FileInputStream(file);
        bis = new BufferedInputStream(is);
        dis = new DataInputStream(bis);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    // Read line-by-line and pick out the relevent information
    while (dis.available() != 0) {

        lineNo++;

        line = dis.readLine();

        // Split line into array of words
        String words[] = line.split("\\s+");
        String firstWord = words[0];

        // Keep a count of which Act we're on
        if (firstWord.equals("FIRST") || firstWord.equals("SECOND") || firstWord.equals("THIRD")) {
            actNo++;
        }

        // Keep count of what page we're on (23 lines/page)
        if ((lineNo % 23) == 0 && lineNo != 0) {
            pageNo++;
        }

        // Check our firstWord is a character name
        if (isCharacter(firstWord)) {
            // If the first word doesn't contain a period (.) then we need
            // to take the second word as well as part of the character
            // name.
            if (!firstWord.contains(".")) {
                firstWord += " " + words[1];

                text = "";
                for (int j = 2; j < words.length; j++) {
                    text += words[j] + " ";
                }
                // If the second word is "and" then it is two characters
                // delievering a line and we need to get the other
                // characters name.
                if (words[1].equals("and")) {
                    firstWord += " " + words[2] + ".";

                    text = "";
                    for (int j = 3; j < words.length; j++) {
                        text += words[j] + " ";
                    }
                    // Handle the rest of the data that hasn't yet been
                    // filtered
                } else if (!words[1].contains(".")) {
                    firstWord = "STAGE.";

                    text = "";
                    for (int j = 0; j < words.length; j++) {
                        text += words[j] + " ";
                    }
                }
            }
            // If the firstWord isn't a character, then it is a stage
            // direction
        } else {
            firstWord = "STAGE.";

            text = "";
            for (int j = 0; j < words.length; j++) {
                text += words[j] + " ";
            }
        }

        // If we didn't manage to populate "text" from the previous if
        // statements, then do it here.
        if (text.equals("")) {
            for (int j = 1; j < words.length; j++) {
                text += words[j] + " ";
            }
        }

        // Once we have all the data picked out from current line in text
        // file, create a new row in the database. Filter out text we don't
        // want in our database.
        if (!isAllUpperCase(words[0])) {
            firstWord = firstWord.substring(0, firstWord.length() - 1);
            mDbAdapter.createPlay(lineNo, firstWord, text, actNo, pageNo, "N", "N", 0, 0, 0);
            // If we're not adding to the database, then we need to reduce
            // the line count.
        } else {
            lineNo--;
        }

        // Clear "text" before we read next line
        text = "";
    }

    // Cleanup
    is.close();
    bis.close();
    dis.close();

    finish();

}

From source file:epn.edu.ec.bibliotecadigital.servidor.ServerRunnable.java

@Override
public void run() {
    try {/*  w  w  w .j a  v  a 2 s.c  o  m*/
        DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocket.getOutputStream());
        OutputStream out;
        String accion = dataIn.readUTF();
        Libro lbr;
        String nombreUsuario = dataIn.readUTF();
        System.out.println("nombreUsuario" + nombreUsuario);
        switch (accion) {
        case "bajar":

            String codArchivo = dataIn.readUTF();
            dataOut = new DataOutputStream(clientSocket.getOutputStream());

            lbr = new LibroJpaController(emf).findLibro(Integer.parseInt(codArchivo));
            if (lbr == null) {
                dataOut.writeBoolean(false);
                break;
            }
            dataOut.writeBoolean(true);

            //File file = new File("C:\\Computacion Distribuida\\" + lbr.getNombre());
            dataOut.writeUTF(lbr.getNombre());
            out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                InputStream in = new ByteArrayInputStream(lbr.getArchivo());

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                Usuariolibros usrLbr = new Usuariolibros();
                usrLbr.setFecha(Calendar.getInstance().getTime());
                usrLbr.setAccion('B');
                usrLbr.setCodigolibro(lbr);
                usrLbr.setNombrecuenta(new Usuario(nombreUsuario));
                new UsuariolibrosJpaController(emf).create(usrLbr);
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "subir":
            dataIn = new DataInputStream(clientSocket.getInputStream());
            String fileName = dataIn.readUTF();
            InputStream in = clientSocket.getInputStream();
            try {
                out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileName);
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
                lbr = new Libro();
                lbr.setNombre(fileName);
                lbr.setArchivo(
                        IOUtils.toByteArray(new FileInputStream("C:\\Computacion Distribuida\\" + fileName)));

                new LibroJpaController(emf).create(lbr);
                Usuariolibros usrLbr = new Usuariolibros();
                usrLbr.setFecha(Calendar.getInstance().getTime());
                usrLbr.setAccion('S');
                usrLbr.setCodigolibro(lbr);
                usrLbr.setNombrecuenta(new Usuario(nombreUsuario));
                new UsuariolibrosJpaController(emf).create(usrLbr);
                actualizarLibrosEnServidores(fileName);
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "obtenerLista":
            ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
            outToServer.writeObject(new LibroJpaController(emf).findLibroEntities());
            outToServer.close();
            break;
        case "verificarEstado":
            dataOut.writeUTF(String.valueOf(server.isDisponible()));
            break;
        case "actualizar":
            dataIn = new DataInputStream(clientSocket.getInputStream());
            String fileNameFromServer = dataIn.readUTF();
            in = clientSocket.getInputStream();
            try {
                out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileNameFromServer);
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
            }

        }
        dataIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.symbian.driver.core.controller.tasks.TEFTask.java

/**
 * @param aVisitor//  w w w  .j  a  v  a 2 s  . c o m
 * @param aTestExecuteScript
 * @param lExecuteOnDevice
 * @param aTask
 * @return The last execption raised when running UCC.
 * @throws JStatException
 */
private boolean runUCC(List<String> aArgs, Task aTask) {
    boolean lReturn = true;
    Socket lUccSocket = null;
    DataOutputStream lSocketOut = null;
    DataInputStream lSocketIn = null;
    int lRunNumber = 0;
    int lUccPort = -1;
    String lUccAddress = null;
    IDeviceComms.ISymbianProcess lProcess = null;

    try {
        String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":");
        lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER);

        lUccAddress = lUccSplit[0];
        lUccPort = Integer.parseInt(lUccSplit[1]);
    } catch (ParseException lParseException) {
        LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException);
        iExceptions.put(lParseException, ESeverity.ERROR);
        lReturn = false;
    } catch (NumberFormatException lNumberFormatException) {
        LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException);
        iExceptions.put(lNumberFormatException, ESeverity.ERROR);
        lReturn = false;
    }

    if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) {
        iExceptions.put(
                new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"),
                ESeverity.ERROR);
        return false;
    }

    // Run the test
    try {
        LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort);

        lUccSocket = new Socket(lUccAddress, lUccPort);
        lSocketOut = new DataOutputStream(lUccSocket.getOutputStream());
        lSocketIn = new DataInputStream(lUccSocket.getInputStream());

        LOGGER.fine("Starting UCC while still polling");
        lProcess = iDeviceProxy.createSymbianProcess();
        if (lProcess != null) {
            // run and don't wait
            if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) {
                iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR);
                lReturn = false;
            }

            // Tell UCC that the test has started.
            LOGGER.fine("Writing to UCC socket: " + lRunNumber);
            lSocketOut.writeInt(lRunNumber);
            lSocketOut.flush();

            int lUCCReply = lSocketIn.readInt();
            LOGGER.fine("UCC Reply: " + lUCCReply);
        }

    } catch (UnknownHostException lUnknownHostException) {
        LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException);
        iExceptions.put(lUnknownHostException, ESeverity.ERROR);
        return false;
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE,
                "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null
                        ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: "
                                + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:"
                                + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound()
                        : "\nUcc Socket is NULL"),
                lIOException);
        iExceptions.put(lIOException, ESeverity.ERROR);
        return false;
    } finally {

        // Close UCC
        if (lSocketOut != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket Out.");
                lUccSocket.shutdownInput();
                lUccSocket.shutdownOutput();
                lSocketOut.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lSocketIn != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket In.");
                lSocketIn.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lUccSocket != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket UCC.");
                lUccSocket.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }

        if (!lUccSocket.isClosed()) {
            LOGGER.warning("Could not close the UCC sockets properly.");
        }

        lSocketOut = null;
        lSocketIn = null;
        lUccSocket = null;

        // Poll TEF Test
        if (!lProcess.join()) {
            iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR);
            lReturn = false;
        }

    }
    return lReturn;
}

From source file:UnicodeUtil.java

private static void loadCompositions(ClassLoader loader) {

    DataInputStream in = null;
    try {/*from ww w . ja  v  a2s  . co m*/
        InputStream source = loader.getResourceAsStream("nu/xom/compositions.dat");
        in = new DataInputStream(source);
        // ???? would it make sense to store a serialized HashMap instead????
        compositions = new HashMap();
        try {
            while (true) {
                String composed = in.readUTF();
                String decomposed = in.readUTF();
                compositions.put(decomposed, composed);
            }
        } catch (java.io.EOFException ex) {
            // finished
        }
    } catch (IOException ex) {
        return;
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException ex) {
            // no big deal
        }
    }

}

From source file:it.unimi.di.big.mg4j.document.SimpleCompressedDocumentCollection.java

public Document document(long index) throws IOException {
    ensureDocumentIndex(index);/*from  w  ww .ja  v  a2  s  .c  om*/
    ensureFiles();
    documentsInputBitStream.position(docOffsets.getLong(index));
    @SuppressWarnings("resource")
    final DataInputStream nonTextDataInputStream = hasNonText
            ? new DataInputStream(
                    new FastBufferedInputStream(zipFile.getInputStream(zipFile.getEntry(Long.toString(index)))))
            : null;
    final MutableString uri = readSelfDelimitedUtf8String(documentsInputBitStream, new MutableString());
    final MutableString title = readSelfDelimitedUtf8String(documentsInputBitStream, new MutableString());

    return new AbstractDocument() {
        final MutableString fieldContent = new MutableString();

        @SuppressWarnings("unchecked")
        final Document fakeDocument = factory.getDocument(NullInputStream.getInstance(),
                Reference2ObjectMaps.EMPTY_MAP);

        int nextField = 0;

        public Object content(int field) throws IOException {
            FieldType fieldType = factory.fieldType(field);

            if (nextField > field)
                throw new IllegalStateException();
            // Skip fields
            final MutableString s = new MutableString();
            int len;
            while (nextField < field) {
                switch (factory.fieldType(nextField)) {
                case TEXT:
                    len = documentsInputBitStream.readDelta();
                    if (exact)
                        len *= 2;
                    documentsInputBitStream.skipDeltas(len);
                    break;
                case VIRTUAL:
                    final int nfrag = nonTextDataInputStream.readInt();
                    for (int i = 0; i < 2 * nfrag; i++)
                        MutableString.skipSelfDelimUTF8(nonTextDataInputStream);
                    break;
                default:
                    try {
                        new ObjectInputStream(nonTextDataInputStream).readObject();
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }
                nextField++;
            }

            // Read field
            nextField++;

            switch (fieldType) {
            case TEXT:
                len = documentsInputBitStream.readDelta();
                fieldContent.length(0);

                termsFrequencyKeeper.reset();
                if (exact)
                    nonTermsFrequencyKeeper.reset();

                while (len-- != 0) {
                    termsInputStream.position(termOffsets
                            .getLong(termsFrequencyKeeper.decode(documentsInputBitStream.readDelta())));
                    s.readSelfDelimUTF8(termsInputStream);
                    fieldContent.append(s);
                    if (exact) {
                        nonTermsInputStream.position(nonTermOffsets
                                .getLong(nonTermsFrequencyKeeper.decode(documentsInputBitStream.readDelta())));
                        s.readSelfDelimUTF8(nonTermsInputStream);
                        fieldContent.append(s);
                    } else
                        fieldContent.append(' ');
                }
                return new FastBufferedReader(fieldContent);
            case VIRTUAL:
                final int nfrag = nonTextDataInputStream.readInt();
                MutableString doc = new MutableString();
                MutableString text = new MutableString();
                VirtualDocumentFragment[] fragArray = new VirtualDocumentFragment[nfrag];
                for (int i = 0; i < nfrag; i++) {
                    doc.readSelfDelimUTF8((InputStream) nonTextDataInputStream);
                    text.readSelfDelimUTF8((InputStream) nonTextDataInputStream);
                    fragArray[i] = new AnchorExtractor.Anchor(doc.copy(), text.copy());
                }
                return new ObjectArrayList<VirtualDocumentFragment>(fragArray);

            default:
                try {
                    return new ObjectInputStream(nonTextDataInputStream).readObject();
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        public CharSequence title() {
            return title;
        }

        public CharSequence uri() {
            return uri.length() == 0 ? null : uri;
        }

        public WordReader wordReader(int field) {
            switch (factory.fieldType(field)) {
            case TEXT:
            case VIRTUAL:
                return fakeDocument.wordReader(field);
            default:
                return null;
            }
        }

        public void close() throws IOException {
            super.close();
            if (hasNonText)
                nonTextDataInputStream.close();
        }

    };
}