Example usage for java.io ObjectInputStream close

List of usage examples for java.io ObjectInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the input stream.

Usage

From source file:com.baidu.terminator.storage.file.FileStorage.java

@Override
public RequestResponseBundle getRecordData(String key) {
    // load record offset from database
    HashMap<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("linkId", link.getId());
    parameters.put("signature", key);
    DataIndex recordData = dataIndexMapper.selectDataIndex(parameters);

    // read data record from file
    RequestResponseBundle bundles = new RequestResponseBundle();
    if (recordData != null) {
        logger.info("[GET] the request hit the file storage!");
        Long offset = recordData.getOffset();

        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {/*from ww w.j a v a  2 s.  c o m*/
            fis = new FileInputStream(filePath);
            fis.skip(offset);
            ois = new ObjectInputStream(fis);
            bundles = (RequestResponseBundle) ois.readObject();
        } catch (FileNotFoundException e) {
            logger.error("[GET] can not find data file: " + filePath, e);
        } catch (IOException e) {
            logger.error("[GET] data record from storage in file fail!", e);
        } catch (ClassNotFoundException e) {
            logger.error("[GET] data record from storage in file fail!", e);
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                logger.error("[GET]   close file output stream error", e);
            }
        }
    } else {
        logger.info("[GET] the request does not hit the file storage!");
    }

    return bundles;
}

From source file:cybervillains.ca.KeyStoreManager.java

