예제 #1
0
  @Override
  public void run(Storage config, AbstractMyJDClientForDesktopJVM api) throws Exception {
    final String session = config.get("session", "");
    final SessionInfo sessioninfo = JSonStorage.restoreFromString(session, SessionInfo.class);
    api.setSessionInfo(sessioninfo);

    api.reconnect();
    Dialog.getInstance()
        .showMessageDialog(
            "Done. New SessionToken: " + JSonStorage.serializeToJson(api.getSessionInfo()));
  }
예제 #2
0
  /**
   * Sorts the model with the column's rowsorter
   *
   * @param column
   * @param sortOrderToggle
   */
  public void sort(final ExtColumn<E> column, final boolean sortOrderToggle) {
    this.sortColumn = column;
    this.sortOrderToggle = sortOrderToggle;

    try {
      JSonStorage.getStorage("ExtTableModel_" + this.modelID).put("SORTCOLUMN", column.getID());
      JSonStorage.getStorage("ExtTableModel_" + this.modelID).put("SORTORDER", sortOrderToggle);
    } catch (final Exception e) {
      Log.exception(e);
    }
    Collections.sort(this.getTableData(), column.getRowSorter(sortOrderToggle));
  }
예제 #3
0
  /**
   * Stores a value.
   *
   * @param key
   * @param value
   */
  public void setProperty(final String key, final Object value) {
    if (value == null) {
      storage.remove(key);
    } else {
      if (value instanceof Boolean) {
        storage.put(key, (Boolean) value);
      } else if (value instanceof Long) {
        storage.put(key, (Long) value);
      } else if (value instanceof Integer) {
        storage.put(key, (Integer) value);
      } else if (value instanceof Byte) {
        storage.put(key, (Byte) value);
      } else if (value instanceof String) {
        storage.put(key, (String) value);
      } else if (value instanceof Double) {
        storage.put(key, (Double) value);
      } else {
        System.out.println("Write " + path + "." + key + (plain ? ".json" : ".ejs"));
        JSonStorage.saveTo(getObjectKey(key), value);
      }

      // throw new RuntimeException("Type " + value.getClass() +
      // " not supported");
      // }
    }
  }
  private void pushToBuffer(Subscriber subscriber, EventObject eventObject) {
    synchronized (buffer) {
      ChannelCollector col = collectors.get(subscriber.getSubscriptionID());
      if (col == null) {

        // Closed channel?
        return;
      }
      Object dls = eventObject.getEventdata();
      if (dls != null && dls instanceof HashMap) {
        if (col != null) {
          HashMap<String, Object> copy = new HashMap<String, Object>((HashMap) dls);

          if (!col.updateDupeCache(eventObject.getEventid() + "." + copy.remove("uuid"), copy)) {
            return;
          }
        }
      }
      System.out.println(
          getClass().getName()
              + "FireEvent -> "
              + subscriber.getSubscriptionID()
              + " : "
              + eventObject.getEventid()
              + " - "
              + JSonStorage.serializeToJson(dls));

      List<EventObject> lst = this.buffer.get(subscriber);
      if (lst == null) {
        lst = new ArrayList<EventObject>();
        buffer.put(subscriber, lst);
      }
      lst.add(eventObject);
    }
  }
  private void load(String pkg) {
    try {
      URL infourl =
          Application.getRessourceURL(JD_CONTROLLING_RECONNECT_PLUGINS + pkg + "/info.json");
      if (infourl == null) {
        LogController.CL().finer("Could not load Reconnect Plugin " + pkg);
        return;
      }

      ReconnectPluginInfo plgInfo =
          JSonStorage.restoreFromString(
              IO.readURLToString(infourl), new TypeRef<ReconnectPluginInfo>() {}, null);
      if (plgInfo == null) {
        LogController.CL().finer("Could not load Reconnect Plugin (no info.json)" + pkg);
        return;
      }
      Class<?> clazz =
          getClass()
              .getClassLoader()
              .loadClass(
                  JD_CONTROLLING_RECONNECT_PLUGINS.replace("/", ".")
                      + pkg
                      + "."
                      + plgInfo.getClassName());
      for (RouterPlugin plg : plugins) {
        if (plg.getClass() == clazz) {
          LogController.CL().finer("Dupe found: " + pkg);
          return;
        }
      }
      plugins.add((RouterPlugin) clazz.newInstance());
    } catch (Throwable e) {
      LogController.CL().log(e);
    }
  }
예제 #6
0
  /**
   * Create a new instance of ExtensionController. This is a singleton class. Access the only
   * existing instance by using {@link #getInstance()}.
   */
  private ExtensionController() {

    map = new HashMap<Class<AbstractExtension<?>>, AbstractExtensionWrapper>();
    list = new ArrayList<AbstractExtensionWrapper>();
    JDController.getInstance()
        .addControlListener(
            new ControlListener() {

              public void controlEvent(ControlEvent event) {
                if (event.getEventID() == ControlEvent.CONTROL_INIT_COMPLETE) {
                  JDController.getInstance().removeControlListener(this);

                  for (AbstractExtensionWrapper plg : list) {
                    if (plg._getExtension() != null && plg._getExtension().getGUI() != null) {

                      plg._getExtension().getGUI().restore();
                    }
                  }
                }
              }
            });
    cacheFile = Application.getResource("tmp/extensioncache/cache.json");
    cache =
        JSonStorage.restoreFrom(
            cacheFile,
            true,
            null,
            new TypeRef<HashMap<String, AbstractExtensionWrapper>>() {},
            new HashMap<String, AbstractExtensionWrapper>());
  }
