protected void load(ZipFile zipfile) throws IOException {
    Enumeration entries = zipfile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) entries.nextElement();

      fireBeginFile(entry.getName());

      Logger.getLogger(getClass())
          .debug("Starting file " + entry.getName() + " (" + entry.getSize() + " bytes)");

      byte[] bytes = null;
      InputStream in = null;
      try {
        in = zipfile.getInputStream(entry);
        bytes = readBytes(in);
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException ex) {
            // Ignore
          }
        }
      }

      Logger.getLogger(getClass())
          .debug("Passing up file " + entry.getName() + " (" + bytes.length + " bytes)");
      getLoader().load(entry.getName(), new ByteArrayInputStream(bytes));

      fireEndFile(entry.getName());
    }
  }
  protected void load(String filename, InputStream in) {
    Logger.getLogger(getClass()).debug("Starting group in stream " + filename);

    ZipInputStream zipfile = null;
    try {
      zipfile = new ZipInputStream(in);

      fireBeginGroup(filename, -1);

      Logger.getLogger(getClass()).debug("Loading ZipInputStream " + filename);
      load(zipfile);
      Logger.getLogger(getClass()).debug("Loaded ZipInputStream " + filename);

      fireEndGroup(filename);
    } catch (IOException ex) {
      Logger.getLogger(getClass()).error("Cannot load Zip file \"" + filename + "\"", ex);
    } finally {
      if (zipfile != null) {
        try {
          zipfile.close();
        } catch (IOException ex) {
          // Ignore
        }
      }
    }
  }
  /* Check: getLoggerNames() must return correct names
   *        for registered loggers and their parents.
   * Returns boolean values: PASSED or FAILED
   */
  public static boolean checkLoggers() {
    String failMsg = "# checkLoggers: getLoggerNames() returned unexpected loggers";
    Vector<String> expectedLoggerNames = new Vector<String>(getDefaultLoggerNames());

    // Create the logger LOGGER_NAME_1
    Logger.getLogger(LOGGER_NAME_1);
    expectedLoggerNames.addElement(PARENT_NAME_1);
    expectedLoggerNames.addElement(LOGGER_NAME_1);

    // Create the logger LOGGER_NAME_2
    Logger.getLogger(LOGGER_NAME_2);
    expectedLoggerNames.addElement(PARENT_NAME_2);
    expectedLoggerNames.addElement(LOGGER_NAME_2);

    Enumeration<String> returnedLoggersEnum = logMgr.getLoggerNames();
    Vector<String> returnedLoggerNames = new Vector<String>(0);
    while (returnedLoggersEnum.hasMoreElements()) {
      String logger = returnedLoggersEnum.nextElement();
      if (!initialLoggerNames.contains(logger)) {
        // filter out the loggers that have been added before this test runs
        returnedLoggerNames.addElement(logger);
      }
    }
    ;

    return checkNames(expectedLoggerNames, returnedLoggerNames, failMsg);
  }
