コード例 #1
0
ファイル: MiscUtilities.java プロジェクト: zukov/Jpicedt
 /**
  * @return an instanciation of the given content-type class name, or null if class wasn't found
  */
 public static ContentType getContentTypeFromClassName(String contentTypeClassName) {
   if (contentTypeClassName == null)
     contentTypeClassName = getAvailableContentTypes()[DEFAULT_CONTENT_TYPE_INDEX];
   ContentType ct = null;
   try {
     Class clazz = Class.forName(contentTypeClassName);
     ct = (ContentType) clazz.newInstance();
   } catch (ClassNotFoundException cnfex) {
     if (jpicedt.Log.DEBUG) cnfex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             "The pluggable content-type you asked for (class "
                 + cnfex.getLocalizedMessage()
                 + ") isn't currently installed, using default instead...",
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   } catch (Exception ex) {
     if (jpicedt.Log.DEBUG) ex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             ex.getLocalizedMessage(),
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   }
   return ct;
 }
コード例 #2
0
  /** Load the given class name with the given class loader. */
  public static Class loadClass(
      String className,
      ClassLoader loader,
      boolean throwExceptionIfNotFound,
      MetadataProject project) {
    Class candidateClass = null;

    try {
      candidateClass = loader.loadClass(className);
    } catch (ClassNotFoundException exc) {
      if (throwExceptionIfNotFound) {
        throw PersistenceUnitLoadingException.exceptionLoadingClassWhileLookingForAnnotations(
            className, exc);
      } else {
        AbstractSessionLog.getLog()
            .log(
                AbstractSessionLog.WARNING,
                "persistence_unit_processor_error_loading_class",
                exc.getClass().getName(),
                exc.getLocalizedMessage(),
                className);
      }
    } catch (NullPointerException npe) {
      // Bug 227630: If any weavable class is not found in the temporary
      // classLoader - disable weaving
      AbstractSessionLog.getLog()
          .log(
              AbstractSessionLog.WARNING,
              AbstractSessionLog.WEAVER,
              "persistence_unit_processor_error_loading_class_weaving_disabled",
              loader,
              project.getPersistenceUnitInfo().getPersistenceUnitName(),
              className);
      // Disable weaving (for 1->1 and many->1)only if the classLoader
      // returns a NPE on loadClass()
      project.disableWeaving();
    } catch (Exception exception) {
      AbstractSessionLog.getLog()
          .log(
              AbstractSessionLog.WARNING,
              AbstractSessionLog.WEAVER,
              "persistence_unit_processor_error_loading_class",
              exception.getClass().getName(),
              exception.getLocalizedMessage(),
              className);
    } catch (Error error) {
      AbstractSessionLog.getLog()
          .log(
              AbstractSessionLog.WARNING,
              AbstractSessionLog.WEAVER,
              "persistence_unit_processor_error_loading_class",
              error.getClass().getName(),
              error.getLocalizedMessage(),
              className);
      throw error;
    }

    return candidateClass;
  }
コード例 #3
0
 public boolean createApplet() {
   try {
     applet = launcherFrame.launcher.launcher.createApplet();
     return true;
   } catch (final ClassNotFoundException e) {
     MCLogger.info(e.getLocalizedMessage());
   } catch (final InstantiationException e) {
     MCLogger.info(e.getLocalizedMessage());
   } catch (final IllegalAccessException e) {
     MCLogger.info(e.getLocalizedMessage());
   }
   return false;
 }