예제 #7
0
 public void load() {
   cacheChanged = false;
   loadUnpacked();
   loadJared();
   if (cacheChanged) {
     JSonStorage.saveTo(cacheFile, cache);
   }
 }
예제 #8
0
 public <E> E getGenericProperty(final String key, final E def) {
   if (def == null || Clazz.isPrimitive(def.getClass())) {
     return storage.get(key, def);
   } else {
     System.out.println("Read " + path + "." + key + (plain ? ".json" : ".ejs"));
     return JSonStorage.restoreFromFile(
         new File(path + "." + key + (plain ? ".json" : ".ejs")), def);
   }
 }
예제 #9
0
 /**
  * Sets the column visible or invisible. This information is stored in database interface for
  * cross session use.
  *
  * @param column
  * @param visible
  */
 public void setVisible(final int column, final boolean visible) {
   final ExtColumn<E> col = this.getExtColumn(column);
   try {
     JSonStorage.getStorage("ExtTableModel_" + this.modelID)
         .put("VISABLE_COL_" + col.getName(), visible);
   } catch (final Exception e) {
     Log.exception(e);
   }
 }
예제 #10
0
 /**
  * Retrieves visible information form database interface to determine if the column is visible or
  * not
  *
  * @param column
  * @return
  */
 public boolean isVisible(final int column) {
   final ExtColumn<E> col = this.getExtColumn(column);
   try {
     return JSonStorage.getStorage("ExtTableModel_" + this.modelID)
         .get("VISABLE_COL_" + col.getName(), col.isDefaultVisible());
   } catch (final Exception e) {
     Log.exception(e);
     return true;
   }
 }
예제 #11
0
  /**
   * Create a new ExtTableModel.
   *
   * @param database databaseinterface instance to store internal tabledata across sessions
   * @param id storageID.
   */
  public ExtTableModel(final String id) {
    super();
    this.extComponentRowHighlighters = new ArrayList<ExtComponentRowHighlighter<E>>();
    this.modelID = id;
    this.initColumns();

    final String columnId =
        JSonStorage.getStorage("ExtTableModel_" + this.modelID)
            .get("SORTCOLUMN", this.columns.get(0).getID());
    for (final ExtColumn<E> col : this.columns) {
      if (col.getID().equals(columnId)) {
        this.sortColumn = col;
        break;
      }
    }
    this.sortOrderToggle =
        JSonStorage.getStorage("ExtTableModel_" + this.modelID).get("SORTORDER", false);
    this.refreshSort();
  }
예제 #12
0
  public Object getProperty(final String key, final Object def) {
    try {
      if (storage.hasProperty(key)) {
        return this.storage.get(key, (String) null);
      } else if (getObjectKey(key).exists()) {

        if (def != null) {
          return JSonStorage.restoreFromFile(getObjectKey(key), def);
        } else {
          TypeRef<?> ref = getType(key);
          System.out.println("Read " + path + "." + key + (plain ? ".json" : ".ejs"));
          if (ref == null) {
            Log.exception(new Exception(path + ".json." + key + " type missing"));
          }
          return JSonStorage.restoreFrom(getObjectKey(key), true, null, ref, null);
        }
      }
    } catch (Throwable e) {
      e.printStackTrace();
    }
    return def;
  }
예제 #13
0
    protected <Typo> Typo call(String command, TypeRef<Typo> type, Object... objects) throws IOException {
        StringBuilder sb = new StringBuilder();

        if (objects != null) {
            for (int i = 0; i < objects.length; i++) {
                sb.append(i == 0 ? "" : "&");

                sb.append(Encoding.urlEncode(JSonStorage.serializeToJson(objects[i])));
            }
        }
        Browser br = new Browser();
        br.setAllowedResponseCodes(200, 503, 500, 400);
        String ret = br.postPageRaw(HTTP_BASE + command, sb.toString());
        if (br.getRequest().getHttpConnection().getResponseCode() == 503) {
            throw new RetryIOException(ret);
        }
        if (br.getRequest().getHttpConnection().getResponseCode() == 400) {
            throw new BadQueryException(ret);
        }
        if (type == null) {
            return null;
        }
        return JSonStorage.restoreFromString(ret, type);
    }
예제 #14
0
  @Deprecated
  public static JSonWrapper get(String string) {
    synchronized (MAP) {
      Storage json = JSonStorage.getPlainStorage(string);

      JSonWrapper ret = MAP.get(json);
      if (ret == null) {
        ret = new JSonWrapper(json);
        if (json.size() == 0) {
          convert(string, ret);
        }
        MAP.put(json, ret);
      }
      return ret;
    }
  }