@SuppressWarnings("unchecked")
public KeyStoreManager(File root) {
    this.root = root;

    Security.insertProviderAt(new BouncyCastleProvider(), 2);

    _sr = new SecureRandom();

    try {/*  w  ww .j  a v a2 s. c o m*/
        _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO);
        _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO);
    } catch (Throwable t) {
        throw new Error(t);
    }

    try {

        File privKeys = new File(root, KEYMAP_SER_FILE);

        if (!privKeys.exists()) {
            _rememberedPrivateKeys = new HashMap<PublicKey, PrivateKey>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys));
            // Deserialize the object
            _rememberedPrivateKeys = (HashMap<PublicKey, PrivateKey>) in.readObject();
            in.close();
        }

        File pubKeys = new File(root, PUB_KEYMAP_SER_FILE);

        if (!pubKeys.exists()) {
            _mappedPublicKeys = new HashMap<PublicKey, PublicKey>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys));
            // Deserialize the object
            _mappedPublicKeys = (HashMap<PublicKey, PublicKey>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // check for file exists, won't happen.
        e.printStackTrace();
    } catch (IOException e) {
        // we could correct, but this probably indicates a corruption
        // of the serialized file that we want to know about; likely
        // synchronization problems during serialization.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // serious problem.
        e.printStackTrace();
        throw new Error(e);
    }

    _rsaKpg.initialize(1024, _sr);
    _dsaKpg.initialize(1024, _sr);

    try {
        _ks = KeyStore.getInstance("JKS");

        reloadKeystore();
    } catch (FileNotFoundException fnfe) {
        try {
            createKeystore();
        } catch (Exception e) {
            throw new Error(e);
        }
    } catch (Exception e) {
        throw new Error(e);
    }

    try {

        File file = new File(root, CERTMAP_SER_FILE);

        if (!file.exists()) {
            _certMap = new HashMap<String, String>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            // Deserialize the object
            _certMap = (HashMap<String, String>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // won't happen, check file.exists()
        e.printStackTrace();
    } catch (IOException e) {
        // corrupted file, we want to know.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // something very wrong, exit
        e.printStackTrace();
        throw new Error(e);
    }

    try {

        File file = new File(root, SUBJMAP_SER_FILE);

        if (!file.exists()) {
            _subjectMap = new HashMap<String, String>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            // Deserialize the object
            _subjectMap = (HashMap<String, String>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // won't happen, check file.exists()
        e.printStackTrace();
    } catch (IOException e) {
        // corrupted file, we want to know.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // something very wrong, exit
        e.printStackTrace();
        throw new Error(e);
    }

}

From source file:net.sf.webissues.core.WebIssuesClientManager.java

public void readCache() {
    if (cacheFile == null || !cacheFile.exists()) {
        return;//from ww w .j a  v a  2  s  . c  om
    }

    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new FileInputStream(cacheFile));
        int size = in.readInt();
        for (int i = 0; i < size; i++) {
            String url = (String) in.readObject();
            WebIssuesClient data = (WebIssuesClient) in.readObject();
            if (url != null && data != null) {
                clientByUrl.put(url, data);
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
        StatusHandler.log(new Status(IStatus.WARNING, WebIssuesCorePlugin.ID_PLUGIN,
                "The WebIssues respository configuration cache could not be read", e));
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.FiskInfoUtility.java

/**
 * Retrieve a serialized <code>FiskInfoPolygon2D</code> from disk as a
 * <code>FiskInfoPolygon2D class</code>
 *
 * @param path//from   w  w w  .ja  va  2s.co  m
 *            the <code>Path</code> to read from
 * @return the Requested <code>FiskInfoPolygon2D</code>
 */
public FiskInfoPolygon2D deserializeFiskInfoPolygon2D(String path) {
    FiskInfoPolygon2D polygon = null;
    FileInputStream fileIn;
    ObjectInputStream in;

    try {
        System.out.println("Starting deserializing");
        fileIn = new FileInputStream(path);
        in = new ObjectInputStream(fileIn);
        polygon = (FiskInfoPolygon2D) in.readObject();

        in.close();
        fileIn.close();
        Log.d("FiskInfo", "Deserialization successful, the data should be stored in the input class");

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        Log.d("Utility", "Deserialization failed, couldn't find class");
        e.printStackTrace();
    }

    return polygon;
}

From source file:com.naryx.tagfusion.cfm.xml.ws.javaplatform.DynamicWebServiceStubGenerator.java

private DynamicCacheClassLoader checkCacheForStub(String wsdlLocation, String newWSDLSum, String portName)
        throws cfmRunTimeException {
    // Look for it by WSDL hash in our java class cache
    File dir = this.genWSDLClassPath(wsdlLocation);
    if (dir.exists()) {
        // Now look for the serialized StubInfo
        File siFile = genStubInfoPath(dir);
        if (siFile.exists()) {
            try {
                StubInfo stubInfo = null;
                FileInputStream fis = null;
                ObjectInputStream ois = null;
                try {
                    fis = new FileInputStream(siFile);
                    ois = new ObjectInputStream(fis);
                    stubInfo = (StubInfo) ois.readObject();
                } finally {
                    if (fis != null)
                        fis.close();/*w  w w . j  a  v a2  s .  c  o m*/
                    if (ois != null)
                        ois.close();
                }

                // Get the class loader for the gen'd stubs
                DynamicCacheClassLoader rtn = DynamicCacheClassLoader.findClassLoader(dir.getCanonicalPath(),
                        DynamicCacheClassLoader.STUB_CLASSES);
                if (rtn == null)
                    throw new cfmRunTimeException(catchDataFactory.generalException("errorCode.runtimeError",
                            "No class loader found for dynamic cache dir: " + dir.getCanonicalPath()));

                // Compare the WSDL sums to see if the WSDL has changed. Then check
                // that the portName
                // we need is the same as the one used to generate the stub's
                // operations initially.
                if (newWSDLSum.equals(stubInfo.getWSDLSum())) {
                    if (portName == null || (portName.equalsIgnoreCase(stubInfo.getPortName()))) {
                        // Nothing's changed, lets go
                        this.si = stubInfo;
                        return rtn;
                    }
                }

                // Otherwise, clear the existing (now invalid) classes and return null
                // (...below)
                rtn.invalidate();
            } catch (IOException ex) {
                // Just ignore and assume we cannot use the cache
                com.nary.Debug.printStackTrace(ex);
            } catch (ClassNotFoundException ex) {
                // Just ignore and assume we cannot use the cache
                com.nary.Debug.printStackTrace(ex);
            }
        }
    }
    // OK, didn't find it
    return null;
}

From source file:edu.snu.leader.simple.SimpleDevelopmentProblem.java

/**
 * Sets up the object by reading it from the parameters stored in
 * state, built off of the parameter base base.
 *
 * @param state/*w  w w  .ja v  a 2 s .  c  om*/
 * @param base
 * @see ec.Problem#setup(ec.EvolutionState, ec.util.Parameter)
 */
@Override
public void setup(EvolutionState state, Parameter base) {
    _LOG.trace("Entering setup( state, base )");

    // Call the superclass implementation
    super.setup(state, base);

    // Get the maximum number of timesteps
    Validate.isTrue(state.parameters.exists(base.push(_MAX_TIMESTEPS_KEY)),
            "Max timesteps parameter not found");
    _maxTimesteps = state.parameters.getInt(base.push(_MAX_TIMESTEPS_KEY), null);
    _LOG.info("Using maxTimesteps=[" + _maxTimesteps + "]");

    // Get the energy consumed per timestep
    Validate.isTrue(state.parameters.exists(base.push(_MIN_ENERGY_CONSUMED_PER_TIMESTEP_KEY)),
            "Energy consumed per timestep not found");
    _minEnergyConsumedPerTimestep = state.parameters.getFloat(base.push(_MIN_ENERGY_CONSUMED_PER_TIMESTEP_KEY),
            null);
    _LOG.info("Using minEnergyConsumedPerTimestep=[" + _minEnergyConsumedPerTimestep + "]");

    // Get the activity energy loss multiplier
    Validate.isTrue(state.parameters.exists(base.push(_ACTIVITY_ENERGY_LOSS_MULTIPLIER_KEY)),
            "Energy consumed per timestep not found");
    _activityEnergyLossMultiplier = state.parameters.getFloat(base.push(_ACTIVITY_ENERGY_LOSS_MULTIPLIER_KEY),
            null);
    _LOG.info("Using activityEnergyLossMultiplier=[" + _activityEnergyLossMultiplier + "]");

    // Get the maturation energy threshold
    Validate.isTrue(state.parameters.exists(base.push(_MATURATION_ENERGY_THRESHOLD_KEY)),
            "Maturation energy threshold not found");
    _maturationEnergyThreshold = state.parameters.getFloat(base.push(_MATURATION_ENERGY_THRESHOLD_KEY), null);
    _LOG.info("Using maturationEnergyThreshold=[" + _maturationEnergyThreshold + "]");

    // Get the maturation energy consumed per timestep
    Validate.isTrue(state.parameters.exists(base.push(_MATURATION_ENERGY_CONSUMED_PER_TIMESTEP_KEY)),
            "Maturation energy consumed per timestep not found");
    _maturationEnergyConsumedPerTimestep = state.parameters
            .getFloat(base.push(_MATURATION_ENERGY_CONSUMED_PER_TIMESTEP_KEY), null);
    _LOG.info("Using maturationEnergyConsumedPerTimestep=[" + _maturationEnergyConsumedPerTimestep + "]");

    // Get the maturation energy threshold
    Validate.isTrue(state.parameters.exists(base.push(_ENERGY_GAIN_MULTIPLIER_KEY)),
            "Energy gain multiplier not found");
    _energyGainMultiplier = state.parameters.getFloat(base.push(_ENERGY_GAIN_MULTIPLIER_KEY), null);
    _LOG.info("Using energyGainMultiplier=[" + _energyGainMultiplier + "]");

    // Get the initial energy level
    Validate.isTrue(state.parameters.exists(base.push(_INITIAL_ENERGY_LEVEL_KEY)),
            "Energy gain multiplier not found");
    _initialEnergyLevel = state.parameters.getFloat(base.push(_INITIAL_ENERGY_LEVEL_KEY), null);
    _LOG.info("Using initialEnergyLevel=[" + _initialEnergyLevel + "]");

    // Get the evaluation count
    Validate.isTrue(state.parameters.exists(base.push(_EVALUATION_COUNT_KEY)), "Evaluation count not found");
    _evaluationCount = state.parameters.getInt(base.push(_EVALUATION_COUNT_KEY), null);
    _LOG.info("Using evaluationCount=[" + _evaluationCount + "]");

    /* Get the number of evaluations to perform using the alternation
     * predation input type */
    _altEvaluationCount = state.parameters.getInt(base.push(_ALT_EVALUATION_COUNT_KEY), null, -1);
    _LOG.info("Using altEvaluationCount=[" + _altEvaluationCount + "]");

    // Get the initial energy level
    Validate.isTrue(state.parameters.exists(base.push(_DESCRIPTION_STEP_COUNT_KEY)),
            "Description step count not found");
    _descriptionStepCount = state.parameters.getInt(base.push(_DESCRIPTION_STEP_COUNT_KEY), null);
    _LOG.info("Using descriptionStepCount=[" + _descriptionStepCount + "]");

    // Get the predation input type
    Validate.isTrue(state.parameters.exists(base.push(_PREDATION_INPUT_TYPE_KEY)),
            "Predation input type not found");
    String predationInputType = state.parameters.getString(base.push(_PREDATION_INPUT_TYPE_KEY), null);
    _predationInputType = PredationInputType.valueOf(predationInputType.toUpperCase().trim());
    Validate.notNull(_predationInputType, "Unknown predation input type [" + predationInputType + "]");
    _LOG.info("Using predationInputType=[" + _predationInputType + "]");

    // Get the alternate predation input type
    String altPredationInputType = state.parameters.getString(base.push(_ALT_PREDATION_INPUT_TYPE_KEY), null);
    if (null != altPredationInputType) {
        _altPredationInputType = PredationInputType.valueOf(altPredationInputType.toUpperCase().trim());
        Validate.notNull(_altPredationInputType,
                "Unknown alternate predation input type [" + _altPredationInputType + "]");
        _LOG.info("Using altPredationInputType=[" + _altPredationInputType + "]");
    }

    // Get the predation noise level multiplier
    _predationNoiseMultiplier = state.parameters.getFloat(base.push(_PREDATION_NOISE_MULTIPLIER_KEY), null,
            0.0f);
    _LOG.info("Using predationNoiseMultiplier=[" + _predationNoiseMultiplier + "]");

    // Get the other's serialized network file (if specified)
    if (state.parameters.exists(base.push(_OTHER_NETWORK_FILE))) {
        String otherNetworkFile = state.parameters.getString(base.push(_OTHER_NETWORK_FILE), null);

        // Deserialize the network file
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(otherNetworkFile));
            Object obj = in.readObject();
            in.close();
            _otherNetwork = (Network) obj;
        } catch (Exception e) {
            _LOG.error("Unable to load other's serialized network from [" + otherNetworkFile + "]", e);
            System.err.println("Unable to load other's serialized network from [" + otherNetworkFile + "]");
            e.printStackTrace();
            System.exit(1);
        }

        // Get the predation input type
        Validate.isTrue(state.parameters.exists(base.push(_OTHER_PREDATION_INPUT_TYPE_KEY)),
                "Other predation input type not found");
        String otherPredationInputType = state.parameters.getString(base.push(_OTHER_PREDATION_INPUT_TYPE_KEY),
                null);
        _otherPredationInputType = PredationInputType.valueOf(otherPredationInputType.toUpperCase().trim());
        Validate.notNull(_otherPredationInputType,
                "Unknown other predation input type [" + otherPredationInputType + "]");
        _LOG.info("Using otherPredationInputType=[" + _otherPredationInputType + "]");

        // Get the alternate predation input type
        String otherAltPredationInputType = state.parameters
                .getString(base.push(_ALT_OTHER_PREDATION_INPUT_TYPE_KEY), null);
        if (null != otherAltPredationInputType) {
            _altOtherPredationInputType = PredationInputType
                    .valueOf(otherAltPredationInputType.toUpperCase().trim());
            Validate.notNull(otherAltPredationInputType,
                    "Unknown alternate other predation input type [" + otherAltPredationInputType + "]");
            _LOG.info("Using altOtherPredationInputType=[" + _altOtherPredationInputType + "]");
        }

        // Get the noise multiplier
        _otherPredationNoiseMultiplier = state.parameters
                .getFloat(base.push(_OTHER_PREDATION_NOISE_MULTIPLIER_KEY), null, 0.0f);
        _LOG.info("Using otherPredationNoiseMultiplier=[" + _otherPredationNoiseMultiplier + "]");
    }

    _LOG.trace("Leaving setup( state, base )");
}

From source file:cai.flow.packets.V9_Packet.java

/**
 * UDPflowsVector//www.  j  a  va  2  s . c om
 *
 * @param RouterIP
 * @param buf
 * @param len
 * @throws DoneException
 */
@SuppressWarnings("unchecked")
public V9_Packet(String RouterIP, byte[] buf, int len) throws DoneException {
    if (Params.DEBUG) {
        // 
        //            File tmpFile = new File("D:\\Dev\\netflow\\jnca\\savePacketT_211.98.0.147_256.cache.tmp");
        File tmpFile = new File("D:\\Dev\\netflow\\jnca\\savePacketT_211.98.0.147_256.cache.tmp");
        if (tmpFile.exists()) {
            try {
                ObjectInputStream fIn = new ObjectInputStream(new FileInputStream(tmpFile));
                System.out.println("Directly read from " + fIn);
                try {
                    buf = (byte[]) fIn.readObject();
                    len = ((Integer) fIn.readObject()).intValue();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                fIn.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                ObjectOutputStream fOut;
                fOut = new ObjectOutputStream(new FileOutputStream(tmpFile));
                fOut.writeObject(buf);
                fOut.writeObject(new Integer(len));
                fOut.flush();
                fOut.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        // 
    }
    if (len < V9_Header_Size) {
        throw new DoneException("    * incomplete header *");
    }

    this.routerIP = RouterIP;
    count = Util.to_number(buf, 2, 2); // (template data flowset

    SysUptime = Util.to_number(buf, 4, 4);
    Variation vrat = Variation.getInstance();
    vrat.setVary(Util.convertIPS2Long(RouterIP), SysUptime);
    unix_secs = Util.to_number(buf, 8, 4);
    packageSequence = Util.to_number(buf, 12, 4);
    sourceId = Util.to_number(buf, 16, 4);

    flows = new Vector((int) count * 30); // Let's first make some space
    optionFlows = new Vector();
    // t
    long flowsetLength = 0l;
    // flowset
    for (int flowsetCounter = 0, packetOffset = V9_Header_Size; flowsetCounter < count
            && packetOffset < len; flowsetCounter++, packetOffset += flowsetLength) {
        // flowset
        long flowsetId = Util.to_number(buf, packetOffset, 2);
        flowsetLength = Util.to_number(buf, packetOffset + 2, 2);
        if (flowsetLength == 0) {
            throw new DoneException("there is a flowset len=0packet invalid");
        }
        if (flowsetId == 0) {
            // template flowsettemplateiddata flowset
            // template flowset
            int thisTemplateOffset = packetOffset + 4;
            do {
                // template
                long templateId = Util.to_number(buf, thisTemplateOffset, 2);
                long fieldCount = Util.to_number(buf, thisTemplateOffset + 2, 2);
                if (TemplateManager.getTemplateManager().getTemplate(this.routerIP, (int) templateId) == null
                        || Params.v9TemplateOverwrite) {
                    try {
                        TemplateManager.getTemplateManager().acceptTemplate(this.routerIP, buf,
                                thisTemplateOffset);
                    } catch (Exception e) {
                        if (Params.DEBUG) {
                            e.printStackTrace();
                        }
                        if ((e.toString() != null) && (!e.toString().equals(""))) {
                            if (e.toString().startsWith("savePacket")) {
                                try {
                                    ObjectOutputStream fOut;
                                    fOut = new ObjectOutputStream(
                                            new FileOutputStream("./" + e.toString() + ".cache.tmp"));
                                    fOut.writeObject(buf);
                                    fOut.writeObject(new Integer(len));
                                    fOut.flush();
                                    fOut.close();
                                    System.err.println("Saved ");
                                } catch (FileNotFoundException e2) {
                                    e2.printStackTrace();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            } else {
                                System.err.println("An Error without save:" + e.toString());
                            }
                        }
                    }

                }
                thisTemplateOffset += fieldCount * 4 + 4; //
            } while (thisTemplateOffset - packetOffset < flowsetLength);
        } else if (flowsetId == 1) { // options flowset
            continue;
            //                int thisOptionTemplateOffset = packetOffset + 4;
            //                // bypass flowsetID and flowset length
            //                do {
            //                    // template
            //                    long optionTemplateId = Util.to_number(buf,
            //                            thisOptionTemplateOffset, 2);
            //                    long scopeLen = Util.to_number(buf,
            //                            thisOptionTemplateOffset + 2, 2);
            //                    long optionLen = Util.to_number(buf,
            //                            thisOptionTemplateOffset + 4, 2);
            //                    if (OptionTemplateManager.getOptionTemplateManager()
            //                        .getOptionTemplate(this.routerIP,
            //                                           (int) optionTemplateId) == null
            //                        || Params.v9TemplateOverwrite) {
            //                        OptionTemplateManager.getOptionTemplateManager()
            //                                .acceptOptionTemplate(this.routerIP, buf,
            //                                thisOptionTemplateOffset);
            //                    }
            //                    thisOptionTemplateOffset += scopeLen + optionLen + 6;
            //                } while (thisOptionTemplateOffset -
            //                         packetOffset < flowsetLength);
        } else if (flowsetId > 255) {
            // data flowset
            // templateId==flowsetId
            Template tOfData = TemplateManager.getTemplateManager().getTemplate(this.routerIP, (int) flowsetId); // flowsetId==templateId
            if (tOfData != null) {
                int dataRecordLen = tOfData.getTypeOffset(-1); // 
                // packetOffset+4 flowsetId  length
                for (int idx = 0, p = packetOffset + 4; (p - packetOffset + dataRecordLen) < flowsetLength; //consider padding
                        idx++, p += dataRecordLen) { //+5 makes OK
                    // IP?v9v5
                    V5_Flow f;
                    try {
                        f = new V5_Flow(RouterIP, buf, p, tOfData);
                        flows.add(f);
                    } catch (DoneException e) {
                        if (Params.DEBUG) {
                            e.printStackTrace();
                        }
                        if ((e.toString() != null) && (!e.toString().equals(""))) {
                            if (e.toString().startsWith("savePacket")) {
                                try {
                                    ObjectOutputStream fOut;
                                    fOut = new ObjectOutputStream(
                                            new FileOutputStream("./" + e.toString() + ".cache.tmp"));
                                    fOut.writeObject(buf);
                                    fOut.writeObject(new Integer(len));
                                    fOut.flush();
                                    fOut.close();
                                    System.err.println("Saved ");
                                } catch (FileNotFoundException e2) {
                                    e2.printStackTrace();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            } else {
                                System.err.println(e.toString());
                            }
                        }
                    }
                }
            } else { //options packet, should refer to option template, not in use now
                continue;
                //                    OptionTemplate otOfData = OptionTemplateManager
                //                                              .getOptionTemplateManager().
                //                                              getOptionTemplate(
                //                            this.routerIP, (int) flowsetId);
                //                    if (otOfData != null) {
                //                        int dataRecordLen = otOfData.getTypeOffset( -1); // 
                //                        // packetOffset+4 flowsetId  length
                //                        for (int idx = 0, p = packetOffset + 4; p
                //                                              - packetOffset < flowsetLength;
                //                                              idx++, p += dataRecordLen) {
                //                            OptionFlow of;
                //                            try {
                //                                of = new OptionFlow(RouterIP, buf, p, otOfData);
                ////                                optionFlows.add(of); // Vector
                //                            } catch (DoneException e) {
                //                                if (Params.DEBUG) {
                //                                    e.printStackTrace();
                //                                }
                //                                System.err.println(e.toString());
                //                            }
                //                        }
                //                    } else {
                //                        System.err.println(this.routerIP + "" + flowsetId
                //                                           + "template");
                //                    }
            }
        }
    }
}

From source file:net.sf.jhylafax.addressbook.AddressBook.java

public void load(File file) throws IOException, ClassNotFoundException {
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    try {//ww  w .  j ava2s .c  o m
        ContactDatabase contactDatabase = (ContactDatabase) in.readObject();
        localAddressBook.setDatabase(contactDatabase);
    } finally {
        in.close();
    }
}

From source file:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM1.java

@Override
public void run() {

    try {//  www  .  j  a  v a 2s  .c o m
        while (true) {
            Socket socket = server.accept();
            log.info("Cliente conectado  " + socket.getInetAddress());

            try {

                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                printWriter.println(conectou);
                log.info("Sinal de autenticao enviado para o Cliente  " + new Date().toString());

                //Faz verificao no fluxo de entrada do Objeto
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

                try {

                    //faz a leitura do Objeto de entrada
                    Object readObject = objectInputStream.readObject();

                    if (readObject instanceof SendSMSMessage) {

                        try {

                            SendSMSMessage smsMessage = (SendSMSMessage) readObject;

                            // Thread.sleep(random.nextInt(10000));

                            ponte.set(smsMessage);
                            Thread t = new Thread(new ConsumerSendSMSMessage(ponte),
                                    "PONTE_ASYNC_DSSOCKETSIM1");
                            t.start();

                            listaSMS.add(smsMessage);

                            objectInputStream.close();
                            socket.close();

                            if (listaSMS.size() > 0 && !listaSMS.isEmpty()) {

                                DServiceModem1 md1 = new DServiceModem1(listaSMS, 1000);
                                new Thread(md1, "MODEM 1").start();
                                listaSMS.clear();

                            }

                        } catch (InterruptedException ex) {
                            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            server.close();
        } catch (IOException ex) {
            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:edu.snu.leader.simple.DecisionDevelopmentProblem.java

/**
 * Sets up the object by reading it from the parameters stored in
 * state, built off of the parameter base base.
 *
 * @param state/* ww w.ja v a  2 s.co  m*/
 * @param base
 * @see ec.Problem#setup(ec.EvolutionState, ec.util.Parameter)
 */
@Override
public void setup(EvolutionState state, Parameter base) {
    _LOG.trace("Entering setup( state, base )");

    // Call the superclass implementation
    super.setup(state, base);

    // Get the maximum number of timesteps
    Validate.isTrue(state.parameters.exists(base.push(_MAX_TIMESTEPS_KEY)),
            "Max timesteps parameter not found");
    _maxTimesteps = state.parameters.getInt(base.push(_MAX_TIMESTEPS_KEY), null);
    _LOG.info("Using maxTimesteps=[" + _maxTimesteps + "]");

    // Get the energy consumed per timestep
    Validate.isTrue(state.parameters.exists(base.push(_MIN_ENERGY_CONSUMED_PER_TIMESTEP_KEY)),
            "Energy consumed per timestep not found");
    _minEnergyConsumedPerTimestep = state.parameters.getFloat(base.push(_MIN_ENERGY_CONSUMED_PER_TIMESTEP_KEY),
            null);
    _LOG.info("Using minEnergyConsumedPerTimestep=[" + _minEnergyConsumedPerTimestep + "]");

    // Get the activity energy loss multiplier
    Validate.isTrue(state.parameters.exists(base.push(_ACTIVITY_ENERGY_LOSS_MULTIPLIER_KEY)),
            "Energy consumed per timestep not found");
    _activityEnergyLossMultiplier = state.parameters.getFloat(base.push(_ACTIVITY_ENERGY_LOSS_MULTIPLIER_KEY),
            null);
    _LOG.info("Using activityEnergyLossMultiplier=[" + _activityEnergyLossMultiplier + "]");

    // Get the maturation energy threshold
    Validate.isTrue(state.parameters.exists(base.push(_MATURATION_ENERGY_THRESHOLD_KEY)),
            "Maturation energy threshold not found");
    _maturationEnergyThreshold = state.parameters.getFloat(base.push(_MATURATION_ENERGY_THRESHOLD_KEY), null);
    _LOG.info("Using maturationEnergyThreshold=[" + _maturationEnergyThreshold + "]");

    // Get the maturation energy consumed per timestep
    Validate.isTrue(state.parameters.exists(base.push(_MATURATION_ENERGY_CONSUMED_PER_TIMESTEP_KEY)),
            "Maturation energy consumed per timestep not found");
    _maturationEnergyConsumedPerTimestep = state.parameters
            .getFloat(base.push(_MATURATION_ENERGY_CONSUMED_PER_TIMESTEP_KEY), null);
    _LOG.info("Using maturationEnergyConsumedPerTimestep=[" + _maturationEnergyConsumedPerTimestep + "]");

    // Get the maturation energy threshold
    Validate.isTrue(state.parameters.exists(base.push(_ENERGY_GAIN_MULTIPLIER_KEY)),
            "Energy gain multiplier not found");
    _energyGainMultiplier = state.parameters.getFloat(base.push(_ENERGY_GAIN_MULTIPLIER_KEY), null);
    _LOG.info("Using energyGainMultiplier=[" + _energyGainMultiplier + "]");

    // Get the initial energy level
    Validate.isTrue(state.parameters.exists(base.push(_INITIAL_ENERGY_LEVEL_KEY)),
            "Energy gain multiplier not found");
    _initialEnergyLevel = state.parameters.getFloat(base.push(_INITIAL_ENERGY_LEVEL_KEY), null);
    _LOG.info("Using initialEnergyLevel=[" + _initialEnergyLevel + "]");

    // Get the evaluation count
    Validate.isTrue(state.parameters.exists(base.push(_EVALUATION_COUNT_KEY)), "Evaluation count not found");
    _evaluationCount = state.parameters.getInt(base.push(_EVALUATION_COUNT_KEY), null);
    _LOG.info("Using evaluationCount=[" + _evaluationCount + "]");

    /* Get the number of evaluations to perform using the alternation
     * predation input type */
    _altEvaluationCount = state.parameters.getInt(base.push(_ALT_EVALUATION_COUNT_KEY), null, -1);
    _LOG.info("Using altEvaluationCount=[" + _altEvaluationCount + "]");

    // Get the initial energy level
    Validate.isTrue(state.parameters.exists(base.push(_DESCRIPTION_STEP_COUNT_KEY)),
            "Description step count not found");
    _descriptionStepCount = state.parameters.getInt(base.push(_DESCRIPTION_STEP_COUNT_KEY), null);
    _LOG.info("Using descriptionStepCount=[" + _descriptionStepCount + "]");

    // Get the predation input type
    Validate.isTrue(state.parameters.exists(base.push(_PREDATION_INPUT_TYPE_KEY)),
            "Predation input type not found");
    String predationInputType = state.parameters.getString(base.push(_PREDATION_INPUT_TYPE_KEY), null);
    _predationInputType = PredationInputType.valueOf(predationInputType.toUpperCase().trim());
    Validate.notNull(_predationInputType, "Unknown predation input type [" + predationInputType + "]");
    _LOG.info("Using predationInputType=[" + _predationInputType + "]");

    // Get the alternate predation input type
    String altPredationInputType = state.parameters.getString(base.push(_ALT_PREDATION_INPUT_TYPE_KEY), null);
    if (null != altPredationInputType) {
        _altPredationInputType = PredationInputType.valueOf(altPredationInputType.toUpperCase().trim());
        Validate.notNull(_altPredationInputType,
                "Unknown alternate predation input type [" + _altPredationInputType + "]");
        _LOG.info("Using altPredationInputType=[" + _altPredationInputType + "]");
    }

    // Get the predation noise level multiplier
    _predationNoiseMultiplier = state.parameters.getFloat(base.push(_PREDATION_NOISE_MULTIPLIER_KEY), null,
            0.0f);
    _LOG.info("Using predationNoiseMultiplier=[" + _predationNoiseMultiplier + "]");

    // Get the other's serialized network file (if specified)
    if (state.parameters.exists(base.push(_OTHER_NETWORK_FILE))) {
        String otherNetworkFile = state.parameters.getString(base.push(_OTHER_NETWORK_FILE), null);

        // Deserialize the network file
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(otherNetworkFile));
            Object obj = in.readObject();
            in.close();
            _otherNetwork = (Network) obj;
        } catch (Exception e) {
            _LOG.error("Unable to load other's serialized network from [" + otherNetworkFile + "]", e);
            System.err.println("Unable to load other's serialized network from [" + otherNetworkFile + "]");
            e.printStackTrace();
            System.exit(1);
        }

        // Get the follow network file
        String followNetworkFile = state.parameters.getString(base.push(_FOLLOW_NETWORK_FILE), null);

        // Deserialize the network file
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(followNetworkFile));
            Object obj = in.readObject();
            in.close();
            _followNetwork = (Network) obj;
        } catch (Exception e) {
            _LOG.error("Unable to load follow serialized network from [" + followNetworkFile + "]", e);
            System.err.println("Unable to load follow serialized network from [" + followNetworkFile + "]");
            e.printStackTrace();
            System.exit(1);
        }

        // Get the no-follow network file
        String noFollowNetworkFile = state.parameters.getString(base.push(_NO_FOLLOW_NETWORK_FILE), null);

        // Deserialize the network file
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(noFollowNetworkFile));
            Object obj = in.readObject();
            in.close();
            _noFollowNetwork = (Network) obj;
        } catch (Exception e) {
            _LOG.error("Unable to load no-follow serialized network from [" + noFollowNetworkFile + "]", e);
            System.err
                    .println("Unable to load no-follow serialized network from [" + noFollowNetworkFile + "]");
            e.printStackTrace();
            System.exit(1);
        }

        // Get the predation input type
        Validate.isTrue(state.parameters.exists(base.push(_OTHER_PREDATION_INPUT_TYPE_KEY)),
                "Other predation input type not found");
        String otherPredationInputType = state.parameters.getString(base.push(_OTHER_PREDATION_INPUT_TYPE_KEY),
                null);
        _otherPredationInputType = PredationInputType.valueOf(otherPredationInputType.toUpperCase().trim());
        Validate.notNull(_otherPredationInputType,
                "Unknown other predation input type [" + otherPredationInputType + "]");
        _LOG.info("Using otherPredationInputType=[" + _otherPredationInputType + "]");

        // Get the alternate predation input type
        String otherAltPredationInputType = state.parameters
                .getString(base.push(_ALT_OTHER_PREDATION_INPUT_TYPE_KEY), null);
        if (null != otherAltPredationInputType) {
            _altOtherPredationInputType = PredationInputType
                    .valueOf(otherAltPredationInputType.toUpperCase().trim());
            Validate.notNull(otherAltPredationInputType,
                    "Unknown alternate other predation input type [" + otherAltPredationInputType + "]");
            _LOG.info("Using altOtherPredationInputType=[" + _altOtherPredationInputType + "]");
        }

        // Get the noise multiplier
        _otherPredationNoiseMultiplier = state.parameters
                .getFloat(base.push(_OTHER_PREDATION_NOISE_MULTIPLIER_KEY), null, 0.0f);
        _LOG.info("Using otherPredationNoiseMultiplier=[" + _otherPredationNoiseMultiplier + "]");
    }

    _LOG.trace("Leaving setup( state, base )");
}