Пример #1
0
 @Override
 public void updateContents() {
     GeneralSettings st = JsonConfig.create(GeneralSettings.class);
     downloadFolder.setText(org.appwork.storage.config.JsonConfig.create(GeneralSettings.class).getDefaultDownloadFolder());
     autoCRC.setSelected(st.isHashCheckEnabled());
     simpleContainer.setSelected(st.isAutoOpenContainerAfterDownload());
     this.remove.setValue(config.getCleanupAfterDownloadAction());
     this.ifFileExists.setValue(config.getIfFileExistsAction());
 }
 public OldRAFDownload(PluginForHost plugin, DownloadLink downloadLink, Request request) throws IOException, PluginException {
     downloadLink.setDownloadInstance(this);
     connectionHandler = new ManagedThrottledConnectionHandler(downloadLink);
     this.downloadLink = downloadLink;
     this.plugin = plugin;
     logger = plugin.getLogger();
     linkStatus = downloadLink.getLinkStatus();
     linkStatus.setStatusText(_JDT._.download_connection_normal());
     browser = plugin.getBrowser().cloneBrowser();
     requestTimeout = JsonConfig.create(GeneralSettings.class).getHttpConnectTimeout();
     readTimeout = JsonConfig.create(GeneralSettings.class).getHttpReadTimeout();
     this.request = request;
 }
    /**
     * 
     * @param downloadLink
     *            downloadlink der geladne werden soll (wird zur darstellung verwendet)
     * @param request
     *            Verbindung die geladen werden soll
     * @param b
     *            Resumefaehige verbindung
     * @param i
     *            max chunks. fuer negative werte wirden die chunks aus der config verwendet. Bsp: -3 : Min(3,Configwert);
     * @return
     * @throws IOException
     * @throws PluginException
     */
    public static DownloadInterface download(DownloadLink downloadLink, Request request, boolean b, int i) throws IOException, PluginException {
        /* disable gzip, because current downloadsystem cannot handle it correct */
        request.getHeaders().put("Accept-Encoding", null);
        RAFDownload dl = new RAFDownload(downloadLink.getLivePlugin(), downloadLink, request);
        PluginForHost plugin = downloadLink.getLivePlugin();
        if (plugin != null) plugin.setDownloadInterface(dl);
        if (i == 0) {
            dl.setChunkNum(JsonConfig.create(GeneralSettings.class).getMaxChunksPerFile());
        } else {
            dl.setChunkNum(i < 0 ? Math.min(i * -1, JsonConfig.create(GeneralSettings.class).getMaxChunksPerFile()) : i);
        }
        dl.setResume(b);
        return dl;

    }
  /**
   * Create a new i nstance of AuthenticationController. This is a singleton class. Access the only
   * existing instance by using {@link #getInstance()}.
   */
  private AuthenticationController() {
    logger = LogController.getInstance().getLogger(AuthenticationController.class.getName());
    config = JsonConfig.create(AuthenticationControllerSettings.class);
    CopyOnWriteArrayList<AuthenticationInfo> list = cleanup(config.getList());
    if (list == null) {
      list = new CopyOnWriteArrayList<AuthenticationInfo>();
    }
    this.list = list;
    ShutdownController.getInstance()
        .addShutdownEvent(
            new ShutdownEvent() {
              @Override
              public void onShutdown(final ShutdownRequest shutdownRequest) {
                config.setList(AuthenticationController.this.list);
              }

              @Override
              public long getMaxDuration() {
                return 0;
              }

              @Override
              public String toString() {
                return "ShutdownEvent: Save AuthController";
              }
            });
  }
Пример #5
0
    private synchronized void updateFilter() {

        String filterRegex = this.getText();
        boolean enabled = filterRegex.length() > 0;

        if (enabled) {

            java.util.List<Pattern> list = new ArrayList<Pattern>();
            try {
                if (JsonConfig.create(GeneralSettings.class).isFilterRegex()) {
                    list.add(LinkgrabberFilterRuleWrapper.createPattern(filterRegex, true));
                } else {
                    String[] filters = filterRegex.split("\\|");
                    for (String filter : filters) {
                        list.add(LinkgrabberFilterRuleWrapper.createPattern(filter, false));
                    }

                }
                filterPatterns = list;

                updaterFilter();

            } catch (final Throwable e) {
                Log.exception(e);
            }
        } else {
            filterPatterns = null;
            updaterFilter();
        }
        updaterFilter();

    }
  /**
   * @param frame
   * @return
   */
  private LocationStorage createConfig(final Window frame) {
    String storageID = RememberRelativeLocator.class.getSimpleName() + "-" + this.getID(frame);
    if (storageID.length() > 128) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < storageID.length(); i++) {
        char c = storageID.charAt(i);
        switch (c) {
          case 'U':
          case 'E':
          case 'I':
          case 'O':
          case 'A':
          case 'J':
          case 'u':
          case 'e':
          case 'i':
          case 'o':
          case 'a':
          case 'j':
            continue;
          default:
            sb.append(c);
        }
      }
      storageID = sb.toString();
    }
    if (storageID.length() > 128) {
      storageID = RememberRelativeLocator.class.getSimpleName() + "-" + Hash.getMD5(storageID);
    }

    return JsonConfig.create(Application.getResource("cfg/" + storageID), LocationStorage.class);
  }
Пример #7
0
public class CFG_CBH {
  public static void main(String[] args) {
    ConfigUtils.printStaticMappings(CaptchaBrotherHoodSettings.class);
  }