예제 #15
0
 @Override
 public String toString() {
   return JSonStorage.toString(this);
 }
예제 #16
0
  @Override
  public Void run() {
    // let's write an info file. and delete if after extraction. this wy we have infosfiles if the
    // extraction crashes jd
    crashLog =
        new ExtractLogFileWriter(
            archive.getName(),
            archive.getFirstArchiveFile().getFilePath(),
            archive.getFactory().getID()) {
          @Override
          public void write(String string) {
            super.write(string);
            logger.info(string);
          }
        };
    try {
      fireEvent(ExtractionEvent.Type.START);
      archive.onStartExtracting();
      crashLog.write("Date: " + new Date());
      crashLog.write("Start Extracting");
      crashLog.write("Extension Setup: \r\n" + extension.getSettings().toString());

      crashLog.write("Archive Setup: \r\n" + JSonStorage.toString(archive.getSettings()));
      extractor.setCrashLog(crashLog);
      logger.info("Start unpacking of " + archive.getFirstArchiveFile().getFilePath());

      for (ArchiveFile l : archive.getArchiveFiles()) {
        if (!new File(l.getFilePath()).exists()) {
          crashLog.write("File missing: " + l.getFilePath());
          logger.info("Could not find archive file " + l.getFilePath());
          archive.addCrcError(l);
        }
      }
      if (archive.getCrcError().size() > 0) {
        fireEvent(ExtractionEvent.Type.FILE_NOT_FOUND);
        crashLog.write("Failed");
        return null;
      }

      if (gotKilled()) {
        return null;
      }
      crashLog.write("Prepare");
      if (extractor.prepare()) {
        extractToFolder = extension.getFinalExtractToFolder(archive);
        crashLog.write("Extract To: " + extractToFolder);
        if (archive.isProtected()) {
          crashLog.write("Archive is Protected");
          if (!StringUtils.isEmpty(archive.getFinalPassword())
              && !checkPassword(archive.getFinalPassword(), false)) {
            /* open archive with found pw */
            logger.info(
                "Password " + archive.getFinalPassword() + " is invalid, try to find correct one");
            archive.setFinalPassword(null);
          }
          if (StringUtils.isEmpty(archive.getFinalPassword())) {
            crashLog.write("Try to find password");
            /* pw unknown yet */
            List<String> spwList = archive.getSettings().getPasswords();
            if (spwList != null) {
              passwordList.addAll(spwList);
            }
            passwordList.addAll(archive.getFactory().getGuessedPasswordList(archive));
            passwordList.add(archive.getName());
            java.util.List<String> pwList = extractor.config.getPasswordList();
            if (pwList == null) {
              pwList = new ArrayList<String>();
            }
            passwordList.addAll(pwList);
            fireEvent(ExtractionEvent.Type.START_CRACK_PASSWORD);
            logger.info("Start password finding for " + archive);
            String correctPW = null;
            for (String password : passwordList) {
              if (password == null) {
                continue;
              }
              if (gotKilled()) {
                return null;
              }
              crashLog.write("Try Password: "******"Found password: \"" + password + "\"");
                break;
              } else {
                // try trimmed password
                String trimmed = password.trim();
                if (trimmed.length() != password.length()) {
                  password = trimmed;
                  if (checkPassword(
                      password, extension.getSettings().isPasswordFindOptimizationEnabled())) {
                    correctPW = password;
                    crashLog.write("Found password: \"" + password + "\"");
                    break;
                  }
                }
              }
            }

            if (correctPW == null) {
              fireEvent(ExtractionEvent.Type.PASSWORD_NEEDED_TO_CONTINUE);
              crashLog.write("Ask for password");
              logger.info("Found no password in passwordlist " + archive);
              if (gotKilled()) {
                return null;
              }
              if (!checkPassword(archive.getFinalPassword(), false)) {
                fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
                logger.info("No password found for " + archive);
                crashLog.write("No password found or given");
                crashLog.write("Failed");
                return null;
              }
            }
            fireEvent(ExtractionEvent.Type.PASSWORD_FOUND);
            logger.info("Found password for " + archive + "->" + archive.getFinalPassword());
          }
          if (StringUtils.isNotEmpty(archive.getFinalPassword())) {
            extension.addPassword(archive.getFinalPassword());
          }
        }
        final DiskSpaceReservation extractReservation =
            new DiskSpaceReservation() {

              @Override
              public long getSize() {
                final long completeSize =
                    Math.max(getCompleteBytes(), archive.getContentView().getTotalSize());
                long ret = completeSize - getProcessedBytes();
                return ret;
              }

              @Override
              public File getDestination() {
                return getExtractToFolder();
              }
            };
        DISKSPACERESERVATIONRESULT reservationResult =
            DownloadWatchDog.getInstance()
                .getSession()
                .getDiskSpaceManager()
                .checkAndReserve(extractReservation, this);
        try {
          switch (reservationResult) {
            case FAILED:
              logger.info(
                  "Not enough harddisk space for unpacking archive "
                      + archive.getFirstArchiveFile().getFilePath());
              crashLog.write("Diskspace Problem: " + reservationResult);
              crashLog.write("Failed");
              fireEvent(ExtractionEvent.Type.NOT_ENOUGH_SPACE);
              return null;
            case INVALIDDESTINATION:
              logger.warning("Could use create subpath");
              crashLog.write("Could use create subpath: " + getExtractToFolder());
              crashLog.write("Failed");
              fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
              return null;
          }
          fireEvent(ExtractionEvent.Type.OPEN_ARCHIVE_SUCCESS);
          if (!getExtractToFolder().exists()) {
            if (!FileCreationManager.getInstance().mkdir(getExtractToFolder())) {
              logger.warning("Could not create subpath");
              crashLog.write("Could not create subpath: " + getExtractToFolder());
              crashLog.write("Failed");
              fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
              return null;
            }
          }
          logger.info("Execute unpacking of:" + archive);
          logger.info("Extract to " + getExtractToFolder());
          crashLog.write(
              "Use Password: "******"|PW Protected:"
                  + archive.isProtected()
                  + ":"
                  + archive.isPasswordRequiredToOpen());
          ScheduledExecutorService scheduler = null;
          try {
            crashLog.write("Start Extracting " + extractor);
            scheduler = DelayedRunnable.getNewScheduledExecutorService();
            timer =
                scheduler.scheduleWithFixedDelay(
                    new Runnable() {
                      public void run() {
                        fireEvent(ExtractionEvent.Type.EXTRACTING);
                      }
                    },
                    1,
                    1,
                    TimeUnit.SECONDS);
            extractor.extract(this);
          } finally {
            crashLog.write("Extractor Returned");
            if (timer != null) {
              timer.cancel(false);
            }
            if (scheduler != null) {
              scheduler.shutdown();
            }
            extractor.close();
            if (extractor.getLastAccessedArchiveFile() != null) {
              crashLog.write("Last used File: " + extractor.getLastAccessedArchiveFile());
            }
            fireEvent(ExtractionEvent.Type.EXTRACTING);
          }
        } finally {
          DownloadWatchDog.getInstance()
              .getSession()
              .getDiskSpaceManager()
              .free(extractReservation, this);
        }
        if (gotKilled()) {
          return null;
        }
        if (extractor.getException() != null) {
          exception = extractor.getException();
          logger.log(exception);
        }
        if (exception != null) {
          crashLog.write("Exception occured: \r\n" + Exceptions.getStackTrace(exception));
        }

        crashLog.write("ExitCode: " + archive.getExitCode());
        switch (archive.getExitCode()) {
          case ExtractionControllerConstants.EXIT_CODE_SUCCESS:
            logger.info("Unpacking successful for " + archive);
            archive
                .getSettings()
                .setExtractionInfo(new ExtractionInfo(getExtractToFolder(), archive));
            crashLog.write(
                "Info: \r\n"
                    + JSonStorage.serializeToJson(
                        new ExtractionInfo(getExtractToFolder(), archive)));
            crashLog.write("Successful");
            successful = true;
            fireEvent(ExtractionEvent.Type.FINISHED);
            logger.clear();
            break;
          case ExtractionControllerConstants.EXIT_CODE_INCOMPLETE_ERROR:
            logger.warning("Archive seems to be incomplete " + archive);
            crashLog.write("Incomplete Archive");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.FILE_NOT_FOUND);
            break;
          case ExtractionControllerConstants.EXIT_CODE_CRC_ERROR:
            logger.warning("A CRC error occurred when unpacking " + archive);
            crashLog.write("CRC Error occured");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED_CRC);
            break;
          case ExtractionControllerConstants.EXIT_CODE_USER_BREAK:
            logger.info("User interrupted unpacking of " + archive);
            crashLog.write("Interrupted by User");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_CREATE_ERROR:
            logger.warning("Could not create Outputfile for" + archive);
            crashLog.write("Could not create Outputfile");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_WRITE_ERROR:
            logger.warning("Unable to write unpacked data on harddisk for " + archive);
            this.exception = new ExtractionException("Write to disk error");
            crashLog.write("Harddisk write Error");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_FATAL_ERROR:
            logger.warning("A unknown fatal error occurred while unpacking " + archive);
            crashLog.write("Unknown Fatal Error");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_WARNING:
            logger.warning("Non fatal error(s) occurred while unpacking " + archive);
            crashLog.write("Unknown Non Fatal Error");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          default:
            crashLog.write("Failed...unknown reason");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
        }
        return null;
      } else {
        crashLog.write("Failed");
        fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
      }
    } catch (Exception e) {
      logger.log(e);
      this.exception = e;
      crashLog.write("Exception occured: \r\n" + Exceptions.getStackTrace(e));
      crashLog.write("Failed");
      fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
    } finally {
      crashLog.close();
      if (!CFG_EXTRACTION.CFG.isWriteExtractionLogEnabled()) {
        crashLog.delete();
      }
      try {
        if (gotKilled()) {
          logger.info("ExtractionController has been killed");
          logger.clear();
        }
        try {
          extractor.close();
        } catch (final Throwable e) {
        }
        fireEvent(ExtractionEvent.Type.CLEANUP);
        archive.onCleanUp();
      } finally {
        logger.close();
      }
    }
    return null;
  }
 /**
  * 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;
   }
 }
예제 #18
0
  @Override
  public ArrayList<DownloadLink> decryptIt(
      final CryptedLink param, final ProgressController progress) throws Exception {
    synchronized (LOCK) {
      PROGRESS = progress;
      final ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
      final String parameter = correctCryptedLink(param.toString());
      setBrowserExclusive();
      br.setFollowRedirects(true);
      br.getHeaders().put("User-Agent", UA);

      /* Handle Captcha and/or password */
      handleCaptchaAndPassword(parameter, param);
      if (!br.getURL().contains("relink.us/")) {
        try {
          validateLastChallengeResponse();
        } catch (final Throwable e) {
        }
        logger.info("Link offline: " + parameter);
        return decryptedLinks;
      }
      if (br.containsHTML("<title>404</title>")) {
        logger.info("Link offline: " + parameter);
        return decryptedLinks;
      }
      if (ALLFORM != null && ALLFORM.getRegex("password").matches()) {
        throw new DecrypterException(DecrypterException.PASSWORD);
      }
      if (ALLFORM != null && ALLFORM.getRegex("captcha").matches()) {
        throw new DecrypterException(DecrypterException.CAPTCHA);
      }

      final String page = br.toString();
      progress.setRange(0);
      final String title =
          br.getRegex("shrink\"><th>(Titel|Baslik|Title)</th><td>(.*?)</td></tr>").getMatch(1);
      FilePackage fp = null;
      if (title != null && title.trim().length() > 0) {
        fp = FilePackage.getInstance();
        fp.setName(title);
        fp.setProperty("ALLOW_MERGE", true);
      }

      /* use cnl2 button if available */
      String cnlUrl = "http://127\\.0\\.0\\.1:9666/flash/addcrypted2";
      if (br.containsHTML(cnlUrl)) {
        final Browser cnlbr = br.cloneBrowser();

        Form cnlForm = null;
        for (Form f : cnlbr.getForms()) {
          if (f.containsHTML(cnlUrl)) {
            cnlForm = f;
          }
        }
        if (cnlForm != null) {

          if (System.getProperty("jd.revision.jdownloaderrevision") != null) {
            String jk =
                cnlbr.getRegex("<input type=\"hidden\" name=\"jk\" value=\"([^\"]+)\"").getMatch(0);
            HashMap<String, String> infos = new HashMap<String, String>();
            infos.put(
                "crypted", Encoding.urlDecode(cnlForm.getInputField("crypted").getValue(), false));
            infos.put("jk", jk);
            String source = cnlForm.getInputField("source").getValue();
            if (StringUtils.isEmpty(source)) {
              source = parameter.toString();
            } else {
              source = Encoding.urlDecode(source, true);
            }
            infos.put("source", source);
            String json = JSonStorage.toString(infos);
            final DownloadLink dl =
                createDownloadlink(
                    "http://dummycnl.jdownloader.org/"
                        + HexFormatter.byteArrayToHex(json.getBytes("UTF-8")));
            if (fp != null) {
              fp.add(dl);
            }
            try {
              distribute(dl);
            } catch (final Throwable e) {
              /* does not exist in 09581 */
            }
            decryptedLinks.add(dl);
            return decryptedLinks;
          } else {
            String jk =
                cnlbr.getRegex("<input type=\"hidden\" name=\"jk\" value=\"([^\"]+)\"").getMatch(0);
            cnlForm.remove("jk");
            cnlForm.put("jk", (jk != null ? jk.replaceAll("\\+", "%2B") : "nothing"));
            try {
              cnlbr.submitForm(cnlForm);
              if (cnlbr.containsHTML("success")) {
                return decryptedLinks;
              }
              if (cnlbr.containsHTML("^failed")) {
                logger.warning(
                    "relink.us: CNL2 Postrequest was failed! Please upload now a logfile, contact our support and add this loglink to your bugreport!");
                logger.warning("relink.us: CNL2 Message: " + cnlbr.toString());
              }
            } catch (Throwable e) {
              logger.info("relink.us: ExternInterface(CNL2) is disabled!");
            }
          }
        }
      }
      if (!br.containsHTML("download.php\\?id=[a-f0-9]+") && !br.containsHTML("getFile\\(")) {
        return null;
      }
      if (!decryptContainer(page, parameter, "dlc", decryptedLinks)) {
        if (!decryptContainer(page, parameter, "ccf", decryptedLinks)) {
          decryptContainer(page, parameter, "rsdf", decryptedLinks);
        }
      }
      /* Webdecryption */
      if (decryptedLinks.isEmpty()) {
        decryptLinks(decryptedLinks, param);
        final String more_links[] =
            new Regex(
                    page,
                    Pattern.compile(
                        "<a href=\"(go\\.php\\?id=[a-zA-Z0-9]+\\&seite=\\d+)\">",
                        Pattern.CASE_INSENSITIVE))
                .getColumn(0);
        for (final String link : more_links) {
          br.getPage("http://relink.us/" + link);
          decryptLinks(decryptedLinks, param);
        }
      }
      if (decryptedLinks.isEmpty() && br.containsHTML(cnlUrl)) {
        throw new DecrypterException("CNL2 only, open this link in Browser");
      }
      try {
        validateLastChallengeResponse();
      } catch (final Throwable e) {
      }
      if (fp != null) {
        fp.addLinks(decryptedLinks);
      }
      return decryptedLinks;
    }
  }
