Example usage for java.io ObjectInput close

List of usage examples for java.io ObjectInput close

Introduction

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

Prototype

public void close() throws IOException;

Source Link

Document

Closes the input stream.

Usage

From source file:org.apache.synapse.message.store.impl.rabbitmq.RabbitMQConsumer.java

public MessageContext receive() {
    if (!checkConnection()) {
        if (!reconnect()) {
            if (logger.isDebugEnabled()) {
                logger.debug(getId() + " cannot receive message from store. Can not reconnect.");
            }/*from   w  w w.  ja  va  2 s .c om*/
            return null;
        } else {
            logger.info(getId() + " reconnected to store.");
            isReceiveError = false;
        }
    }
    //setting channel
    if (channel != null) {
        if (!channel.isOpen()) {
            if (!setChannel()) {
                logger.info(getId() + " unable to create the channel.");
                return null;
            }
        }
    } else {
        if (!setChannel()) {
            logger.info(getId() + " unable to create the channel.");
            return null;
        }
    }
    //receive messages
    try {

        GetResponse delivery = null;
        delivery = channel.basicGet(queueName, false);

        if (delivery != null) {
            //deserilizing message
            StorableMessage storableMessage = null;
            ByteArrayInputStream bis = new ByteArrayInputStream(delivery.getBody());
            ObjectInput in = new ObjectInputStream(bis);
            try {
                storableMessage = (StorableMessage) in.readObject();
            } catch (ClassNotFoundException e) {
                logger.error(getId() + "unable to read the stored message" + e);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }

            bis.close();
            in.close();
            org.apache.axis2.context.MessageContext axis2Mc = store.newAxis2Mc();
            MessageContext synapseMc = store.newSynapseMc(axis2Mc);
            synapseMc = MessageConverter.toMessageContext(storableMessage, axis2Mc, synapseMc);
            updateCache(delivery, synapseMc, null, false);
            if (logger.isDebugEnabled()) {
                logger.debug(getId() + " Received MessageId:" + delivery.getProps().getMessageId());
            }
            return synapseMc;
        }
    } catch (ShutdownSignalException sse) {
        logger.error(getId() + " connection error when receiving messages" + sse);
    } catch (IOException ioe) {
        logger.error(getId() + " connection error when receiving messages" + ioe);
    }
    return null;
}

From source file:org.lexgrid.valuesets.helper.compiler.FileSystemCachingValueSetDefinitionCompilerDecorator.java

/**
 * Retrieve coded node set./*from  w  ww . ja va 2 s  .co  m*/
 * 
 * @param md5 the md5
 * 
 * @return the coded node set
 * 
 * @throws Exception the exception
 */
protected CodedNodeSet retrieveCodedNodeSet(String md5) {

    try {

        File cachedCnsFile = new File(this.getDiskStorePath() + File.separator + this.getFileName(md5));
        if (!cachedCnsFile.exists()) {
            LoggerFactory.getLogger().info("Compiled Value Set Definition cache miss.");

            return null;
        } else {
            LoggerFactory.getLogger().info("Compiled Value Set Definition cache hit.");

            FileUtils.touch(cachedCnsFile);
        }

        ObjectInput in = new ObjectInputStream(new FileInputStream(cachedCnsFile));
        CodedNodeSetImpl cns;
        try {
            cns = (CodedNodeSetImpl) in.readObject();
        } catch (Exception e) {
            LoggerFactory.getLogger().warn(
                    "Compiled Value Set Definition was found, but it is invalid or corrupted. Removing...", e);
            if (!FileUtils.deleteQuietly(cachedCnsFile)) {
                FileUtils.forceDeleteOnExit(cachedCnsFile);
            }

            throw e;
        }

        in.close();

        if (cns == null) {
            return null;
        } else {
            return cns;
        }
    } catch (Exception e) {
        LoggerFactory.getLogger()
                .warn("There was an error retrieving the Compiled Value Set Definition from the Cache."
                        + " Caching will not be used for this Value Set Definition.", e);

        return null;
    }
}

From source file:org.kepler.objectmanager.repository.RepositoryManager.java

/**
 * First we check to see if there is a configuration file containing the
 * name of the default remote save repository. Then we check the
 * configuration file./*from  w ww. java2  s  .c om*/
 */