  // Static Mappings for interface
  // org.jdownloader.captcha.v2.solver.captchabrotherhood.CaptchaBrotherHoodSettings
  public static final CaptchaBrotherHoodSettings CFG =
      JsonConfig.create(CaptchaBrotherHoodSettings.class);
  public static final StorageHandler<CaptchaBrotherHoodSettings> SH =
      (StorageHandler<CaptchaBrotherHoodSettings>) CFG._getStorageHandler();
  // let's do this mapping here. If we map all methods to static handlers, access is faster, and we
  // get an error on init if mappings are
  // wrong.

  public static final BooleanKeyHandler ENABLED =
      SH.getKeyHandler("Enabled", BooleanKeyHandler.class);

  public static final StringKeyHandler USER = SH.getKeyHandler("User", StringKeyHandler.class);

  public static final StringKeyHandler PASS = SH.getKeyHandler("Pass", StringKeyHandler.class);

  public static final StringKeyHandler BLACK_LIST =
      SH.getKeyHandler("BlackList", StringKeyHandler.class);

  public static final StringKeyHandler WHITE_LIST =
      SH.getKeyHandler("WhiteList", StringKeyHandler.class);
}
Пример #8
0
    public ChunksEditor(boolean b) {
        super(b);

        add(lbl = getLbl(_GUI._.ChunksEditor_ChunksEditor_(), NewTheme.I().getIcon("chunks", 18)));
        config = JsonConfig.create(GeneralSettings.class);
        spinner = new ExtSpinner(new ConfigIntSpinnerModel(org.jdownloader.settings.staticreferences.CFG_GENERAL.MAX_CHUNKS_PER_FILE));
        try {
            ((DefaultEditor) spinner.getEditor()).getTextField().addFocusListener(new FocusListener() {

                @Override
                public void focusLost(FocusEvent e) {
                }

                @Override
                public void focusGained(FocusEvent e) {
                    // requires invoke later!
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            ((DefaultEditor) spinner.getEditor()).getTextField().selectAll();
                        }
                    });

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            // too much fancy Casting.
        }
        // new SpinnerNumberModel(config.getMaxChunksPerFile(), 1, 20, 1)

        add(spinner, "height " + Math.max(spinner.getEditor().getPreferredSize().height, 20) + "!,width " + getEditorWidth() + "!");
    }
    public ParalellDownloadsEditor(boolean b) {
        super(b);
        config = JsonConfig.create(GeneralSettings.class);
        add(getLbl(_GUI._.ParalellDownloadsEditor_ParalellDownloadsEditor_(), NewTheme.I().getIcon("paralell", 18)));
        spinner = new ExtSpinner(new ConfigIntSpinnerModel(org.jdownloader.settings.staticreferences.CFG_GENERAL.MAX_SIMULTANE_DOWNLOADS));
        try {
            ((DefaultEditor) spinner.getEditor()).getTextField().addFocusListener(new FocusListener() {

                @Override
                public void focusLost(FocusEvent e) {
                }

                @Override
                public void focusGained(FocusEvent e) {
                    // requires invoke later!
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            ((DefaultEditor) spinner.getEditor()).getTextField().selectAll();
                        }
                    });

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            // too much fancy Casting.
        }
        add(spinner, "height " + Math.max(spinner.getEditor().getPreferredSize().height, 20) + "!,width " + getEditorWidth() + "!");
    }
 @Override
 public void actionPerformed(ActionEvent e) {
     //
     JsonConfig.create(GraphicalUserInterfaceSettings.class).setConfigViewVisible(true);
     JDGui.getInstance().setContent(ConfigurationView.getInstance(), true);
     ConfigurationView.getInstance().setSelectedSubPanel(AccountManagerSettings.class);
     ConfigurationView.getInstance().getSubPanel(AccountManagerSettings.class).getAccountManager().getTabbedPane().setSelectedIndex(1);
 }
    /**
     * private constructor for FilePackage, sets created timestamp and downloadDirectory
     */
    private FilePackage() {
        downloadDirectory = org.appwork.storage.config.JsonConfig.create(GeneralSettings.class).getDefaultDownloadFolder();
        created = System.currentTimeMillis();
        /* till refactoring is complete */
        this.downloadLinkList = new ArrayList<DownloadLink>();
        setName(null);

    }
 /**
  * set the download folder for this FilePackage
  * 
  * @param subFolder
  */
 public void setDownloadDirectory(String folder) {
     if (StringUtils.isEmpty(folder)) {
         folder = org.appwork.storage.config.JsonConfig.create(GeneralSettings.class).getDefaultDownloadFolder();
     } /*else if (!CrossSystem.isAbsolutePath(folder)) {
         Log.L.severe("FilePackage: setDownloadDirectory only allows absolute pathes! Using default one!");
         folder = org.appwork.storage.config.JsonConfig.create(GeneralSettings.class).getDefaultDownloadFolder();
     }*/
     downloadDirectory = folder;
 }
Пример #13
0
 @Override
 public void save() {
     GeneralSettings st = JsonConfig.create(GeneralSettings.class);
     st.setDefaultDownloadFolder(downloadFolder.getText());
     st.setHashCheckEnabled(autoCRC.isSelected());
     st.setAutoOpenContainerAfterDownload(simpleContainer.isSelected());
     config.setCleanupAfterDownloadAction(remove.getValue());
     config.setIfFileExistsAction(this.ifFileExists.getValue());
 }