예제 #19
0
  public PathChooser(final String id, final boolean useQuickLIst) {
    super("ins 0", "[fill,grow][]", "[]");
    this.id = id;
    this.setOpaque(false);
    this.txt =
        new ExtTextField() {
          /** */
          private static final long serialVersionUID = 3243788323043431841L;

          /*
           * (non-Javadoc)
           *
           * @see org.appwork.swing.components.ExtTextField#getText()
           */
          @Override
          public String getText() {

            String ret = super.getText();

            if (ret.equals(helpText) && getForeground() == helpColor) {
              ret = "";
            }
            return ret;
          }

          @Override
          public JPopupMenu getPopupMenu(
              final AbstractAction cutAction,
              final AbstractAction copyAction,
              final AbstractAction pasteAction,
              final AbstractAction deleteAction,
              final AbstractAction selectAction) {
            final JPopupMenu self =
                PathChooser.this.getPopupMenu(
                    PathChooser.this.txt,
                    cutAction,
                    copyAction,
                    pasteAction,
                    deleteAction,
                    selectAction);

            if (self == null) {
              return super.getPopupMenu(
                  cutAction, copyAction, pasteAction, deleteAction, selectAction);
            }
            return self;
          }

          /*
           * (non-Javadoc)
           *
           * @see org.appwork.swing.components.ExtTextField#onChanged()
           */
          @Override
          public void onChanged() {
            PathChooser.this.onChanged(PathChooser.this.txt);
          }
        };
    this.txt.setHelpText(this.getHelpText());
    this.bt = new ExtButton(new BrowseAction());

    if (useQuickLIst) {
      this.txt.setHelperEnabled(false);
      this.destination =
          new SearchComboBox<String>() {

            @Override
            public JTextField createTextField() {
              return PathChooser.this.txt;
            }

            @Override
            protected Icon getIconForValue(final String value) {
              return null;
            }

            @Override
            protected String getTextForValue(final String value) {
              return value;
            }

            @Override
            public boolean isAutoCompletionEnabled() {
              return false;
            }

            @Override
            public void onChanged() {
              PathChooser.this.onChanged(PathChooser.this.txt);
            }

            @Override
            protected void sortFound(final List<String> found) {

              Collections.sort(
                  found,
                  new Comparator<String>() {

                    @Override
                    public int compare(final String o1, final String o2) {
                      return o1.compareTo(o2);
                    }
                  });
            }
          };
      // this code makes enter leave the dialog.

      this.destination
          .getTextField()
          .getInputMap()
          .put(KeyStroke.getKeyStroke("pressed TAB"), "auto");

      this.destination.getTextField().setFocusTraversalKeysEnabled(false);

      this.destination
          .getTextField()
          .getActionMap()
          .put(
              "auto",
              new AbstractAction() {

                @Override
                public void actionPerformed(final ActionEvent e) {
                  if (!PathChooser.this.auto(PathChooser.this.txt)) {
                    //
                    System.out.println("NExt Fpcus");
                    final KeyboardFocusManager manager =
                        KeyboardFocusManager.getCurrentKeyboardFocusManager();
                    manager.focusNextComponent();
                  }
                }
              });
      this.destination.setUnkownTextInputAllowed(true);
      this.destination.setBadColor(null);
      this.destination.setSelectedItem(null);

      this.add(this.destination);
    } else {
      this.txt.setHelperEnabled(true);
      this.add(this.txt);
    }
    this.add(this.bt);

    final String preSelection =
        JSonStorage.getStorage(Dialog.FILECHOOSER)
            .get(Dialog.LASTSELECTION + id, this.getDefaultPreSelection());
    if (preSelection != null) {
      this.setFile(new File(preSelection));
    }
  }