private void initRemoteSaveRepo() {
    if (isDebugging)
        log.debug("initRemoteSaveRepo()");
    File remoteSaveRepoFile = new File(_remoteSaveRepoFileName);

    if (!remoteSaveRepoFile.exists()) {
        setSaveRepository(null);
    } else {
        if (isDebugging) {
            log.debug("remoteSaveRepo exists: " + remoteSaveRepoFile.toString());
        }

        try {
            InputStream is = null;
            ObjectInput oi = null;
            try {
                is = new FileInputStream(remoteSaveRepoFile);
                oi = new ObjectInputStream(is);
                Object newObj = oi.readObject();

                String repoName = (String) newObj;
                Repository saveRepo = getRepository(repoName);
                if (saveRepo != null) {
                    setSaveRepository(saveRepo);
                }

                return;

            } finally {
                if (oi != null) {
                    oi.close();
                }
                if (is != null) {
                    is.close();
                }
            }

        } catch (Exception e1) {
            // problem reading file, try to delete it
            log.warn("Exception while reading localSaveRepoFile: " + e1.getMessage());
            try {
                remoteSaveRepoFile.delete();
            } catch (Exception e2) {
                log.warn("Unable to delete localSaveRepoFile: " + e2.getMessage());
            }
        }
    }

}

From source file:com.ethanruffing.preferenceabstraction.AutoPreferences.java

/**
 * Reads the stored value for an Object preference.
 *
 * @param key The key that the preference is stored under.
 * @param def The default value to return if a setting is not found for the
 *            given key.//from   w  ww.jav a  2s .  c o  m
 * @return The value stored for the preference, or the default value on
 * failure.
 */
@Override
public Object getObject(String key, Object def) {
    if (configType == ConfigurationType.SYSTEM) {
        byte[] inArr = prefs.getByteArray(key, null);
        if (inArr == null)
            return def;

        ByteArrayInputStream bis = new ByteArrayInputStream(inArr);
        ObjectInput in = null;
        try {
            in = new ObjectInputStream(bis);
            return in.readObject();
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
            return def;
        } finally {
            try {
                bis.close();
            } catch (IOException ex) {
                // ignore close exception
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                // ignore close exception
            }
        }
    } else {
        Object val = fileConfig.getProperty(key);
        if (val == null)
            return def;
        else
            return val;
    }
}

From source file:org.kepler.util.AuthNamespace.java

/**
 * Read in the Authority and Namespace from the AuthorizedNamespace file.
 *///from   www.j  av a 2s  .  c  o m
public void refreshAuthNamespace() {
    if (isDebugging)
        log.debug("refreshAuthNamespace()");

    try {
        InputStream is = null;
        ObjectInput oi = null;
        try {
            is = new FileInputStream(_anFileName);
            oi = new ObjectInputStream(is);
            Object newObj = oi.readObject();

            String theString = (String) newObj;
            int firstColon = theString.indexOf(':');
            setAuthority(theString.substring(0, firstColon));
            setNamespace(theString.substring(firstColon + 1));
        } finally {
            if (oi != null) {
                oi.close();
            }
            if (is != null) {
                is.close();
            }
        }
    } catch (FileNotFoundException e) {
        log.error(_saveFileName + " file was not found: " + _anFileName);
        e.printStackTrace();
    } catch (IOException e) {
        log.error("Unable to create ObjectInputStream");
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        log.error("Unable to read from ObjectInput");
        e.printStackTrace();
    } catch (Exception e) {
        log.error(e.toString());
        e.printStackTrace();
    }

    if (isDebugging) {
        log.debug("Instance Authority: " + getAuthority());
        log.debug("Instance Namespace: " + getNamespace());
        log.debug("Instance AuthNamespace: " + getAuthNamespace());
        log.debug("Instance Hash Value: " + getFileNameForm());
    }

}

From source file:org.ecoinformatics.seek.ecogrid.EcoGridServicesController.java

public void readServices() {

    File saveFile = new File(_saveFileName);

    if (saveFile.exists()) {
        try {/*from ww  w.j a  v a  2s.co m*/
            InputStream is = new FileInputStream(saveFile);
            ObjectInput oi = new ObjectInputStream(is);
            Object newObj = oi.readObject();
            oi.close();

            Vector<EcoGridService> servs = (Vector<EcoGridService>) newObj;
            for (EcoGridService egs : servs) {
                addService(egs);
            }

            return;
        } catch (Exception e1) {
            // problem reading file, try to delete it
            log.warn("Exception while reading EcoGridServices file: " + e1.getMessage());
            try {
                saveFile.delete();
            } catch (Exception e2) {
                log.warn("Unable to delete EcoGridServices file: " + e2.getMessage());
            }
        }
    } else {
        // initialize default services from the Config.xml file
        readServicesFromConfig();
    }
}