Пример #14
0
    public void doOptimization(ReconnectResult res, ProcessCallBackAdapter processCallBackAdapter) throws InterruptedException {
        java.util.List<ReconnectResult> list = new ArrayList<ReconnectResult>();
        list.add(res);
        // int failed = 0;
        int success = 1;
        long duration = res.getSuccessDuration();
        long offlineDuration = res.getOfflineDuration();
        long maxOfflineDuration = res.getOfflineDuration();
        long maxSuccessDuration = res.getSuccessDuration();
        long startTime = res.getStartTime();
        for (int i = 1; i < JsonConfig.create(ReconnectConfig.class).getOptimizationRounds(); i++) {
            processCallBackAdapter.setProgress(this, (i * 100) / JsonConfig.create(ReconnectConfig.class).getOptimizationRounds());
            ReconnectResult r;
            try {
                r = validate();
            } catch (ReconnectException e) {
                e.printStackTrace();
                r = createReconnectResult();
            }
            list.add(r);
            if (r.isSuccess()) {

                success++;
                duration += r.getSuccessDuration();
                startTime = r.getStartTime();
                offlineDuration = Math.min(offlineDuration, r.getOfflineDuration());
                maxOfflineDuration = Math.max(maxOfflineDuration, r.getOfflineDuration());
                maxSuccessDuration = Math.max(maxSuccessDuration, r.getSuccessDuration());
            }

        }
        duration /= success;
        double successRate = success / (double) JsonConfig.create(ReconnectConfig.class).getOptimizationRounds();
        // increase successduration if successrate is lower than 1.0 (100%)
        res.setAverageSuccessDuration((long) (duration / successRate));
        res.setMaxOfflineDuration(maxOfflineDuration * 2);
        res.setMaxSuccessDuration(maxSuccessDuration * 4);
        res.setOfflineTime(offlineDuration);
        res.setStartTime(startTime);

    }
Пример #15
0
public class CFG_CHAT {
  public static void main(String[] args) {
    ConfigUtils.printStaticMappings(
        ChatConfig.class,
        "Application.getResource(\"cfg/\" + "
            + ChatExtension.class.getSimpleName()
            + ".class.getName())");
  }

  // Static Mappings for interface org.jdownloader.extensions.chat.ChatConfig
  public static final ChatConfig CFG =
      JsonConfig.create(
          Application.getResource("cfg/" + ChatExtension.class.getName()), ChatConfig.class);
  public static final StorageHandler<ChatConfig> SH =
      (StorageHandler<ChatConfig>) CFG._getStorageHandler();
  // let's do this mapping here. If we map all methods to static handlers, access is faster, and we
  // get an error on init if mappings are
  // wrong.
  // true
  public static final BooleanKeyHandler FRESH_INSTALL =
      SH.getKeyHandler("FreshInstall", BooleanKeyHandler.class);
  // false
  public static final BooleanKeyHandler GUI_ENABLED =
      SH.getKeyHandler("GuiEnabled", BooleanKeyHandler.class);
  // true
  public static final BooleanKeyHandler USER_COLOR_ENABLED =
      SH.getKeyHandler("UserColorEnabled", BooleanKeyHandler.class);
  // 6667
  public static final IntegerKeyHandler IRC_PORT =
      SH.getKeyHandler("IrcPort", IntegerKeyHandler.class);
  // irc.freenode.net
  public static final StringKeyHandler IRC_SERVER =
      SH.getKeyHandler("IrcServer", StringKeyHandler.class);
  // null
  public static final StringKeyHandler PERFORM_ON_LOGIN_COMMANDS =
      SH.getKeyHandler("PerformOnLoginCommands", StringKeyHandler.class);
  // false
  public static final BooleanKeyHandler ENABLED =
      SH.getKeyHandler("Enabled", BooleanKeyHandler.class);
  // #jDownloader
  public static final StringKeyHandler CHANNEL =
      SH.getKeyHandler("Channel", StringKeyHandler.class);
  // null
  public static final StringKeyHandler NICK = SH.getKeyHandler("Nick", StringKeyHandler.class);
  // null
  public static final StringKeyHandler CHANNEL_LANGUAGE =
      SH.getKeyHandler("ChannelLanguage", StringKeyHandler.class);
  // 0
  public static final IntegerKeyHandler USER_LIST_POSITION =
      SH.getKeyHandler("UserListPosition", IntegerKeyHandler.class);
}
Пример #16
0
  /** @param args */
  public static void main(String[] args) {
    ListConfig cfg = JsonConfig.create(ListConfig.class);

    double[] da = cfg.getDoubleArray();
    Double[] dwa = cfg.getDoubleWrapperArray();
    ArrayList<Double> dwl = cfg.getDoubleWrapperList();
    cfg.setDoubleArray(new double[] {9.8, 7.6});
    cfg.setDoubleWrapperArray(new Double[] {7.6, 5.4});
    dwl.add(Math.random());
    cfg.setDoubleWrapperList(dwl);

    System.out.println(da);
    System.out.println(dwa);
    System.out.println("SUCCESSFUL");
    System.exit(1);
  }