예제 #20
0
파일: Loc.java 프로젝트: amicom/my-project
/**
 * This class provides functions to return translated strings
 * 
 * @author Christian
 */
@Deprecated
public class Loc {
    /**
     * The directory, where all localization files are located. A_ because this
     * the order is important.
     */
    // public static final File A_LOCALIZATION_DIR =
    // Application.getResource("languages/");

    public static final Storage             CFG             = JSonStorage.getStorage("Locale");
    /**
     * The HashMap which contains all hashcodes of the keys and their translated
     * values.
     * 
     * @see Loc#parseLocalization(RFSFile)
     */
    private static HashMap<Integer, String> DATA            = null;

    private static String                   DEFAULT_LOCALE_CACHE;

    /**
     * The name of the default localization file. This is the english language.
     */
    private static final String             FALLBACK_LOCALE = "en_GB";

    private static String                   locale;

    /**
     * The key (String) under which the saved localization-name is stored.
     */
    public static final String              PROPERTY_LOCALE = "PROPERTY_LOCALE2";

    public static String _(final Translate t) {
        return t.s();
    }

    public static String _(final Translate t, final Object... parameter) {
        return t.s(parameter);
    }

    /**
     * @return
     */
    private static String getDefaultLocale() {
        if (Loc.DEFAULT_LOCALE_CACHE != null) { return Loc.DEFAULT_LOCALE_CACHE; }
        final String sys = System.getProperty("user.language").toLowerCase();
        final String cou = System.getProperty("user.country").toUpperCase();

        final String[] locs = Loc.getLocales();
        if (locs.length == 0) {
            Loc.DEFAULT_LOCALE_CACHE = Loc.FALLBACK_LOCALE;

        }
        if (Loc.DEFAULT_LOCALE_CACHE == null) {
            for (final String l : locs) {

                if (l.equals(sys + "_" + cou)) {
                    Loc.DEFAULT_LOCALE_CACHE = l;
                    break;
                }
            }
        }
        if (Loc.DEFAULT_LOCALE_CACHE == null) {
            for (final String l : locs) {

                if (l.equals(sys)) {
                    Loc.DEFAULT_LOCALE_CACHE = l;
                    break;
                }
            }
        }
        if (Loc.DEFAULT_LOCALE_CACHE == null) {
            for (final String l : locs) {
                if (l.startsWith(sys + "_")) {
                    Loc.DEFAULT_LOCALE_CACHE = l;
                    break;
                }
            }
        }

        if (Loc.DEFAULT_LOCALE_CACHE == null) {
            for (final String l : locs) {
                if (l.equals(Loc.FALLBACK_LOCALE)) {
                    Loc.DEFAULT_LOCALE_CACHE = l;
                    break;
                }
            }
        }
        if (Loc.DEFAULT_LOCALE_CACHE == null) {
            Loc.DEFAULT_LOCALE_CACHE = locs[0];
        }
        return Loc.DEFAULT_LOCALE_CACHE;
    }