From source file:org.jfree.data.time.junit.TimeSeriesTest.java

/**
 * Serialize an instance, restore it, and check for equality.
 *///from   w  w  w .j  a v  a  2  s.co m
public void testSerialization() {
    TimeSeries s1 = new TimeSeries("A test");
    s1.add(new Year(2000), 13.75);
    s1.add(new Year(2001), 11.90);
    s1.add(new Year(2002), null);
    s1.add(new Year(2005), 19.32);
    s1.add(new Year(2007), 16.89);
    TimeSeries s2 = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(s1);
        out.close();
        ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
        s2 = (TimeSeries) in.readObject();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    assertTrue(s1.equals(s2));
}

From source file:com.microsoft.applicationinsights.internal.channel.common.TransmissionFileSystemOutput.java

private Optional<Transmission> loadTransmission(File file) {
    Transmission transmission = null;//from   w  ww.  jav  a2  s  .  co  m

    InputStream fileInput = null;
    ObjectInput input = null;
    try {
        if (file == null) {
            return Optional.absent();
        }

        fileInput = new FileInputStream(file);
        InputStream buffer = new BufferedInputStream(fileInput);
        input = new ObjectInputStream(buffer);
        transmission = (Transmission) input.readObject();
    } catch (FileNotFoundException e) {
        InternalLogger.INSTANCE.error("Failed to load transmission, file not found, exception: %s",
                e.getMessage());
    } catch (ClassNotFoundException e) {
        InternalLogger.INSTANCE.error("Failed to load transmission, non transmission, exception: %s",
                e.getMessage());
    } catch (IOException e) {
        InternalLogger.INSTANCE.error("Failed to load transmission, io exception: %s", e.getMessage());
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }

    return Optional.fromNullable(transmission);
}