Пример #17
0
 protected HashResult getHashResult(Downloadable downloadable, File file)
     throws InterruptedException {
   if (JsonConfig.create(GeneralSettings.class).isHashCheckEnabled()
       && downloadable.isHashCheckEnabled()) {
     AtomicBoolean hashCheckLock = new AtomicBoolean(false);
     synchronized (HASHCHECK_QEUEU) {
       HASHCHECK_QEUEU.add(hashCheckLock);
       hashCheckLock.set(HASHCHECK_QEUEU.indexOf(hashCheckLock) != 0);
     }
     try {
       if (hashCheckLock.get()) {
         synchronized (hashCheckLock) {
           if (hashCheckLock.get()) {
             final PluginProgress hashProgress =
                 new HashCheckPluginProgress(null, Color.YELLOW.darker().darker(), null);
             try {
               downloadable.addPluginProgress(hashProgress);
               hashCheckLock.wait();
             } finally {
               downloadable.removePluginProgress(hashProgress);
             }
           }
         }
       }
       final HashInfo hashInfo = downloadable.getHashInfo();
       final HashResult hashResult = downloadable.getHashResult(hashInfo, file);
       return hashResult;
     } finally {
       synchronized (HASHCHECK_QEUEU) {
         boolean callNext = HASHCHECK_QEUEU.indexOf(hashCheckLock) == 0;
         HASHCHECK_QEUEU.remove(hashCheckLock);
         if (HASHCHECK_QEUEU.size() > 0 && callNext) {
           hashCheckLock = HASHCHECK_QEUEU.get(0);
         } else {
           hashCheckLock = null;
         }
       }
       if (hashCheckLock != null) {
         synchronized (hashCheckLock) {
           hashCheckLock.set(false);
           hashCheckLock.notifyAll();
         }
       }
     }
   }
   return null;
 }
Пример #18
0
public class CFG_DBC {
  public static void main(String[] args) {
    ConfigUtils.printStaticMappings(DeathByCaptchaSettings.class);
  }

  // Static Mappings for interface org.jdownloader.captcha.v2.solver.dbc.DeathByCaptchaSettings
  public static final DeathByCaptchaSettings CFG = JsonConfig.create(DeathByCaptchaSettings.class);
  public static final StorageHandler<DeathByCaptchaSettings> SH =
      (StorageHandler<DeathByCaptchaSettings>) CFG._getStorageHandler();
  // let's do this mapping here. If we map all methods to static handlers, access is faster, and we
  // get an error on init if mappings are
  // wrong.

  /** Captcha BlackList for hoster */
  public static final StringKeyHandler BLACK_LIST =
      SH.getKeyHandler("BlackList", StringKeyHandler.class);

  /** Max. Captchas Parallel */
  public static final IntegerKeyHandler THREADPOOL_SIZE =
      SH.getKeyHandler("ThreadpoolSize", IntegerKeyHandler.class);

  /** Captcha WhiteList for hoster */
  public static final StringKeyHandler WHITE_LIST =
      SH.getKeyHandler("WhiteList", StringKeyHandler.class);

  /** Active the deathbycaptcha.eu service */
  public static final BooleanKeyHandler ENABLED =
      SH.getKeyHandler("Enabled", BooleanKeyHandler.class);

  /** Activate the Captcha Feedback */
  public static final BooleanKeyHandler FEED_BACK_SENDING_ENABLED =
      SH.getKeyHandler("FeedBackSendingEnabled", BooleanKeyHandler.class);

  /** Your deathbycaptcha.eu Username */
  public static final StringKeyHandler USER_NAME =
      SH.getKeyHandler("UserName", StringKeyHandler.class);