    /**
     * Returns a localized regular expression for words that usualy ar present
     * in an error message
     * 
     * @return
     */
    public static String getErrorRegex() {
        return Loc.L("system.error", ".*(error|failed).*");
    }

    /**
     * @return
     */
    public static String getLocale() {

        return Loc.locale;
    }

    /**
     * @return
     */
    public static String[] getLocales() {
        final java.util.List<String> ret = new ArrayList<String>();

        // first look out for all translations in filesystem
        String[] files;

        files = Application.getResource("languages/").list(new FilenameFilter() {

            public boolean accept(final File dir, final String name) {
                return name.endsWith(".loc");

            }

        });

        if (files != null) {
            for (final String file : files) {
                ret.add(file.substring(0, file.length() - 4));
            }
        }

        // Search in jar:
        try {
            URL url = Application.getRessourceURL("languages/");
            if (url != null) {
                Enumeration<URL> resources;

                resources = Thread.currentThread().getContextClassLoader().getResources("languages/");

                while (resources.hasMoreElements()) {

                    url = resources.nextElement();
                    if (url.getProtocol().equalsIgnoreCase("jar")) {
                        final String path = url.getPath();
                        final int index = path.lastIndexOf('!');

                        final String jarPath = path.substring(0, index);
                        final String internPath = path.substring(index + 2);

                        final JarInputStream jarFile = new JarInputStream(new FileInputStream(new File(new URL(jarPath).toURI())));
                        JarEntry e;

                        String jarName;
                        while ((e = jarFile.getNextJarEntry()) != null) {
                            jarName = e.getName();
                            if (jarName.startsWith(internPath) && jarName.endsWith(".loc")) {
                                String filename = new File(jarName).getName();
                                filename = filename.substring(0, filename.length() - 4);
                                ret.remove(filename);
                                ret.add(filename);
                            }
                        }
                    } else {
                        files = new File(url.toURI()).list(new FilenameFilter() {

                            public boolean accept(final File dir, final String name) {
                                return name.endsWith(".loc");

                            }

                        });

                        if (files != null) {
                            for (final String file : files) {
                                ret.add(file.substring(0, file.length() - 4));
                            }
                        }
                    }
                }
            }
        } catch (final Exception e) {
            Log.exception(e);
        }
        return ret.toArray(new String[] {});

    }