コード例 #4
0
  /**
   * method to find all classes in a given jar
   *
   * @param resource The url to the jar file
   * @param pkgname The package name for classes found inside the base directory
   * @return The classes
   */
  private static List findClassesInJar(URL resource, String pkgname) {
    String relPath = pkgname.replace('.', '/');
    String path =
        resource
            .getPath()
            .replaceFirst("[.]jar[!].*", ".jar") // $NON-NLS-1$ //$NON-NLS-2$
            .replaceFirst("file:", ""); // $NON-NLS-1$ //$NON-NLS-2$
    try {
      path = URLDecoder.decode(path, "utf-8"); // $NON-NLS-1$
    } catch (UnsupportedEncodingException uee) {
      log.error(uee.getLocalizedMessage(), uee);
    }
    List classes = new ArrayList();
    JarFile jarFile = null;
    try {
      jarFile = new JarFile(path);
      Enumeration entries = jarFile.entries();
      while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();
        String className = null;
        if (entryName.endsWith(".class") // $NON-NLS-1$
            && entryName.startsWith(relPath)) {
          className =
              entryName
                  .replace('/', '.')
                  .replace('\\', '.')
                  .replaceAll(".class", ""); // $NON-NLS-1$ //$NON-NLS-2$

          if (className != null) {
            try {
              classes.add(Class.forName(className));
            } catch (ClassNotFoundException cnfe) {
              log.error(cnfe.getLocalizedMessage(), cnfe);
            }
          }
        }
      }
    } catch (IOException ioe) {
      log.warn(ioe.getLocalizedMessage(), ioe);
    } finally {
      if (jarFile != null) {
        try {
          jarFile.close();
        } catch (IOException e) {
          log.error(e.getLocalizedMessage(), e);
        }
      }
    }
    return classes;
  }
コード例 #5
0
ファイル: DataEntry.java プロジェクト: kwangbkim/IBAlgoTrader
 /** Constructor establishes connection to database. Connection stays open until end of program. */
 public DataEntry() {
   try {
     Class.forName("org.sqlite.JDBC");
     MyConnection =
         DriverManager.getConnection(
             "jdbc:sqlite:/Users/Kwang/Investment Management/Database/Database.sqlite");
     MyConnection.setAutoCommit(true);
   } catch (ClassNotFoundException e) {
     System.out.println(e.getLocalizedMessage());
     throw new IllegalStateException("Class.ForName failed.");
   } catch (SQLException e) {
     System.out.println(e.getLocalizedMessage());
   }
 }
コード例 #6
0
ファイル: JavaProxy.java プロジェクト: goodwill/jruby
  @JRubyMethod(frame = true)
  public IRubyObject marshal_load(ThreadContext context, IRubyObject str) {
    try {
      ByteList byteList = str.convertToString().getByteList();
      ByteArrayInputStream bais =
          new ByteArrayInputStream(
              byteList.getUnsafeBytes(), byteList.getBegin(), byteList.getRealSize());
      ObjectInputStream ois = new JRubyObjectInputStream(context.getRuntime(), bais);

      object = ois.readObject();

      return this;
    } catch (IOException ioe) {
      throw context.getRuntime().newIOErrorFromException(ioe);
    } catch (ClassNotFoundException cnfe) {
      throw context
          .getRuntime()
          .newTypeError("Class not found unmarshaling Java type: " + cnfe.getLocalizedMessage());
    }
  }
コード例 #7
0
  public void init() {
    // Make Minecraft portable ! :D
    final File workDirectory = Utils.getWorkingDirectory(launcherFrame);

    try {
      final List<Field> fields =
          JavaUtils.getFieldsWithType(
              classLoader.loadClass("net.minecraft.client.Minecraft"), File.class);
      for (final Field field : fields) {
        field.setAccessible(true);
        try {
          field.get(classLoader.loadClass("net.minecraft.client.Minecraft"));
          field.set(null, workDirectory);
        } catch (final IllegalArgumentException e) {
        } catch (final IllegalAccessException e) {
        }
      }
    } catch (final ClassNotFoundException e) {
      MCLogger.info(e.getLocalizedMessage());
    }
  }
コード例 #8
0
  protected void testDatabase(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    try {
      SetupWizardUtil.testDatabase(request);

      jsonObject.put("success", true);

      putMessage(request, jsonObject, "database-connection-was-established-sucessfully");
    } catch (ClassNotFoundException cnfe) {
      putMessage(
          request, jsonObject, "database-driver-x-is-not-present", cnfe.getLocalizedMessage());
    } catch (SQLException sqle) {
      putMessage(request, jsonObject, "database-connection-could-not-be-established");
    }

    response.setContentType(ContentTypes.APPLICATION_JSON);
    response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);

    ServletResponseUtil.write(response, jsonObject.toString());
  }