  /** Your deathbycaptcha.eu Password */
  public static final StringKeyHandler PASSWORD =
      SH.getKeyHandler("Password", StringKeyHandler.class);
}
  public java.util.List<ReconnectResult> autoFind(final ProcessCallBack feedback)
      throws InterruptedException {

    StatsManager.I().track("reconnectAutoFind/start");
    final java.util.List<ReconnectResult> scripts = new ArrayList<ReconnectResult>();

    for (final RouterPlugin plg : ReconnectPluginController.this.plugins) {
      if (Thread.currentThread().isInterrupted()) {
        throw new InterruptedException();
      }
      if (plg instanceof UPNPRouterPlugin || plg instanceof LiveHeaderReconnect) {
        try {

          feedback.setStatus(plg, null);

          java.util.List<ReconnectResult> founds = plg.runDetectionWizard(feedback);

          if (founds != null) {
            scripts.addAll(founds);
          }
          if (scripts.size() > 0) {
            break;
          }
        } catch (InterruptedException e) {
          throw e;
        } catch (Exception e) {

        }
      }
    }
    if (scripts.size() > 0) {
      HashMap<String, String> map = new HashMap<String, String>();
      map.put("plg", scripts.get(0).getInvoker().getPlugin().getID());
      StatsManager.I().track("reconnectAutoFind/success", map);
    } else {
      StatsManager.I().track("reconnectAutoFind/failed");
    }
    if (JsonConfig.create(ReconnectConfig.class).getOptimizationRounds() > 1
        && scripts.size() > 0) {
      int i = 1;
      long bestTime = Long.MAX_VALUE;
      long optiduration = 0;
      for (ReconnectResult found : scripts) {

        bestTime = Math.min(bestTime, found.getSuccessDuration());
        optiduration +=
            found.getSuccessDuration()
                * (JsonConfig.create(ReconnectConfig.class).getOptimizationRounds() - 1)
                * 1.5;
      }
      try {

        Dialog.getInstance()
            .showConfirmDialog(
                0,
                _GUI.T.AutoDetectAction_actionPerformed_dooptimization_title(),
                _GUI.T.AutoDetectAction_actionPerformed_dooptimization_msg(
                    scripts.size(),
                    TimeFormatter.formatMilliSeconds(optiduration, 0),
                    TimeFormatter.formatMilliSeconds(bestTime, 0)),
                new AbstractIcon(IconKey.ICON_OK, 32),
                _GUI.T.AutoDetectAction_run_optimization(),
                _GUI.T.AutoDetectAction_skip_optimization());
        feedback.setProgress(this, 0);
        for (int ii = 0; ii < scripts.size(); ii++) {
          ReconnectResult found = scripts.get(ii);
          feedback.setStatusString(
              this, _GUI.T.AutoDetectAction_run_optimize(found.getInvoker().getName()));
          final int step = ii;
          found.optimize(
              new ProcessCallBackAdapter() {

                public void setProgress(Object caller, int percent) {
                  feedback.setProgress(
                      caller, (step) * (100 / scripts.size()) + percent / scripts.size());
                }

                public void setStatusString(Object caller, String string) {
                  feedback.setStatusString(caller, _GUI.T.AutoDetectAction_run_optimize(string));
                }
              });
        }
      } catch (DialogNoAnswerException e) {

      }
    }
    try {
      Collections.sort(
          scripts,
          new Comparator<ReconnectResult>() {

            public int compare(ReconnectResult o1, ReconnectResult o2) {
              return new Long(o1.getAverageSuccessDuration())
                  .compareTo(new Long(o2.getAverageSuccessDuration()));
            }
          });
    } catch (final Throwable e) {

      org.appwork.utils.logging2.extmanager.LoggerFactory.getDefaultLogger().log(e);
    }
    return scripts;
  }
 private LinkedList<FilePackage> load(File file) {
   synchronized (SAVELOADLOCK) {
     LinkedList<FilePackage> ret = null;
     if (file != null && file.exists()) {
       ZipIOReader zip = null;
       try {
         zip = new ZipIOReader(file);
         /* lets restore the FilePackages from Json */
         HashMap<Integer, FilePackage> map = new HashMap<Integer, FilePackage>();
         DownloadControllerStorable dcs = null;
         InputStream is = null;
         for (ZipEntry entry : zip.getZipFiles()) {
           try {
             if (entry.getName().matches("^\\d+$")) {
               int packageIndex = Integer.parseInt(entry.getName());
               is = zip.getInputStream(entry);
               byte[] bytes = IO.readStream((int) entry.getSize(), is);
               String json = new String(bytes, "UTF-8");
               bytes = null;
               FilePackageStorable storable =
                   JSonStorage.stringToObject(json, new TypeRef<FilePackageStorable>() {}, null);
               json = null;
               if (storable != null) {
                 map.put(packageIndex, storable._getFilePackage());
               } else {
                 throw new WTFException("restored a null FilePackageStorable");
               }
             } else if ("extraInfo".equalsIgnoreCase(entry.getName())) {
               is = zip.getInputStream(entry);
               byte[] bytes = IO.readStream((int) entry.getSize(), is);
               String json = new String(bytes, "UTF-8");
               bytes = null;
               dcs =
                   JSonStorage.stringToObject(
                       json, new TypeRef<DownloadControllerStorable>() {}, null);
               json = null;
             }
           } finally {
             try {
               is.close();
             } catch (final Throwable e) {
             }
           }
         }
         /* sort positions */
         java.util.List<Integer> positions = new ArrayList<Integer>(map.keySet());
         Collections.sort(positions);
         /* build final ArrayList of FilePackages */
         java.util.List<FilePackage> ret2 = new ArrayList<FilePackage>(positions.size());
         for (Integer position : positions) {
           ret2.add(map.get(position));
         }
         if (dcs != null
             && JsonConfig.create(GeneralSettings.class).isConvertRelativePathesJDRoot()) {
           try {
             String oldRootPath = dcs.getRootPath();
             if (!StringUtils.isEmpty(oldRootPath)) {
               String newRoot = JDUtilities.getJDHomeDirectoryFromEnvironment().getAbsolutePath();
               /*
                * convert pathes relative to JDownloader root,only in jared version
                */
               for (FilePackage pkg : ret2) {
                 if (!CrossSystem.isAbsolutePath(pkg.getDownloadDirectory())) {
                   /* no need to convert relative pathes */
                   continue;
                 }
                 String pkgPath = getDownloadDirectory(pkg).getAbsolutePath();
                 if (pkgPath.startsWith(oldRootPath + "/")) {
                   /*
                    * folder is inside JDRoot, lets update it
                    */
                   String restPath = pkgPath.substring(oldRootPath.length());
                   String newPath = new File(newRoot, restPath).getAbsolutePath();
                   pkg.setDownloadDirectory(newPath);
                 }
               }
             }
           } catch (final Throwable e) {
             /* this method can throw exceptions, eg in SVN */
             logger.log(e);
           }
         }
         map = null;
         positions = null;
         ret = new LinkedList<FilePackage>(ret2);
       } catch (final Throwable e) {
         logger.log(e);
       } finally {
         try {
           zip.close();
         } catch (final Throwable e) {
         }
       }
     }
     return ret;
   }
 }
 /**
  * saves List of FilePackages to given File as ZippedJSon
  *
  * @param packages
  * @param file
  */
 private boolean save(java.util.List<FilePackage> packages, File file) throws IOException {
   synchronized (SAVELOADLOCK) {
     List<File> availableDownloadLists = null;
     if (file == null) {
       availableDownloadLists = getAvailableDownloadLists();
       if (availableDownloadLists.size() > 0) {
         String counter =
             new Regex(availableDownloadLists.get(0).getName(), "downloadList(\\d+)\\.zip")
                 .getMatch(0);
         long count = 1;
         if (counter != null) {
           count = Long.parseLong(counter) + 1;
         }
         file = Application.getResource("cfg/downloadList" + count + ".zip");
       }
       if (file == null) file = Application.getResource("cfg/downloadList.zip");
     }
     if (packages != null && file != null) {
       if (file.exists()) {
         if (file.isDirectory()) throw new IOException("File " + file + " is a directory");
         if (file.delete() == false) throw new IOException("Could not delete file " + file);
       } else {
         if (file.getParentFile().exists() == false && file.getParentFile().mkdirs() == false)
           throw new IOException("Could not create parentFolder for file " + file);
       }
       /* prepare formatter(001,0001...) for package filenames in zipfiles */
       String format = "%02d";
       if (packages.size() >= 10) {
         format = String.format("%%0%dd", (int) Math.log10(packages.size()) + 1);
       }
       boolean deleteFile = true;
       ZipIOWriter zip = null;
       FileOutputStream fos = null;
       try {
         fos = new FileOutputStream(file);
         zip = new ZipIOWriter(new BufferedOutputStream(fos, 32767));
         int index = 0;
         for (FilePackage pkg : packages) {
           /* convert FilePackage to JSon */
           FilePackageStorable storable = new FilePackageStorable(pkg);
           String string = JSonStorage.toString(storable);
           storable = null;
           byte[] bytes = string.getBytes("UTF-8");
           string = null;
           zip.addByteArry(bytes, true, "", String.format(format, (index++)));
         }
         DownloadControllerStorable dcs = new DownloadControllerStorable();
         try {
           /*
            * set current RootPath of JDownloader, so we can update it when user moves JDownloader folder
            */
           dcs.setRootPath(JDUtilities.getJDHomeDirectoryFromEnvironment().getAbsolutePath());
         } catch (final Throwable e) {
           /* the method above can throw exceptions, eg in SVN */
           logger.log(e);
         }
         zip.addByteArry(JSonStorage.toString(dcs).getBytes("UTF-8"), true, "", "extraInfo");
         /* close ZipIOWriter */
         zip.close();
         deleteFile = false;
         try {
           int keepXOld = Math.max(JsonConfig.create(GeneralSettings.class).getKeepXOldLists(), 0);
           if (availableDownloadLists != null && availableDownloadLists.size() > keepXOld) {
             availableDownloadLists =
                 availableDownloadLists.subList(keepXOld, availableDownloadLists.size());
             for (File oldDownloadList : availableDownloadLists) {
               logger.info(
                   "Delete outdated DownloadList: "
                       + oldDownloadList
                       + " "
                       + oldDownloadList.delete());
             }
           }
         } catch (final Throwable e) {
           logger.log(e);
         }
         return true;
       } catch (final Throwable e) {
         logger.log(e);
       } finally {
         try {
           fos.close();
         } catch (final Throwable e) {
         }
         if (deleteFile && file.exists()) {
           file.delete();
         }
       }
     }
     return false;
   }
 }