    public static URL getResourceURL(final String loc) throws MalformedURLException {
        final File singleFile = Application.getResource("languages/" + loc + ".loc");
        URL file = Application.getRessourceURL("languages/" + loc + ".loc");
        if (singleFile.exists() && singleFile.length() > 0 || file == null) {
            file = singleFile.toURI().toURL();
        }
        return file;
    }

    /**
     * Returns the translated value for the translation-key. If the current
     * language file doesn't contain the translated value, the default value
     * will be returned.
     * 
     * @param key
     *            key for the translation in the language file. the key should
     *            <b>always</b> have the following structure
     *            <i>PACKAGE_NAME_FROM_CALLER.CLASS_NAME_FROM_CALLER.key</i>
     * @param def
     *            default value which will be returned if there is no mapping
     *            for the key
     * @return translated value or the def parameter
     * @see Loc#LF(String, String, Object...)
     * @throws IllegalArgumentException
     *             if the key is null or is empty
     */
    public static String L(String key, final String def) {
        if (key == null || (key = key.trim()).length() == 0) { throw new IllegalArgumentException(); }
        if (Loc.DATA == null) {
            Log.L.warning("No parsed localization found! Loading now from saved localization file!");
            try {
                Loc.setLocale(Loc.CFG.get(Loc.PROPERTY_LOCALE, Loc.FALLBACK_LOCALE));
            } catch (final Exception e) {

                Log.L.severe("Error while loading the stored localization name!");
                Loc.setLocale(Loc.FALLBACK_LOCALE);
            }
            if (Loc.DATA == null) { return def == null ? "Error in Loc! No loaded data!" : def; }
        }

        final String loc = Loc.DATA.get(key.toLowerCase().hashCode());
        if (loc == null) {
            Loc.DATA.put(key.toLowerCase().hashCode(), def);
            return def;
        }
        return loc;
    }