예제 #4
0
  public static synchronized void createLoggers(boolean reinit) {

    if (m_initialized == true && reinit == false) {
      return;
    }

    if (!m_initialized) {
      Logger.getLogger("").removeHandler(Logger.getLogger("").getHandlers()[0]);
    }

    if (m_initialized) {
      m_severeLogger.removeHandler(m_severeLogger.getHandlers()[0]);
      m_nonSevereLogger.removeHandler(m_nonSevereLogger.getHandlers()[0]);
    }

    Handler severeHandler = new AMyConsoleHandler(System.err);
    severeHandler.setFormatter(new SingleLineFormatter());
    m_severeLogger.addHandler(severeHandler);
    m_severeLogger.setLevel(getLoggingLevel());

    Handler nonSevereHandler = new AMyConsoleHandler(System.out);
    nonSevereHandler.setFormatter(new SingleLineFormatter());
    m_nonSevereLogger.addHandler(nonSevereHandler);
    m_nonSevereLogger.setLevel(getLoggingLevel());

    m_initialized = true;
  }
  public LocalVariableTable_attribute(ConstantPool constantPool, Visitable owner, DataInput in)
      throws IOException {
    super(constantPool, owner);

    int byteCount = in.readInt();
    Logger.getLogger(getClass()).debug("Attribute length: " + byteCount);

    int localVariableTableLength = in.readUnsignedShort();
    Logger.getLogger(getClass())
        .debug("Reading " + localVariableTableLength + " local variable(s) ...");
    for (int i = 0; i < localVariableTableLength; i++) {
      Logger.getLogger(getClass()).debug("Local variable " + i + ":");
      localVariables.add(new LocalVariable(this, in));
    }
  }
  public void summaryAction(HttpServletRequest req, HttpServletResponse res) {
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<String, Object>();
    DocumentManager docMan = new DocumentManager();

    try {

      if (req.getParameter("documentId") != null) {
        // Get the document ID
        int docId = Integer.parseInt(req.getParameter("documentId"));
        // Get the document using document id
        Document document = docMan.get(docId);
        // Set title to name of the document
        viewData.put("title", document.getDocumentName());
        // Create List of access records
        List<AccessRecord> accessRecords = new LinkedList<AccessRecord>();
        // Add access records for document to the list
        accessRecords = docMan.getAccessRecords(docId);

        viewData.put("accessRecords", accessRecords);
      } else {
        // Go back to thread page.
      }

    } catch (Exception e) {
      Logger.getLogger("").log(Level.SEVERE, "An error occurred when getting profile user", e);
    }

    view(req, res, "/views/group/Document.jsp", viewData);
  }
  /** Creates a new AjaxMetricsFilterConfiguration populated with the default values. */
  protected AjaxMetricsFilterConfiguration() {
    log = Logger.getLogger(getClass());
    // ==========================================================================
    // Set default property values
    // ==========================================================================
    parameterNames.put(pUri, "AG_U");
    parameterNames.put(pElapsed, "AG_E");
    parameterNames.put(pConcurrent, "AG_C");
    parameterNames.put(pException, "AG_X");
    parameterNames.put(pHcode, "AG_H");
    parameterNames.put(pDelta, "AG_D");
    parameterNames.put(pFailure, "AG_F");
    parameterNames.put(pInteractive, "AG_I");
    parameterNames.put(pInteractiveTime, "AG_T");
    parameterNames.put(pInteractiveCallbacks, "AG_B");
    parameterNames.put(pSerialNumber, "AG_S");
    parameterNames.put(pParameter, "AG_P");
    parameterNames.put(pRunOption, "AG_O");

    runOptions.put(reportInteractive, false);
    runOptions.put(reportDelta, true);
    runOptions.put(logging, false);
    runOptions.put(uploadBatch, false);
    runOptions.put(uploadInParams, false);

    batchOptions.put(batchTime, 40);
    batchOptions.put(batchSize, 5);
  }
  protected void load(ZipInputStream in) throws IOException {
    ZipEntry entry;
    while ((entry = in.getNextEntry()) != null) {
      fireBeginFile(entry.getName());

      Logger.getLogger(getClass())
          .debug("Starting file " + entry.getName() + " (" + entry.getSize() + " bytes)");
      byte[] bytes = readBytes(in);

      Logger.getLogger(getClass())
          .debug("Passing up file " + entry.getName() + " (" + bytes.length + " bytes)");
      getLoader().load(entry.getName(), new ByteArrayInputStream(bytes));

      fireEndFile(entry.getName());
    }
  }
예제 #9
0
  /**
   * Main method. Begins the GUI, and the rest of the program.
   *
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    // playSound();
    try {
      for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException
        | InstantiationException
        | IllegalAccessException
        | UnsupportedLookAndFeelException ex) {
      Logger.getLogger(mainForm.class.getName()).log(Level.SEVERE, null, ex);
    }
    // </editor-fold>

    /* Create and display the form */
    EventQueue.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            new mainForm().setVisible(true);
          }
        });
  }
예제 #10
0
/** @author Symphorien Wanko */
public class PopupMessageHandlerSLick extends TestSuite implements BundleActivator {
  /** Logger for this class */
  private static Logger logger = Logger.getLogger(PopupMessageHandlerSLick.class);