From source file:BeanContainer.java

  protected JMenuBar createMenuBar() {
  JMenuBar menuBar = new JMenuBar();
    /*from   ww w  .j a v  a2  s . com*/
  JMenu mFile = new JMenu("File");

  JMenuItem mItem = new JMenuItem("New...");
  ActionListener lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {  
      Thread newthread = new Thread() {
        public void run() {
          String result = (String)JOptionPane.showInputDialog(
            BeanContainer.this, 
            "Please enter class name to create a new bean", 
            "Input", JOptionPane.INFORMATION_MESSAGE, null, 
            null, m_className);
          repaint();
          if (result==null)
            return;
          try {
            m_className = result;
            Class cls = Class.forName(result);
            Object obj = cls.newInstance();
            if (obj instanceof Component) {
              m_activeBean = (Component)obj;
              m_activeBean.addFocusListener(
                BeanContainer.this);
              m_activeBean.requestFocus();
              getContentPane().add(m_activeBean);
            }
            validate();
          }
          catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(
              BeanContainer.this, "Error: "+ex.toString(),
              "Warning", JOptionPane.WARNING_MESSAGE);
          }
        }
      };
      newthread.start();
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);

  mItem = new JMenuItem("Load...");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {  
      Thread newthread = new Thread() {
        public void run() {
          m_chooser.setCurrentDirectory(m_currentDir);
          m_chooser.setDialogTitle(
            "Please select file with serialized bean");
          int result = m_chooser.showOpenDialog(
            BeanContainer.this);
          repaint();
          if (result != JFileChooser.APPROVE_OPTION)
            return;
          m_currentDir = m_chooser.getCurrentDirectory();
          File fChoosen = m_chooser.getSelectedFile();
          try {
            FileInputStream fStream = 
              new FileInputStream(fChoosen);
            ObjectInput  stream  =  
              new ObjectInputStream(fStream);
            Object obj = stream.readObject();
            if (obj instanceof Component) {
              m_activeBean = (Component)obj;
              m_activeBean.addFocusListener(
                BeanContainer.this);
              m_activeBean.requestFocus();
              getContentPane().add(m_activeBean);
            }
            stream.close();
            fStream.close();
            validate();
          }
          catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(
              BeanContainer.this, "Error: "+ex.toString(),
              "Warning", JOptionPane.WARNING_MESSAGE);
          }
          repaint();
        }
      };
      newthread.start();
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);

  mItem = new JMenuItem("Save...");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      Thread newthread = new Thread() {
        public void run() {
          if (m_activeBean == null)
            return;
          m_chooser.setDialogTitle(
            "Please choose file to serialize bean");
          m_chooser.setCurrentDirectory(m_currentDir);
          int result = m_chooser.showSaveDialog(
            BeanContainer.this);
          repaint();
          if (result != JFileChooser.APPROVE_OPTION)
            return;
          m_currentDir = m_chooser.getCurrentDirectory();
          File fChoosen = m_chooser.getSelectedFile();
          try {
            FileOutputStream fStream = 
              new FileOutputStream(fChoosen);
            ObjectOutput stream  =  
              new ObjectOutputStream(fStream);
            stream.writeObject(m_activeBean);
            stream.close();
            fStream.close();
          }
          catch (Exception ex) {
            ex.printStackTrace();
          JOptionPane.showMessageDialog(
            BeanContainer.this, "Error: "+ex.toString(),
            "Warning", JOptionPane.WARNING_MESSAGE);
          }
        }
      };
      newthread.start();
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);

  mFile.addSeparator();

  mItem = new JMenuItem("Exit");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      System.exit(0);
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);
  menuBar.add(mFile);
    
  JMenu mEdit = new JMenu("Edit");

  mItem = new JMenuItem("Delete");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      if (m_activeBean == null)
        return;
      Object obj = m_editors.get(m_activeBean);
      if (obj != null) {
        BeanEditor editor = (BeanEditor)obj;
        editor.dispose();
        m_editors.remove(m_activeBean);
      }
      getContentPane().remove(m_activeBean);
      m_activeBean = null;
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  mEdit.add(mItem);

  mItem = new JMenuItem("Properties...");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      if (m_activeBean == null)
        return;
      Object obj = m_editors.get(m_activeBean);
      if (obj != null) {
        BeanEditor editor = (BeanEditor)obj;
        editor.setVisible(true);
        editor.toFront();
      }
      else {
        BeanEditor editor = new BeanEditor(m_activeBean);
        m_editors.put(m_activeBean, editor);
      }
    }
  };
  mItem.addActionListener(lst);
  mEdit.add(mItem);
  menuBar.add(mEdit);

  JMenu mLayout = new JMenu("Layout");
  ButtonGroup group = new ButtonGroup();

  mItem = new JRadioButtonMenuItem("FlowLayout");
  mItem.setSelected(true);
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e){
      getContentPane().setLayout(new FlowLayout());
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);

  mItem = new JRadioButtonMenuItem("GridLayout");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e){
      int col = 3;
      int row = (int)Math.ceil(getContentPane().
        getComponentCount()/(double)col);
      getContentPane().setLayout(new GridLayout(row, col, 10, 10));
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);
    
  mItem = new JRadioButtonMenuItem("BoxLayout - X");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      getContentPane().setLayout(new BoxLayout(
        getContentPane(), BoxLayout.X_AXIS));
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);
    
  mItem = new JRadioButtonMenuItem("BoxLayout - Y");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      getContentPane().setLayout(new BoxLayout(
        getContentPane(), BoxLayout.Y_AXIS));
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);
    
  mItem = new JRadioButtonMenuItem("DialogLayout");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      getContentPane().setLayout(new DialogLayout());
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);

  menuBar.add(mLayout);

  return menuBar;
}

From source file:gov.nij.er.ui.EntityResolutionDemo.java

private void loadParameters(File file) {
    ObjectInput input = null;
    try {/*w  w w . j av a2  s  .c o m*/
        input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
        @SuppressWarnings("unchecked")
        Set<AttributeParameters> parameters = (Set<AttributeParameters>) input.readObject();
        if (!rawDataTreeModel.checkParametersConsistent(parameters)) {
            error("Loaded parameters are not consistent with current loaded dataset");
            return;
        }
        parametersTableModel.loadParameters(parameters);
        LOG.debug("Read parameters from file " + file.getAbsolutePath());
    } catch (Exception ex) {
        error("Error reading parameters from file.");
        ex.printStackTrace();
    } finally {
        try {
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}