    /**
     * Returns the translated value for the translation-key filled with the
     * parameters.
     * 
     * @param key
     *            key for the translation in the language file. the key should
     *            <b>always</b> have the following structure
     *            <i>PACKAGE_NAME_FROM_CALLER.CLASS_NAME_FROM_CALLER.key</i>
     * @param def
     *            default value which will be returned if there is no mapping
     *            for the key
     * @param args
     *            parameters which should be inserted in the translated string
     * @return translated value or the def parameter filled with the parameters
     * @see Loc#L(String, String)
     */
    public static String LF(final String key, final String def, final Object... args) {
        try {
            return String.format(Loc.L(key, def), args);
        } catch (final Exception e) {
            return "Error: " + key;
        }
    }

    /**
     * Creates a HashMap with the data obtained from the localization file. <br>
     * <b>Warning:</b> Overwrites any previously created HashMap
     * 
     * @param file
     *            {@link RFSFile} object to the localization file
     * @throws IllegalArgumentException
     *             if the parameter is null or doesn't exist
     * @see Loc#DATA
     */
    public static void parseLocalization(final URL file) throws IllegalArgumentException {
        if (file == null) { throw new IllegalArgumentException(); }

        if (Loc.DATA != null) {
            Log.L.finer("Previous HashMap will be overwritten!");
        }
        Loc.DATA = new HashMap<Integer, String>();

        BufferedReader reader = null;
        InputStreamReader isr = null;
        InputStream fis = null;
        try {
            reader = new BufferedReader(isr = new InputStreamReader(fis = file.openStream(), "UTF8"));

            String line;
            String key;
            String value;
            int split;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#")) {
                    continue;
                }

                if ((split = line.indexOf('=')) <= 0) {
                    continue;
                }

                key = line.substring(0, split).toLowerCase().trim();
                value = line.substring(split + 1).trim();
                value = value.replace("\\n", "\n").replace("\\r", "\r");

                Loc.DATA.put(key.hashCode(), value);
            }
        } catch (final FileNotFoundException e) {
            throw new IllegalArgumentException(e);
        } catch (final Exception e) {
            org.appwork.utils.logging.Log.exception(e);
        } finally {
            try {
                reader.close();
            } catch (final Throwable e) {
            }
            try {
                isr.close();
            } catch (final Throwable e) {
            }
            try {
                fis.close();
            } catch (final Throwable e) {
            }
        }
    }

    /**
     * Set-up this class by creating the HashMap for the key-string-pairs.
     * 
     * @param loc
     *            name of the localization file
     * @see Loc#parseLocalization(RFSFile)
     */
    public static void setLocale(String loc) {
        try {
            if (loc == null) {

                loc = Loc.CFG.get(Loc.PROPERTY_LOCALE, Loc.getDefaultLocale());
            }
            // first check filesystem
            final URL file = Loc.getResourceURL(loc);

            Loc.locale = loc;
            if (file != null) {
                // TODO

                Loc.CFG.put(Loc.PROPERTY_LOCALE, loc);
                Loc.parseLocalization(file);
            } else {
                Log.L.info("The language " + loc + " isn't available! Parsing default (" + Loc.FALLBACK_LOCALE + ".loc) one!");
                Loc.locale = Loc.getDefaultLocale();
                final String[] locs = Loc.locale.split("_");
                Locale.setDefault(new Locale(locs[0], locs[1]));
                Loc.parseLocalization(Loc.getResourceURL(Loc.FALLBACK_LOCALE));
            }
        } catch (final Exception e) {
            org.appwork.utils.logging.Log.exception(e);
        }
    }
}
 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;
   }
 }