Пример #22
0
  /**
   * @param <T>
   * @param class1
   * @return
   */
  public static <T extends ConfigInterface> T create(final Class<T> configInterface) {

    return JsonConfig.create(
        Application.getResource("cfg/" + configInterface.getName()), configInterface);
  }
Пример #23
0
/** @author thomas */
@PlainStorage
public interface MyInterface extends ConfigInterface {
  public static final MyInterface CFG = JsonConfig.create(MyInterface.class);

  @SuppressWarnings("unchecked")
  public static final StorageHandler<MyInterface> SH =
      (StorageHandler<MyInterface>) CFG._getStorageHandler();

  @DefaultBooleanValue(value = true)
  public boolean getB2();

  @DefaultBooleanArrayValue(value = {true, false, true})
  public boolean[] getBooleanArray();

  @DefaultByteValue(value = 0)
  public byte getByte();

  @DefaultByteArrayValue(value = {1, 2, 3})
  public byte[] getByteArray();

  @DefaultFactory(DefaultD.class)
  public double getD();

  @DefaultDoubleArrayValue(value = {1.0d, 2.0d, 3.0d})
  public double[] getDoubleArray();

  public void setDoubleArray(double[] arr);

  @DefaultEnumValue(value = "A")
  public Type getEnum();

  @DefaultFloatValue(value = 0.5f)
  public float getFloat();

  @DefaultFloatArrayValue(value = {1.0f, 2.0f, 3.0f})
  public Float[] getFloatArray();

  /** @return */
  public ArrayList<TestObject> getGenericList();

  public static final IntegerKeyHandler INT =
      CFG._getStorageHandler().getKeyHandler("Int", IntegerKeyHandler.class);

  @DefaultIntValue(value = 2)
  @SpinnerValidator(min = 1, max = 10, step = 1)
  public int getInt();

  @DefaultIntArrayValue(value = {1, 2, 3})
  public int[] getIntArray();

  @DefaultLongValue(value = 0l)
  public long getL();

  @DefaultLongArrayValue(value = {1, 2, 3})
  public long[] getLongArray();

  // @DefaultJsonObject(value = "{\"a\":5}")
  public TestObject getObject();

  public HashSet<String> getSet();

  public void setSet(HashSet<String> set);

  public ArrayList<TestObject[]> getStorableArrayList();

  // public Object[] getObjectArray();
  @DefaultStringValue(value = "test")
  public String getString();