  /** our bundle context */
  protected static BundleContext bundleContext = null;

  /** implements BundleActivator.start() */
  public void start(BundleContext bc) throws Exception {
    logger.info("starting popup message test ");

    bundleContext = bc;

    setName("PopupMessageHandlerSLick");

    Hashtable<String, String> properties = new Hashtable<String, String>();

    properties.put("service.pid", getName());

    // we maybe are running on machine without WM and systray
    // (test server machine), skip tests
    if (ServiceUtils.getService(bc, SystrayService.class) != null) {
      addTest(TestPopupMessageHandler.suite());
    }

    bundleContext.registerService(getClass().getName(), this, properties);
  }

  /** implements BundleActivator.stop() */
  public void stop(BundleContext bc) throws Exception {}
}
  public void preprocess(Run run) {
    File logFile = new File(getRunDir(run), "genetik.log");

    try {
      SimpleFileHandler fh = new SimpleFileHandler(logFile);
      fh.setFormatter(new CompactFormatter());

      Logger logger = Logger.getLogger(GenetikConstants.LOGGER);
      logger.setLevel(Level.INFO);
      logger.setUseParentHandlers(false);
      Handler handlers[] = logger.getHandlers();

      logger.addHandler(fh);

      for (Handler h : handlers) {
        logger.removeHandler(h);

        if (h instanceof SimpleFileHandler) h.close(); // close our old one
      }
    } catch (Exception exp) {
      throw new IllegalArgumentException(
          "Unable to create log file at " + logFile.getAbsolutePath());
    }

    super.preprocess(run);
  }
예제 #12
0
    /**
     * Add a named logger.  This does nothing and returns false if a logger
     * with the same name is already registered.
     * <p>
     * The Logger factory methods call this method to register each
     * newly created Logger.
     * <p>
     * The application should retain its own reference to the Logger 
     * object to avoid it being garbage collected.  The LogManager
     * may only retain a weak reference.
     *
     * @param   logger the new logger.
     * @return  true if the argument logger was registered successfully,
     *          false if a logger of that name already exists.
     * @exception NullPointerException if the logger name is null.
     */
    public synchronized boolean addLogger(Logger logger) {
	String name = logger.getName();
	if (name == null) {
	    throw new NullPointerException();
	}

	Logger old = (Logger) loggers.get(name);
	if (old != null) {
	    // We already have a registered logger with the given name.
	    return false;
	}

	// We're adding a new logger.
	// Note that we are creating a strong reference here that will
	// keep the Logger in existence indefinitely.
	loggers.put(name, logger);

	// Apply any initial level defined for the new logger.
	Level level = getLevelProperty(name+".level", null);
	if (level != null) {
	    doSetLevel(logger, level);
	}

	// If any of the logger's parents have levels defined,
	// make sure they are instantiated.
	int ix = 1;
	for (;;) {
	    int ix2 = name.indexOf(".", ix);
	    if (ix2 < 0) {
		break;
	    }
	    String pname = name.substring(0,ix2);
	    if (getProperty(pname+".level") != null) {
		// This pname has a level definition.  Make sure it exists.
		Logger plogger = Logger.getLogger(pname);
	    }
	    ix = ix2+1;
	}

	// Find the new node and its parent.
	LogNode node = findNode(name);
	node.logger = logger;
	Logger parent = null;
	LogNode nodep = node.parent;
	while (nodep != null) {
	    if (nodep.logger != null) {
		parent = nodep.logger;
		break;
	    }
	    nodep = nodep.parent;
	}

	if (parent != null) {
            doSetParent(logger, parent);
	}
	// Walk over the children and tell them we are their new parent.
	node.walkAndSetParent(logger);

	return true;
    }
예제 #13
0
public class IdlePointCron extends HttpServlet {
  /** */
  private static final long serialVersionUID = 1L;

  private static final Logger log = Logger.getLogger(IdlePointCron.class.getName());