コード例 #9
0
 /**
  * Creates a tile manager from the given file or directory.
  *
  * <p>
  *
  * <ul>
  *   <li>If the argument {@linkplain Files#isRegularFile(Path, LinkOption...)} is a file} having
  *       the {@code ".serialized"} suffix, then this method deserializes the object in the given
  *       file and passes it to {@link #createFromObject(Object)}.
  *   <li>If the given argument {@linkplain Files#isDirectory(Path, LinkOption...)} is a
  *       directory}, then this method delegates to {@link #create(Path, PathMatcher,
  *       ImageReaderSpi)} which scan all image files found in the directory.
  *   <li>Otherwise an {@link IOException} is thrown.
  * </ul>
  *
  * @param file The serialized file or the directory to scan.
  * @return A tile manager created from the tiles in the given directory.
  * @throws IOException If the given file is not recognized, or an I/O operation failed.
  * @since 3.15
  */
 public TileManager[] create(final Path file) throws IOException {
   if (Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
     final String suffix = file.getFileName().toString();
     if (!suffix.endsWith(".serialized")) {
       throw new IOException(Errors.format(Errors.Keys.UnknownFileSuffix_1, suffix));
     }
     final Object manager;
     try (InputStream fin = Files.newInputStream(file);
         ObjectInputStream in = new ObjectInputStream(fin)) {
       try {
         manager = in.readObject();
       } catch (ClassNotFoundException cause) {
         InvalidClassException ex = new InvalidClassException(cause.getLocalizedMessage());
         ex.initCause(cause);
         throw ex;
       }
     }
     return setSourceFile(createFromObject(manager), file);
   } else if (Files.isDirectory(file, LinkOption.NOFOLLOW_LINKS)) {
     return create(file, null, null);
   } else {
     throw new IOException(Errors.format(Errors.Keys.NotADirectory_1, file));
   }
 }
コード例 #10
0
  @Override
  public Connection getConnection() {
    if (connection == null) {
      Properties conf = ConfigSingleton.getInstance();
      try {
        Class.forName(conf.getProperty("database.driver"));
        connection =
            DriverManager.getConnection(
                conf.getProperty("database.url"),
                conf.getProperty("database.user"),
                conf.getProperty("database.pass"));
        return connection;
      } catch (ClassNotFoundException e) {
        logger.error(e.getLocalizedMessage());
        return null;
      } catch (SQLException e) {
        logger.error(e.getLocalizedMessage());
        return null;
      }

    } else {
      return connection;
    }
  }
  private <T extends RealFieldElement<T>> RungeKuttaStepInterpolator convertInterpolator(
      final RungeKuttaFieldStepInterpolator<T> fieldInterpolator,
      final FirstOrderFieldDifferentialEquations<T> eqn) {

    RungeKuttaStepInterpolator regularInterpolator = null;
    try {

      String interpolatorName = fieldInterpolator.getClass().getName();
      String integratorName = interpolatorName.replaceAll("Field", "");
      @SuppressWarnings("unchecked")
      Class<RungeKuttaStepInterpolator> clz =
          (Class<RungeKuttaStepInterpolator>) Class.forName(integratorName);
      regularInterpolator = clz.newInstance();

      double[][] yDotArray = null;
      java.lang.reflect.Field fYD = RungeKuttaFieldStepInterpolator.class.getDeclaredField("yDotK");
      fYD.setAccessible(true);
      @SuppressWarnings("unchecked")
      T[][] fieldYDotk = (T[][]) fYD.get(fieldInterpolator);
      yDotArray = new double[fieldYDotk.length][];
      for (int i = 0; i < yDotArray.length; ++i) {
        yDotArray[i] = new double[fieldYDotk[i].length];
        for (int j = 0; j < yDotArray[i].length; ++j) {
          yDotArray[i][j] = fieldYDotk[i][j].getReal();
        }
      }
      double[] y = new double[yDotArray[0].length];

      EquationsMapper primaryMapper = null;
      EquationsMapper[] secondaryMappers = null;
      java.lang.reflect.Field fMapper =
          AbstractFieldStepInterpolator.class.getDeclaredField("mapper");
      fMapper.setAccessible(true);
      @SuppressWarnings("unchecked")
      FieldEquationsMapper<T> mapper = (FieldEquationsMapper<T>) fMapper.get(fieldInterpolator);
      java.lang.reflect.Field fStart = FieldEquationsMapper.class.getDeclaredField("start");
      fStart.setAccessible(true);
      int[] start = (int[]) fStart.get(mapper);
      primaryMapper = new EquationsMapper(start[0], start[1]);
      secondaryMappers = new EquationsMapper[mapper.getNumberOfEquations() - 1];
      for (int i = 0; i < secondaryMappers.length; ++i) {
        secondaryMappers[i] = new EquationsMapper(start[i + 1], start[i + 2]);
      }

      AbstractIntegrator dummyIntegrator =
          new AbstractIntegrator("dummy") {
            @Override
            public void integrate(ExpandableStatefulODE equations, double t) {
              Assert.fail("this method should not be called");
            }

            @Override
            public void computeDerivatives(final double t, final double[] y, final double[] yDot) {
              T fieldT = fieldInterpolator.getCurrentState().getTime().getField().getZero().add(t);
              T[] fieldY =
                  MathArrays.buildArray(
                      fieldInterpolator.getCurrentState().getTime().getField(), y.length);
              for (int i = 0; i < y.length; ++i) {
                fieldY[i] =
                    fieldInterpolator.getCurrentState().getTime().getField().getZero().add(y[i]);
              }
              T[] fieldYDot = eqn.computeDerivatives(fieldT, fieldY);
              for (int i = 0; i < yDot.length; ++i) {
                yDot[i] = fieldYDot[i].getReal();
              }
            }
          };
      regularInterpolator.reinitialize(
          dummyIntegrator,
          y,
          yDotArray,
          fieldInterpolator.isForward(),
          primaryMapper,
          secondaryMappers);

      T[] fieldPreviousY = fieldInterpolator.getPreviousState().getState();
      for (int i = 0; i < y.length; ++i) {
        y[i] = fieldPreviousY[i].getReal();
      }
      regularInterpolator.storeTime(fieldInterpolator.getPreviousState().getTime().getReal());

      regularInterpolator.shift();

      T[] fieldCurrentY = fieldInterpolator.getCurrentState().getState();
      for (int i = 0; i < y.length; ++i) {
        y[i] = fieldCurrentY[i].getReal();
      }
      regularInterpolator.storeTime(fieldInterpolator.getCurrentState().getTime().getReal());

    } catch (ClassNotFoundException cnfe) {
      Assert.fail(cnfe.getLocalizedMessage());
    } catch (InstantiationException ie) {
      Assert.fail(ie.getLocalizedMessage());
    } catch (IllegalAccessException iae) {
      Assert.fail(iae.getLocalizedMessage());
    } catch (NoSuchFieldException nsfe) {
      Assert.fail(nsfe.getLocalizedMessage());
    } catch (IllegalArgumentException iae) {
      Assert.fail(iae.getLocalizedMessage());
    }

    return regularInterpolator;
  }