  @DefaultStringArrayValue(value = {"test", "testb"})
  public String[] getStringArray();

  @DefaultEnumArrayValue(
      value = {"org.appwork.storage.config.test.Type.A", "org.appwork.storage.config.test.Type.B"})
  public Type[] getTypeArray();

  /** @param list */
  @CryptedStorage(
      key = {
        0x01, 0x02, 0x11, 0x01, 0x01, 0x54, 0x01, 0x01, 0x01, 0x01, 0x12, 0x01, 0x01, 0x01, 0x22,
        0x01
      })
  public void setGenericList(ArrayList<TestObject> list);

  public void setInt(int i);

  /** @param is */
  public void setIntArray(int[] is);

  class DefFac extends AbstractDefaultFactory<TestObject> {

    @Override
    public TestObject getDefaultValue() {
      // TODO Auto-generated method stub
      return null;
    }
  }

  class DefValid extends AbstractValidator<TestObject> {

    /*
     * (non-Javadoc)
     *
     * @see
     * org.appwork.storage.config.annotations.AbstractValidator#validate
     * (java.lang.Object)
     */
    @Override
    public void validate(TestObject object) throws ValidationException {
      System.out.println("CHECK " + object);
    }
  }

  /** @param o */
  @DefaultFactory(org.appwork.storage.config.test.MyInterface.DefFac.class)
  @ValidatorFactory(org.appwork.storage.config.test.MyInterface.DefValid.class)
  public void setObject(TestObject o);