  @Override
  @SuppressWarnings(Const.WARNING_UNCHECKED)
  public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
      throws IOException {
    // PrintWriter out;
    // out = resp.getWriter();
    try {
      processGet();
    } catch (NimbitsException e) {
      LogHelper.logException(IdlePointCron.class, e);
    }
  }

  protected static int processGet() throws NimbitsException {
    final List<Entity> points = EntityServiceFactory.getInstance().getIdleEntities();
    log.info("Processing " + points.size() + " potentially idle points");
    for (final Entity p : points) {
      try {
        checkIdle((Point) p);
      } catch (NimbitsException e) {

        LogHelper.logException(IdlePointCron.class, e);
      }
    }
    return points.size();
  }

  protected static boolean checkIdle(final Point p) throws NimbitsException {
    final Calendar c = Calendar.getInstance();
    c.add(Calendar.SECOND, p.getIdleSeconds() * -1);
    boolean retVal = false;
    final List<Entity> result =
        EntityServiceFactory.getInstance()
            .getEntityByKey(
                UserServiceFactory.getServerInstance().getAdmin(), p.getOwner(), EntityType.user);
    if (!result.isEmpty()) {
      final User u = (User) result.get(0);
      final List<Value> v = ValueServiceFactory.getInstance().getCurrentValue(p);
      if (p.getIdleSeconds() > 0
          && !v.isEmpty()
          && v.get(0).getTimestamp().getTime() <= c.getTimeInMillis()
          && !p.getIdleAlarmSent()) {
        p.setIdleAlarmSent(true);
        EntityServiceFactory.getInstance().addUpdateEntity(u, p);
        // PointServiceFactory.getInstance().updatePoint(u, p);
        final Value va = ValueFactory.createValueModel(v.get(0), AlertType.IdleAlert);
        SubscriptionServiceFactory.getInstance().processSubscriptions(u, p, va);
        retVal = true;
      }
    }
    return retVal;
  }
}
예제 #14
0
/** Export to an ARC file */
public class ArcExporter extends Exporter {

  private static Logger log = Logger.getLogger("ArcExporter");

  protected CIProperties arcProps = null;
  String arcFilePrefix = "SimulatedCrawl";
  AtomicInteger serialNo = new AtomicInteger(0);
  ARCWriter aw;
  boolean isResponse;

  public ArcExporter(LockssDaemon daemon, ArchivalUnit au, boolean isResponse) {
    super(daemon, au);
    this.isResponse = isResponse;
  }

  protected void start() {
    aw = makeARCWriter();
  }

  protected void finish() throws IOException {
    aw.close();
  }

  private ARCWriter makeARCWriter() {
    return new ARCWriter(
        serialNo, ListUtil.list(dir), prefix, compress, maxSize >= 0 ? maxSize : Long.MAX_VALUE);
  }

  protected void writeCu(CachedUrl cu) throws IOException {
    String url = cu.getUrl();
    long contentSize = cu.getContentSize();
    CIProperties props = cu.getProperties();
    long fetchTime = Long.parseLong(props.getProperty(CachedUrl.PROPERTY_FETCH_TIME));
    InputStream contentIn = cu.getUnfilteredInputStream();
    try {
      if (isResponse) {
        String hdrString = getHttpResponseString(cu);
        long size = contentSize + hdrString.length();
        InputStream headerIn = new ReaderInputStream(new StringReader(hdrString));
        InputStream concat = new SequenceInputStream(headerIn, contentIn);
        try {
          aw.write(xlateFilename(url), cu.getContentType(), getHostIp(), fetchTime, size, concat);
        } finally {
          IOUtil.safeClose(concat);
        }
      } else {
        aw.write(
            xlateFilename(url),
            cu.getContentType(),
            getHostIp(),
            fetchTime,
            cu.getContentSize(),
            contentIn);
      }
    } finally {
      AuUtil.safeRelease(cu);
    }
  }
}
예제 #15
0
 // @Override
 public synchronized String getIP() {
   try {
     return NetUtils.getIPAddress();
   } catch (ConnectException ex) {
     Logger.getLogger(Mapa.class.getName()).log(Level.SEVERE, null, ex);
   }
   return "";
 }