コード例 #12
0
  /**
   * Checks if there is no TestNG tests for Cucumber Scenarios
   *
   * @return String error message if there is any problem. If no problem found returns null;
   */
  public static String checkTests() {
    try {
      File featuresDir = new File(RESOURCES);
      Collection<File> featuresFiles =
          FileUtils.listFiles(featuresDir, new String[] {"feature"}, true);
      ArrayList<String> featurePaths = new ArrayList<>();
      for (File featuresFile : featuresFiles) {
        String featureDir = featuresFile.getParent();
        if (!featurePaths.contains(featureDir)) {
          featurePaths.add(featureDir);
        }
      }
      List<CucumberFeature> features =
          CucumberFeature.load(new FileResourceLoader(), featurePaths, new ArrayList<>());
      for (CucumberFeature cucumberFeature : features) {
        for (CucumberTagStatement scenarioTagStatement : cucumberFeature.getFeatureElements()) {
          String featureName = cucumberFeature.getUri();
          featureName = featureName.substring(0, featureName.indexOf("."));
          if (scenarioMap.get(featureName) == null) {
            scenarioMap.put(featureName, new ArrayList<Scenario>());
          }
          String scenarioName = scenarioTagStatement.getVisualName();
          scenarioName = scenarioName.substring(scenarioName.indexOf(":") + 1).trim();
          scenarioMap.get(featureName).add(new Scenario(scenarioName));
        }
      }
      String uniqueCheck = checkTestNamesUnique(scenarioMap);
      Collection<File> testngTests =
          FileUtils.listFiles(new File(TEST_DIR), new String[] {"java"}, true);
      for (File testngTest : testngTests) {
        String classPath = testngTest.getCanonicalPath();
        classPath = classPath.substring(classPath.indexOf("java") + 5).replace(File.separator, ".");
        classPath = classPath.substring(0, classPath.lastIndexOf("."));
        Class<?> test = classLoader.loadClass(classPath);
        if (test.getAnnotation(Feature.class) != null) {
          String featureName = test.getAnnotation(Feature.class).value();
          for (Method method : test.getMethods()) {
            if (method.getAnnotation(com.legalmonkeys.test.annotation.Scenario.class) != null) {
              String scenarioName =
                  method.getAnnotation(com.legalmonkeys.test.annotation.Scenario.class).value();
              List<Scenario> scenarios = scenarioMap.get(featureName);
              for (Scenario scenario : scenarios) {
                if (scenario.getScenarioName().equals(scenarioName)) {
                  if (method.getAnnotation(org.testng.annotations.Test.class) != null) {
                    scenario.setFoundInTestNG(true);
                  }
                }
              }
            }
          }
        }
      }

      int testCount = 0;
      boolean fail = false;
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("\n");
      if (uniqueCheck != null) {
        fail = true;
        stringBuilder.append(uniqueCheck);
      }
      for (String featureName : scenarioMap.keySet()) {
        for (Scenario scenario : scenarioMap.get(featureName)) {
          testCount++;
          if (!scenario.isFoundInTestNG()) {
            stringBuilder
                .append("Feature: \"")
                .append(featureName)
                .append(".feature\". Scenario: \"")
                .append(scenario.getScenarioName())
                .append("\" TestNG test not found.")
                .append("\n");
            fail = true;
          }
        }
      }
      if (fail) {
        return stringBuilder.toString();
      }
      if (testCount == 0) {
        return "Error: 0 scenarios found.";
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      return "Error checking tests state." + e.getLocalizedMessage();
    } catch (IOException e) {
      e.printStackTrace();
      return "Error checking tests state." + e.getLocalizedMessage();
    }
    return null;
  }
コード例 #13
0
  /** Test of execute method, of class HeightMapUpdate. */
  @Test
  public void testExecute() {
    System.out.println("execute");
    HeightMapUpdate instance = null;
    com.novusradix.JavaPop.Server.HeightMap serverh;
    com.novusradix.JavaPop.Client.HeightMap clienth;
    serverh = new com.novusradix.JavaPop.Server.HeightMap(new Dimension(128, 128));
    clienth = new com.novusradix.JavaPop.Client.HeightMap(new Dimension(128, 128), null);

    serverh.up(0, 0);
    serverh.up(0, 0);
    serverh.up(5, 5);
    serverh.up(106, 7);
    serverh.up(106, 7);
    serverh.up(106, 7);
    serverh.up(106, 7);

    serverh.up(112, 25);
    serverh.up(112, 25);

    serverh.up(112, 125);
    serverh.up(112, 125);
    serverh.up(127, 127);
    serverh.up(127, 127);
    serverh.setTile(0, 0, Tile.BASALT);
    serverh.setTile(126, 126, Tile.BURNT);

    instance = serverh.GetUpdate();
    try {
      FileOutputStream fo;
      fo = new FileOutputStream("HeightMapUpdateTest.dat");
      ObjectOutputStream oos;

      oos = new ObjectOutputStream(fo);

      oos.writeObject(instance);
      oos.close();
      fo.close();

      instance = null;

      FileInputStream fi = new FileInputStream("HeightMapUpdateTest.dat");
      ObjectInputStream ois = new ObjectInputStream(fi);

      instance = (HeightMapUpdate) ois.readObject();
      ois.close();
      fi.close();
    } catch (ClassNotFoundException ex) {
      fail(ex.getLocalizedMessage());
    } catch (FileNotFoundException ex) {
      fail(ex.getLocalizedMessage());
    } catch (IOException ex) {
      fail(ex.getLocalizedMessage());
    }

    instance.clientMap = clienth;

    instance.texture = new HashMap<Integer, Byte>();
    instance.execute();
    assertTrue(clienth.getHeight(0, 0) == 2);
    assertTrue(clienth.getHeight(5, 5) == 1);
    assertTrue(clienth.getHeight(106, 7) == 4);
    assertTrue(clienth.getHeight(112, 25) == 2);
    assertTrue(clienth.getHeight(112, 125) == 2);
  }
コード例 #14
0
ファイル: Invoice.java プロジェクト: metasfresh/metasfresh
  /**
   * Invoke the form VCreateFromPackage
   *
   * @param ctx context
   * @param WindowNo window no
   * @param mTab tab
   * @param mField field
   * @param value value
   * @return null or error message
   */
  public String createFrom(
      final Properties ctx,
      final int WindowNo,
      final GridTab mTab,
      final GridField mField,
      final Object value) {

    final I_C_Invoice invoice = InterfaceWrapperHelper.create(mTab, I_C_Invoice.class);
    if (invoice.getC_Invoice_ID() <= 0) {
      return "";
    }
    final I_C_DocType dt = invoice.getC_DocTypeTarget();

    if (!Constants.DOCBASETYPE_AEInvoice.equals(dt.getDocBaseType())
        || !CommissionConstants.COMMISSON_INVOICE_DOCSUBTYPE_CORRECTION.equals(
            dt.getDocSubType())) {
      // nothing to do
      final IDocumentPA docPA = Services.get(IDocumentPA.class);
      final I_C_DocType dtCorr =
          docPA.retrieve(
              ctx,
              invoice.getAD_Org_ID(),
              Constants.DOCBASETYPE_AEInvoice,
              CommissionConstants.COMMISSON_INVOICE_DOCSUBTYPE_CORRECTION,
              true,
              null);
      if (dtCorr != null) {
        final String msg =
            Msg.getMsg(
                ctx, MSG_INVOICECORR_CREATEFROM_WRONG_DOCTYPE_1P, new Object[] {dtCorr.getName()});
        return msg;
      } else {
        throw new AdempiereException(
            "Missing C_DocType with DocBaseType='"
                + Constants.DOCBASETYPE_AEInvoice
                + "' and DocSubType='"
                + CommissionConstants.COMMISSON_INVOICE_DOCSUBTYPE_CORRECTION
                + "'");
      }
    }

    final String swingclassname = "de.metas.commission.form.VCreateCorrections";
    final String zkclassname = "not.yet.implemented";
    final String classname;
    if (Ini.isClient()) {
      classname = swingclassname;
    } else {
      classname = zkclassname;
      return "";
    }

    ICreateFrom cf = null;
    Class cl;
    try {
      if (Ini.isClient()) {
        cl = Class.forName(classname);
      } else {
        cl = Thread.currentThread().getContextClassLoader().loadClass(classname);
      }
    } catch (final ClassNotFoundException e) {
      log.error(e.getLocalizedMessage(), e);
      return e.getLocalizedMessage();
    }
    if (cl != null) {
      try {
        java.lang.reflect.Constructor<? extends ICreateFrom> ctor =
            cl.getConstructor(I_C_Invoice.class, int.class);
        cf = ctor.newInstance(invoice, WindowNo);
      } catch (Throwable e) {
        log.error(e.getLocalizedMessage(), e);
        return e.getLocalizedMessage();
      }
    }

    if (cf != null) {
      if (cf.isInitOK()) {
        cf.showWindow();
        cf.closeWindow();
        mTab.dataRefresh();
      } else cf.closeWindow();
    }

    return "";
  } // createShippingPackages
コード例 #15
0
  public fileBackupProgram(JFrame frame) {
    super(new BorderLayout());
    this.frame = frame;

    errorDialog = new CustomDialog(frame, "Please enter a new name for the error log", this);
    errorDialog.pack();

    moveDialog = new CustomDialog(frame, "Please enter a new name for the move log", this);
    moveDialog.pack();

    printer = new FilePrinter();
    timers = new ArrayList<>();
    log = new JTextArea(5, 20);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);
    Object obj;
    copy = true;
    listModel = new DefaultListModel();
    // destListModel = new DefaultListModel();
    directoryList = new directoryStorage();

    // Create a file chooser
    fc = new JFileChooser();

    // Create the menu bar.
    menuBar = new JMenuBar();

    // Build the first menu.
    menu = new JMenu("File");
    menu.getAccessibleContext()
        .setAccessibleDescription("The only menu in this program that has menu items");
    menuBar.add(menu);

    editError = new JMenuItem("Save Error Log As...");
    editError
        .getAccessibleContext()
        .setAccessibleDescription("Change the name of the error log file");
    editError.addActionListener(new ErrorListener());
    menu.add(editError);

    editMove = new JMenuItem("Save Move Log As...");
    editMove
        .getAccessibleContext()
        .setAccessibleDescription("Change the name of the move log file");
    editMove.addActionListener(new MoveListener());
    menu.add(editMove);

    exit = new JMenuItem("Exit");
    exit.getAccessibleContext().setAccessibleDescription("Exit the Program");
    exit.addActionListener(new CloseListener());
    menu.add(exit);
    frame.setJMenuBar(menuBar);
    // Uncomment one of the following lines to try a different
    // file selection mode.  The first allows just directories
    // to be selected (and, at least in the Java look and feel,
    // shown).  The second allows both files and directories
    // to be selected.  If you leave these lines commented out,
    // then the default mode (FILES_ONLY) will be used.
    //
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    // fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    openButton = new JButton(openString);
    openButton.setActionCommand(openString);
    openButton.addActionListener(new OpenListener());

    destButton = new JButton(destString);
    destButton.setActionCommand(destString);
    destButton.addActionListener(new DestListener());

    // Create the save button.  We use the image from the JLF
    // Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton(saveString);
    saveButton.setActionCommand(saveString);
    saveButton.addActionListener(new SaveListener());

    URL imageURL = getClass().getResource(greenButtonIcon);
    ImageIcon greenSquare = new ImageIcon(imageURL);
    startButton = new JButton("Start", greenSquare);
    startButton.setSize(60, 20);
    startButton.setHorizontalTextPosition(AbstractButton.LEADING);
    startButton.setActionCommand("Start");
    startButton.addActionListener(new StartListener());

    imageURL = getClass().getResource(redButtonIcon);
    ImageIcon redSquare = new ImageIcon(imageURL);
    stopButton = new JButton("Stop", redSquare);
    stopButton.setSize(60, 20);
    stopButton.setHorizontalTextPosition(AbstractButton.LEADING);
    stopButton.setActionCommand("Stop");
    stopButton.addActionListener(new StopListener());

    copyButton = new JRadioButton("Copy");
    copyButton.setActionCommand("Copy");
    copyButton.setSelected(true);
    copyButton.addActionListener(new RadioListener());

    moveButton = new JRadioButton("Move");
    moveButton.setActionCommand("Move");
    moveButton.addActionListener(new RadioListener());

    ButtonGroup group = new ButtonGroup();
    group.add(copyButton);
    group.add(moveButton);

    // For layout purposes, put the buttons in a separate panel

    JPanel optionPanel = new JPanel();

    GroupLayout layout = new GroupLayout(optionPanel);
    optionPanel.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout.createSequentialGroup().addComponent(copyButton).addComponent(moveButton));
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(copyButton)
                    .addComponent(moveButton)));

    JPanel buttonPanel = new JPanel(); // use FlowLayout

    layout = new GroupLayout(buttonPanel);
    buttonPanel.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(openButton)
                    .addComponent(optionPanel))
            .addComponent(destButton)
            .addComponent(startButton)
            .addComponent(stopButton)
        // .addComponent(saveButton)
        );
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(openButton)
                    .addComponent(destButton)
                    .addComponent(startButton)
                    .addComponent(stopButton)
                // .addComponent(saveButton)
                )
            .addComponent(optionPanel));

    buttonPanel.add(optionPanel);
    /*
    buttonPanel.add(openButton);
    buttonPanel.add(destButton);
    buttonPanel.add(startButton);
    buttonPanel.add(stopButton);
    buttonPanel.add(saveButton);
    buttonPanel.add(listLabel);
    buttonPanel.add(copyButton);
    buttonPanel.add(moveButton);
    */
    destButton.setEnabled(false);
    startButton.setEnabled(false);
    stopButton.setEnabled(false);

    // Add the buttons and the log to this panel.

    // add(logScrollPane, BorderLayout.CENTER);

    JLabel listLabel = new JLabel("Monitored Directory:");
    listLabel.setLabelFor(list);

    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    list.setVisibleRowCount(8);
    JScrollPane listScrollPane = new JScrollPane(list);
    JPanel listPane = new JPanel();
    listPane.setLayout(new BorderLayout());

    listPane.add(listLabel, BorderLayout.PAGE_START);
    listPane.add(listScrollPane, BorderLayout.CENTER);

    listSelectionModel = list.getSelectionModel();
    listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
    // monitored, destination, waitInt, check

    destination = new JLabel("Destination Directory: ");

    waitField = new JFormattedTextField();
    // waitField.setValue(240);
    waitField.setEditable(false);
    waitField.addPropertyChangeListener(new FormattedTextListener());

    waitInt = new JLabel("Wait Interval (in minutes)");
    // waitInt.setLabelFor(waitField);

    checkField = new JFormattedTextField();
    checkField.setSize(1, 10);
    // checkField.setValue(60);
    checkField.setEditable(false);
    checkField.addPropertyChangeListener(new FormattedTextListener());

    check = new JLabel("Check Interval (in minutes)");
    // check.setLabelFor(checkField);

    fireButton = new JButton(fireString);
    fireButton.setActionCommand(fireString);
    fireButton.addActionListener(new FireListener());

    JPanel fieldPane = new JPanel();
    // fieldPane.add(destField);
    layout = new GroupLayout(fieldPane);
    fieldPane.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(waitInt)
                    .addComponent(check))
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(waitField, 60, 60, 60)
                    .addComponent(checkField, 60, 60, 60)));

    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(waitInt)
                    .addComponent(waitField))
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(check)
                    .addComponent(checkField)));

    JPanel labelPane = new JPanel();

    labelPane.setLayout(new BorderLayout());

    labelPane.add(destination, BorderLayout.PAGE_START);
    labelPane.add(fieldPane, BorderLayout.CENTER);

    layout = new GroupLayout(labelPane);
    labelPane.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(destination)
                    .addComponent(fieldPane)));

    layout.setVerticalGroup(
        layout.createSequentialGroup().addComponent(destination).addComponent(fieldPane));
    // labelPane.add(destination);
    // labelPane.add(fieldPane);

    try {
      // Read from disk using FileInputStream
      FileInputStream f_in = new FileInputStream(LOG_DIRECTORY + "\\save.data");

      // Read object using ObjectInputStream
      ObjectInputStream obj_in = new ObjectInputStream(f_in);

      // Read an object
      directoryList = (directoryStorage) obj_in.readObject();
      ERROR_LOG_NAME = (String) obj_in.readObject();
      MOVE_LOG_NAME = (String) obj_in.readObject();

      if (ERROR_LOG_NAME instanceof String) {
        printer.changeErrorLogName(ERROR_LOG_NAME);
      }

      if (MOVE_LOG_NAME instanceof String) {
        printer.changeMoveLogName(MOVE_LOG_NAME);
      }

      if (directoryList instanceof directoryStorage) {
        System.out.println("found object");
        // directoryList = (directoryStorage) obj;

        Iterator<Directory> directories = directoryList.getDirectories();
        Directory d;
        while (directories.hasNext()) {
          d = directories.next();

          try {
            listModel.addElement(d.getDirectory().toRealPath());
          } catch (IOException x) {
            printer.printError(x.toString());
          }

          int index = list.getSelectedIndex();
          if (index == -1) {
            list.setSelectedIndex(0);
          }

          index = list.getSelectedIndex();
          Directory dir = directoryList.getDirectory(index);

          destButton.setEnabled(true);
          checkField.setValue(dir.getInterval());
          waitField.setValue(dir.getWaitInterval());
          checkField.setEditable(true);
          waitField.setEditable(true);

          // directoryList.addNewDirectory(d);
          // try {
          // listModel.addElement(d.getDirectory().toString());
          // } catch (IOException x) {
          // printer.printError(x.toString());
          // }

          // timer = new Timer();
          // timer.schedule(new CopyTask(d.directory, d.destination, d.getWaitInterval(), printer,
          // d.copy), 0, d.getInterval());
        }

      } else {
        System.out.println("did not find object");
      }
      obj_in.close();
    } catch (ClassNotFoundException x) {
      printer.printError(x.getLocalizedMessage());
      System.err.format("Unable to read");
    } catch (IOException y) {
      printer.printError(y.getLocalizedMessage());
    }

    // Layout the text fields in a panel.

    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));

    buttonPane.add(fireButton);
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    add(buttonPanel, BorderLayout.PAGE_START);
    add(listPane, BorderLayout.LINE_START);
    // add(destListScrollPane, BorderLayout.CENTER);

    add(fieldPane, BorderLayout.LINE_END);
    add(labelPane, BorderLayout.CENTER);
    add(buttonPane, BorderLayout.PAGE_END);
  }