  @DefaultFactory(MyDefaultCreator.class)
  public ArrayList<Integer> getDefault();
}
Пример #24
0
 public ChallengeDialogHandler(DomainInfo instance, T captchaChallenge2) {
   this.host = instance;
   this.captchaChallenge = captchaChallenge2;
   config = JsonConfig.create(CaptchaSettings.class);
   logger = JDGui.getInstance().getLogger();
   dialogHandler =
       new DialogHandler() {
         @Override
         public <T> T showDialog(final AbstractDialog<T> dialog)
             throws DialogClosedException, DialogCanceledException {
           // synchronized (this) {
           try {
             dialog.forceDummyInit();
             boolean silentModeActive = JDGui.getInstance().isSilentModeActive();
             if (silentModeActive) {
               // switch (CFG_SILENTMODE.CFG.getOnCaptchaDuringSilentModeAction()) {
               // case WAIT_IN_BACKGROUND_UNTIL_WINDOW_GETS_FOCUS_OR_TIMEOUT
               // // Cancel dialog
               // throw new DialogClosedException(Dialog.RETURN_CLOSED);
               // }
               // if this is the edt, we should not block it.. NEVER
               if (!SwingUtilities.isEventDispatchThread()) {
                 // block dialog calls... the shall appear as soon as isSilentModeActive is false.
                 long countdown = -1;
                 if (dialog.isCountdownFlagEnabled()) {
                   long countdownDif = dialog.getCountdown();
                   countdown = System.currentTimeMillis() + countdownDif;
                 }
                 if (countdown < 0
                     && CFG_SILENTMODE.CFG.getOnCaptchaDuringSilentModeAction()
                         == CaptchaDuringSilentModeAction
                             .WAIT_IN_BACKGROUND_UNTIL_WINDOW_GETS_FOCUS_OR_TIMEOUT) {
                   countdown =
                       System.currentTimeMillis()
                           + CFG_SILENTMODE.ON_DIALOG_DURING_SILENT_MODE_ACTION_TIMEOUT.getValue();
                 }
                 JDGui.getInstance().flashTaskbar();
                 while (JDGui.getInstance().isSilentModeActive()) {
                   if (countdown > 0) {
                     Thread.sleep(
                         Math.min(Math.max(1, countdown - System.currentTimeMillis()), 250));
                     if (System.currentTimeMillis() > countdown) {
                       dialog.onTimeout();
                       // clear interrupt
                       Thread.interrupted();
                       throw new DialogCanceledException(dialog.getReturnmask());
                     }
                   } else {
                     Thread.sleep(250);
                   }
                 }
               }
             }
           } catch (InterruptedException e) {
             throw new DialogClosedException(Dialog.RETURN_INTERRUPT, e);
           } catch (DialogCanceledException e) {
             throw e;
           } catch (Exception e) {
             logger.log(e);
           }
           dialog.resetDummyInit();
           new EDTRunner() {
             @Override
             protected void runInEDT() {
               dialog.displayDialog();
             }
           }.waitForEDT();
           return null;
           // }
         }
       };
 }
 private ReconnectPluginController() {
   this.storage = JsonConfig.create(ReconnectConfig.class);
   this.scan();
 }
    protected void onChunksReady() {
        logger.info("Close connections if they are not closed yet");
        try {
            for (RAFChunk c : this.getChunks()) {
                c.closeConnections();
            }
        } finally {
            logger.info("Close File. Let AV programs run");
            try {
                outputPartFile.close();
            } catch (Throwable e) {
            }
        }
        downloadLink.getLinkStatus().setStatusText(null);
        if (!handleErrors()) return;
        try {
            File part = new File(outputCompleteFile.getAbsolutePath() + ".part");
            /* lets check the hash/crc/sfv */
            if (JsonConfig.create(GeneralSettings.class).isHashCheckEnabled()) {
                synchronized (HASHCHECKLOCK) {
                    /*
                     * we only want one hashcheck running at the same time. many finished downloads can cause heavy diskusage here
                     */
                    String hash = null;
                    String type = null;
                    Boolean success = null;

                    // StatsManager
                    if ((hash = downloadLink.getMD5Hash()) != null && hash.length() == 32) {
                        /* MD5 Check */
                        type = "MD5";
                        downloadLink.getLinkStatus().setStatusText(_JDT._.system_download_doCRC2("MD5"));
                        String hashFile = Hash.getMD5(part);
                        success = hash.equalsIgnoreCase(hashFile);
                    } else if (!StringUtils.isEmpty(hash = downloadLink.getSha1Hash()) && hash.length() == 40) {
                        /* SHA1 Check */
                        type = "SHA1";
                        downloadLink.getLinkStatus().setStatusText(_JDT._.system_download_doCRC2("SHA1"));
                        String hashFile = Hash.getSHA1(part);
                        success = hash.equalsIgnoreCase(hashFile);
                    } else if ((hash = new Regex(downloadLink.getName(), ".*?\\[([A-Fa-f0-9]{8})\\]").getMatch(0)) != null) {
                        type = "CRC32";
                        String hashFile = Long.toHexString(Hash.getCRC32(part));
                        success = hash.equalsIgnoreCase(hashFile);
                    } else {
                        DownloadLink sfv = null;
                        synchronized (downloadLink.getFilePackage()) {
                            for (DownloadLink dl : downloadLink.getFilePackage().getChildren()) {
                                if (dl.getFileOutput().toLowerCase().endsWith(".sfv")) {
                                    sfv = dl;
                                    break;
                                }
                            }
                        }
                        /* SFV File Available, lets use it */
                        if (sfv != null && sfv.getLinkStatus().hasStatus(LinkStatus.FINISHED)) {
                            String sfvText = IO.readFileToString(new File(sfv.getFileOutput()));
                            if (sfvText != null) {
                                /* Delete comments */
                                sfvText = sfvText.replaceAll(";(.*?)[\r\n]{1,2}", "");
                                if (sfvText != null && sfvText.contains(downloadLink.getName())) {
                                    downloadLink.getLinkStatus().setStatusText(_JDT._.system_download_doCRC2("CRC32"));
                                    type = "CRC32";
                                    String crc = Long.toHexString(Hash.getCRC32(part));
                                    success = new Regex(sfvText, downloadLink.getName() + "\\s*" + crc).matches();
                                }
                            }
                        }
                    }
                    if (success != null) {
                        hashCheckFinished(type, success);
                    }
                }
            }

            boolean renameOkay = false;
            int retry = 5;
            /* rename part file to final filename */
            while (retry > 0) {
                /* first we try normal rename method */
                if ((renameOkay = part.renameTo(outputCompleteFile)) == true) {
                    break;
                }
                /* this may fail because something might lock the file */
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    break;
                }
                retry--;
            }
            /* Fallback */
            if (renameOkay == false) {
                /* rename failed, lets try fallback */
                logger.severe("Could not rename file " + part + " to " + outputCompleteFile);
                logger.severe("Try copy workaround!");
                try {
                    //DISKSPACECHECK freeSpace = DownloadWatchDog.getInstance().checkFreeDiskSpace(part.getParentFile(), part.length());
                    //if (DISKSPACECHECK.FAILED.equals(freeSpace)) throw new Throwable("not enough diskspace free to copy part to complete file");
                    IO.copyFile(part, outputCompleteFile);
                    renameOkay = true;
                    part.deleteOnExit();
                    part.delete();
                } catch (Throwable e) {
                    LogSource.exception(logger, e);
                    /* error happened, lets delete complete file */
                    if (outputCompleteFile.exists() && outputCompleteFile.length() != part.length()) {
                        outputCompleteFile.delete();
                        outputCompleteFile.deleteOnExit();
                    }
                }
                if (!renameOkay) {
                    logger.severe("Copy workaround: :(");
                    error(LinkStatus.ERROR_LOCAL_IO, _JDT._.system_download_errors_couldnotrename());
                } else {
                    logger.severe("Copy workaround: :)");
                }
            }
            if (renameOkay) {

                /*if (StatsManager.I().isEnabled()) {
                    long speed = 0;
                    long startDelay = -1;
                    try {
                        speed = (outputCompleteFile.length() - Math.max(0, sizeBefore)) / ((System.currentTimeMillis() - getStartTimeStamp()) / 1000);
                    } catch (final Throwable e) {
                        LogSource.exception(logger, e);
                    }
                    try {
                        startDelay = System.currentTimeMillis() - downloadLink.getDownloadLinkController().getStartTimestamp();
                    } catch (final Throwable e) {
                        LogSource.exception(logger, e);
                    }
                    StatsManager.I().onFileDownloaded(outputCompleteFile, downloadLink, speed, startDelay, getChunks().size());
                }*/

                /* save absolutepath as final location property */
                downloadLink.setProperty(DownloadLink.PROPERTY_FINALLOCATION, outputCompleteFile.getAbsolutePath());
                Date last = TimeFormatter.parseDateString(connection.getHeaderField("Last-Modified"));
                if (last != null && JsonConfig.create(GeneralSettings.class).isUseOriginalLastModified()) {
                    /* set original lastModified timestamp */
                    outputCompleteFile.setLastModified(last.getTime());
                } else {
                    /* set current timestamp as lastModified timestamp */
                    outputCompleteFile.setLastModified(System.currentTimeMillis());
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception", e);
            addException(e);
        }
    }