예제 #16
0
 public void actionPerformed(ActionEvent e) {
   try {
     undo.redo();
   } catch (CannotRedoException ex) {
     Logger.getLogger(RedoAction.class.getName()).log(Level.SEVERE, "Unable to redo", ex);
   }
   update();
   undoAction.update();
 }
예제 #17
0
  DBPort(InetSocketAddress addr, DBPortPool pool, MongoOptions options) throws IOException {
    _options = options;
    _addr = addr;
    _pool = pool;

    _hashCode = _addr.hashCode();

    _logger = Logger.getLogger(_rootLogger.getName() + "." + addr.toString());
  }
예제 #18
0
  /**
   * Construye el objeto que gestionara la comunicacion de datos.
   *
   * @param s Socket de conexion.
   * @throws Exception
   */
  public DataAttendant(Socket s) throws Exception {
    mylogger = Logger.getLogger("isabel.nereda.DataAttendant");
    mylogger.fine("Creating DataAttendant object.");

    sock = s;
    myPP = new PacketProcessor(sock);

    NeReDa.peers.Add(this);
  }
예제 #19
0
/** Test class for <code>org.lockss.scheduler.StepperTask</code> */
public class TestStepperTask extends LockssTestCase {
  public static Class testedClasses[] = {
    org.lockss.scheduler.StepTask.class, org.lockss.scheduler.StepperTask.class,
  };

  static Logger log = Logger.getLogger("TestStepperTask");

  public void setUp() throws Exception {
    super.setUp();
    TimeBase.setSimulated();
  }

  public void tearDown() throws Exception {
    TimeBase.setReal();
    super.tearDown();
  }

  static StepperTask taskBetween(long minStart, long deadline, int duration, Stepper stepper) {
    return new StepperTask(
        Deadline.at(minStart), Deadline.at(deadline), duration, null, null, stepper);
  }

  Stepper newSt(final boolean isFinished) {
    return new Stepper() {
      public int computeStep(int metric) {
        return 0;
      }

      public boolean isFinished() {
        return isFinished;
      }
    };
  }

  public void testStepper() {
    Stepper st = newSt(false);
    StepperTask t = taskBetween(100, 200, 50, st);
    assertEquals(st, t.getStepper());
    assertFalse(t.isBackgroundTask());
    assertFalse(t.isFinished());
    t.e = new Exception();
    assertTrue(t.isFinished());

    Stepper st2 = newSt(true);
    StepperTask t2 = taskBetween(100, 200, 50, st2);
    assertTrue(t2.isFinished());
  }

  public void testToString() {
    Stepper st = newSt(false);
    StepperTask t = taskBetween(100, 200, 50, st);
    t.toString();
    t.cookie = "foo";
    t.toString();
  }
}
  @Override
  public void delete(IMatchresultDto value) {
    try {
      server.domain.classes.Matchresult matchresult = createDomain(value);

      DomainFacade.getInstance().delete(matchresult);
    } catch (IdNotFoundException | CouldNotDeleteException ex) {
      Logger.getLogger(MatchresultMapper.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
예제 #21
0
/**
 * The <tt>Resources</tt> class manages the access to the internationalization properties files and
 * the image resources used in this plugin.
 *
 * @author Yana Stamcheva
 */
public class Resources {

  private static Logger log = Logger.getLogger(Resources.class);

  /** The name of the resource, where internationalization strings for this plugin are stored. */
  private static final String STRING_RESOURCE_NAME =
      "resources.languages.plugin.contactinfo.resources";

  /** The name of the resource, where paths to images used in this bundle are stored. */
  private static final String IMAGE_RESOURCE_NAME =
      "net.java.sip.communicator.plugin.contactinfo.resources";

  /** The string resource bundle. */
  private static final ResourceBundle STRING_RESOURCE_BUNDLE =
      ResourceBundle.getBundle(STRING_RESOURCE_NAME);

  /** The image resource bundle. */
  private static final ResourceBundle IMAGE_RESOURCE_BUNDLE =
      ResourceBundle.getBundle(IMAGE_RESOURCE_NAME);

  /**
   * Returns an internationalized string corresponding to the given key.
   *
   * @param key The key of the string.
   * @return An internationalized string corresponding to the given key.
   */
  public static String getString(String key) {
    try {
      return STRING_RESOURCE_BUNDLE.getString(key);

    } catch (MissingResourceException e) {
      return '!' + key + '!';
    }
  }

  /**
   * Loads an image from a given image identifier.
   *
   * @param imageID The identifier of the image.
   * @return The image for the given identifier.
   */
  public static ImageIcon getImage(String imageID) {
    BufferedImage image = null;

    String path = IMAGE_RESOURCE_BUNDLE.getString(imageID);

    try {
      image = ImageIO.read(Resources.class.getClassLoader().getResourceAsStream(path));
    } catch (IOException e) {
      log.error("Failed to load image:" + path, e);
    }

    return new ImageIcon(image);
  }
}
public class TestElsevierXmlLinkExtractorFactory extends LinkExtractorTestCase {

  private static Logger logger = Logger.getLogger("TestElsevierXmlLinkExtractorFactory");

  String srcUrl = "http://www.example.com/";

  private static final String withLinks =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
          + "<!DOCTYPE dataset SYSTEM \"http://support.sciencedirect.com/xml/sdosftp10.dtd\">\n"
          + "<dataset identifier=\"OXM10160\" customer=\"OHL\""
          + " status=\"Announcement\""
          + " version=\"Network Dataset Announcement/Confirmation v1.0\">"
          + " <date year=\"2007\" month=\"May\" day=\"1\"/>\n"
          + "<file name=\"01407007.tar\" size=\"21780480\""
          + " md5=\"6c7266e0e246bf3e8cf1cd8b659a7a73\"/>\n"
          + "<file name=\"03064530.tar\" size=\"12748800\""
          + " md5=\"df9519d3075e164d22f5dd4988a693c3\"/>\n"
          + "<file name=\"dataset.toc\" size=\"2216587\""
          + " md5=\"cd21741eb91fa0fdfef2fa36485e21a0\"/>\n"
          + "</dataset>\n";

  private static final String withoutLinks =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
          + "<!DOCTYPE dataset SYSTEM \"http://support.sciencedirect.com/xml/sdosftp10.dtd\">\n"
          + "<dataset identifier=\"OXM10160\" customer=\"OHL\""
          + " status=\"Announcement\""
          + " version=\"Network Dataset Announcement/Confirmation v1.0\">"
          + " <date year=\"2007\" month=\"May\" day=\"1\"/>\n"
          + "</dataset>\n";

  private static final String[] links = {
    "01407007.tar", "03064530.tar", "dataset.toc",
  };

  public String getMimeType() {
    return "text/xml";
  }

  public LinkExtractorFactory getFactory() {
    return new ElsevierXmlLinkExtractorFactory();
  }

  public void testFindCorrectEntries() throws Exception {
    Set expected = new HashSet();
    for (String link : links) {
      expected.add(srcUrl + link);
    }
    assertEquals(expected, extractUrls(withLinks));
  }

  public void testFindNoEntries() throws Exception {
    assertEmpty(extractUrls(withoutLinks));
  }
}
  @Override
  public Integer set(IMatchresultDto value) {
    try {
      server.domain.classes.Matchresult matchresult = createDomain(value);

      return DomainFacade.getInstance().set(matchresult);
    } catch (IdNotFoundException | CouldNotSaveException ex) {
      Logger.getLogger(MatchresultMapper.class.getName()).log(Level.SEVERE, null, ex);
    }

    return 0;
  }
예제 #24
0
/**
 * 这是LWTownIndicatorAppend-直供乡追加电费指针记录表的数据访问对象类<br>
 * 创建于 2008-12-17 11:27:43.218<br>
 * JToolpad(1.6.0) Vendor:[email protected]
 */
public class DBLwTownIndicatorAppend extends DBLwTownIndicatorAppendBase {
  private static Logger logger = Logger.getLogger(DBLwTownIndicatorAppend.class);

  /**
   * 构造函数
   *
   * @param dbManager 资源管理类
   */
  public DBLwTownIndicatorAppend(DBManager dbManager) {
    super(dbManager);
  }
}
예제 #25
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
예제 #26
0
 public static TypeList load(String gamePath, String dataName) {
   System.out.println("load:" + dataName);
   InputStream is = null;
   Savable sav = null;
   try {
     File file =
         new File(
             System.getProperty("user.dir")
                 + File.separator
                 + gamePath
                 + File.separator
                 + dataName);
     if (!file.exists()) {
       return null;
     }
     is = new BufferedInputStream(new FileInputStream(file));
     // is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)));
     XMLImporter imp = XMLImporter.getInstance();
     // if (manager != null) {
     //     imp.setAssetManager(manager);
     // }
     sav = imp.load(is);
   } catch (IOException ex) {
     Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
     ex.printStackTrace();
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException ex) {
         Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
         ex.printStackTrace();
       }
     }
   }
   return (TypeList) sav;
 }
예제 #27
0
  public void save(String gamePath, String dataName) {
    XMLExporter ex = XMLExporter.getInstance();
    OutputStream os = null;
    try {

      File daveFolder = new File(System.getProperty("user.dir") + File.separator + gamePath);
      if (!daveFolder.exists() && !daveFolder.mkdirs()) {
        Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error creating save file!");
        throw new IllegalStateException("SaveGame dataset cannot be created");
      }
      File saveFile = new File(daveFolder.getAbsolutePath() + File.separator + dataName);
      if (!saveFile.exists()) {
        if (!saveFile.createNewFile()) {
          Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error creating save file!");
          throw new IllegalStateException("SaveGame dataset cannot be created");
        }
      }
      os = new BufferedOutputStream(new FileOutputStream(saveFile));
      // os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(saveFile)));
      ex.save(this, os);
    } catch (IOException ex1) {
      Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error saving data: {0}", ex1);
      ex1.printStackTrace();
      throw new IllegalStateException("SaveGame dataset cannot be saved");
    } finally {
      try {
        if (os != null) {
          os.close();
        }
      } catch (IOException ex1) {
        Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error saving data: {0}", ex1);
        ex1.printStackTrace();
        throw new IllegalStateException("SaveGame dataset cannot be saved");
      }
    }
  }
예제 #28
0
  /**
   * Load the application information from the properties file specified by the application adaptor.
   * The resource bundle information is stored in a Map for convenient access.
   *
   * @param path Path to the source information.
   * @return The map containing the application information
   */
  private Map loadApplicationInfo(final String path) {
    Map infoMap;

    try {
      infoMap = Util.loadResourceBundle(path);
    } catch (MissingResourceException exception) {
      final String message = "No application \"About Box\" information resource found at: " + path;
      Logger.getLogger("global").log(Level.WARNING, message, exception);
      System.err.println(message);

      // substitute with default information
      infoMap = new HashMap();
      infoMap.put("name", Application.getAdaptor().getClass().getName());
    }

    return infoMap;
  }
예제 #29
0
  public UkkonenSuffixTree() {
    logger =
        Logger.getLogger(
            "edu.psu.compbio.seqcode.gse.projects.chipseq.assembler.UkkonenSuffixTree");
    isLogging = true;
    minLogLevel = Level.SEVERE;
    logger.setFilter(new LoggingFilter());
    logger.addHandler(new LoggingHandler(System.err, false));
    logger.setUseParentHandlers(false);
    logger.setLevel(Level.SEVERE);

    logger.log(Level.FINE, "Logger setup complete.");

    strings = new Vector<TreeString>();
    terminal = '$';
    root = new TreeNode(null);
    totalStringEdges = new Vector<TreeEdge>();
    extState = null;
  }
  private byte[] readBytes(InputStream in) {
    byte[] result = null;

    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] buffer = new byte[BUFFER_SIZE];
      int bytesRead = 0;
      while ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
        out.write(buffer, 0, bytesRead);
      }
      out.close();

      result = out.toByteArray();
    } catch (IOException ex) {
      Logger.getLogger(getClass()).debug("Error loading Zip entry", ex);
    }

    return (result);
  }