Пример #1
0
  private AbstractExtensionWrapper getCache(Class<AbstractExtension<?>> cls)
      throws StartException, InstantiationException, IllegalAccessException, IOException {
    String id = cls.getName().substring(27);
    // File cache = Application.getResource("tmp/extensioncache/" + id +
    // ".json");
    // AbstractExtensionWrapper cached = JSonStorage.restoreFrom(cache,
    // true, (byte[]) null, new TypeRef<AbstractExtensionWrapper>() {

    AbstractExtensionWrapper cached = cache.get(id);

    int v = AbstractExtension.readVersion(cls);
    if (cached != null) {
      cached._setClazz(cls);
      if (cached.getVersion() != v
          || !cached.getLng().equals(_JDT.getLanguage())
          || cached._getSettings() == null) {
        // update cache
        cached = null;
      }
    }
    if (cached == null) {
      Log.L.info("Update Cache " + cache);
      cached = AbstractExtensionWrapper.create(id, cls);
      cache.put(id, cached);
      cacheChanged = true;
    } else {
      cached._setClazz(cls);
    }
    return cached;
  }
Пример #2
0
    /**
     * 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);
        }
    }
Пример #3
0
  @Override
  protected String send(String serviceName, String routine, String serialise)
      throws ServerInvokationException {
    try {
      String url =
          "http://" + this.host + "/" + serviceName + "/" + URLEncoder.encode(routine, "UTF-8");
      Log.L.finer(url + "?" + serialise);
      String red = br.postPageRaw(url, serialise);

      URLConnectionAdapter con = br.getHttpConnection();
      if (con.getResponseCode() == HTTPConstants.ResponseCode.SUCCESS_OK.getCode()) {
        return red;
      } else if (con.getResponseCode()
          == HTTPConstants.ResponseCode.SERVERERROR_INTERNAL.getCode()) {
        // Exception
        throw new ServerInvokationException(red, new Requestor(serviceName, routine, serialise));
      } else {
        throw new RemoteCallCommunicationException("Wrong ResponseCode " + con.getResponseCode());
      }
    } catch (final ServerInvokationException e) {
      throw e;
    } catch (final IOException e) {

      throw new RemoteCallCommunicationException(e);
    } catch (final Exception e) {
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }
      throw new RuntimeException(e);
    }
  }
Пример #4
0
 /**
  * Called when a new directory has to be added.
  *
  * <p>For each 'addDir' call server will call 'closeDir' method after all children of the added
  * directory are added.
  *
  * <p>This implementation creates corresponding directory below root directory.
  */
 public void addDir(String path, String copyFromPath, long copyFromRevision) throws SVNException {
   File newDir = new File(myRootDirectory, path);
   if (!newDir.exists()) {
     if (!newDir.mkdirs()) {
       SVNErrorMessage err =
           SVNErrorMessage.create(
               SVNErrorCode.IO_ERROR, "error: failed to add the directory ''{0}''.", newDir);
       throw new SVNException(err);
     }
   }
   Log.L.fine("dir added: " + path);
 }
Пример #5
0
    /**
     * 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;
    }
Пример #6
0
    /**
     * 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) {
            }
        }
    }
  public void validate(Login login, String url) {

    if (StringUtils.isEmpty(url)) {
      return;
    }
    AuthenticationInfo.Type type = null;
    if (url.startsWith("ftp")) {
      type = Type.FTP;
    } else if (url.startsWith("http")) {
      type = Type.HTTP;
    } else {
      Log.L.info("Unknown Protocoll: " + url);
      return;
    }

    String urlHost = Browser.getHost(url, true);
    for (AuthenticationInfo info : list) {
      if (!info.isEnabled()) {
        continue;
      }
      String authHost = info.getHostmask();
      if (info.getType().equals(type) && !StringUtils.isEmpty(authHost)) {
        boolean contains = false;
        if (authHost.length() > urlHost.length()) {
          /* hostMask of AuthenticationInfo is longer */
          contains = authHost.contains(urlHost);
        } else {
          /* hostMask of urlHost is longer */
          contains = urlHost.contains(authHost);
        }
        if (contains) {
          if (StringUtils.equals(info.getUsername(), login.getUsername())
              && StringUtils.equals(info.getPassword(), login.getPassword())) {
            info.setLastValidated(System.currentTimeMillis());
          }
        }
      }
    }
  }
  public ExceptionDialog(
      final int flag,
      final String title,
      final String message,
      final Throwable exception,
      final String okOption,
      final String cancelOption) {
    super(flag, title, null, okOption, cancelOption);
    Log.L.fine(
        "Dialog    ["
            + okOption
            + "]["
            + cancelOption
            + "]\r\nflag:  "
            + Integer.toBinaryString(flag)
            + "\r\ntitle: "
            + title
            + "\r\nmsg:   \r\n"
            + message);

    this.message = message;
    this.exception = exception;
  }
  public List<Login> getSortedLoginsList(String url) {
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    AuthenticationInfo.Type type = null;
    if (url.startsWith("ftp")) {
      type = Type.FTP;
    } else if (url.startsWith("http")) {
      type = Type.HTTP;
    } else {
      Log.L.info("Unknown Protocoll: " + url);
      return null;
    }
    final ArrayList<AuthenticationInfo> possibleInfos = new ArrayList<AuthenticationInfo>();

    String urlHost = Browser.getHost(url, true);
    for (AuthenticationInfo info : list) {
      if (!info.isEnabled()) {
        continue;
      }
      final String authHost = info.getHostmask();
      if (info.getType().equals(type) && !StringUtils.isEmpty(authHost)) {
        boolean contains = false;
        if (authHost.length() > urlHost.length()) {
          /* hostMask of AuthenticationInfo is longer */
          contains = authHost.contains(urlHost);
        } else {
          /* hostMask of urlHost is longer */
          contains = urlHost.contains(authHost);
        }
        if (contains) {
          possibleInfos.add(info);
        }
      }
    }
    try {
      Collections.sort(
          possibleInfos,
          new Comparator<AuthenticationInfo>() {

            @Override
            public int compare(AuthenticationInfo o1, AuthenticationInfo o2) {
              int ret = Integer.compare(o2.getHostmask().length(), o1.getHostmask().length());
              if (ret == 0) {
                ret = Long.compare(o2.getLastValidated(), o1.getLastValidated());
              }
              if (ret == 0) {
                ret = Long.compare(o2.getCreated(), o1.getCreated());
              }
              return ret;
            }
          });

    } catch (Throwable e) {
      logger.log(e);
    }
    final ArrayList<Login> ret = new ArrayList<Login>();
    for (AuthenticationInfo info : possibleInfos) {
      ret.add(new Login(info.getUsername(), info.getPassword()));
    }
    return ret;
  }
Пример #10
0
  @SuppressWarnings("unchecked")
  private void loadUnpacked() {
    URL ret = getClass().getResource("/");
    File root;
    if (ret.getProtocol().equalsIgnoreCase("file")) {
      try {
        root = new File(ret.toURI());
      } catch (URISyntaxException e) {
        Log.exception(e);
        Log.L.finer("Did not load unpacked Extensions from " + ret);
        return;
      }
    } else {
      Log.L.finer("Did not load unpacked Extensions from " + ret);
      return;
    }
    root = new File(root, AbstractExtension.class.getPackage().getName().replace('.', '/'));
    Log.L.finer("Load Extensions from: " + root.getAbsolutePath());
    File[] folders =
        root.listFiles(
            new FileFilter() {

              public boolean accept(File pathname) {
                return pathname.isDirectory();
              }
            });
    ClassLoader cl = getClass().getClassLoader();
    main:
    for (File f : folders) {
      File[] modules =
          f.listFiles(
              new FilenameFilter() {

                public boolean accept(File dir, String name) {
                  return name.endsWith("Extension.class");
                }
              });
      boolean loaded = false;
      for (File module : modules) {

        Class<?> cls;
        try {
          cls =
              cl.loadClass(
                  AbstractExtension.class.getPackage().getName()
                      + "."
                      + module.getParentFile().getName()
                      + "."
                      + module.getName().substring(0, module.getName().length() - 6));

          if (AbstractExtension.class.isAssignableFrom(cls)) {
            loaded = true;
            initModule((Class<AbstractExtension<?>>) cls);
            continue main;
          }
        } catch (IllegalArgumentException e) {
          Log.L.warning("Did not init Extension " + module + " : " + e.getMessage());
        } catch (Throwable e) {
          Log.exception(e);
          Dialog.getInstance().showExceptionDialog("Error", e.getMessage(), e);
        }
      }
      if (!loaded) {
        Log.L.warning("Could not load any Extension Module from " + f);
      }
    }
  }
Пример #11
0
  public static void main(String[] args) {
    Log.L.setLevel(Level.ALL);
    new EDTRunner() {

      @Override
      protected void runInEDT() {

        final ProgressGetter pg =
            new ProgressGetter() {

              private long loaded = 0;
              private long total = 100;

              @Override
              public int getProgress() {

                if (this.total == 0) {
                  return 0;
                }
                return (int) (this.loaded * 100 / this.total);
              }

              @Override
              public String getString() {

                if (this.total <= 0) {
                  return _AWU.T.connecting();
                }
                String ret =
                    _AWU.T.progress(
                        SizeFormatter.formatBytes(this.loaded),
                        SizeFormatter.formatBytes(this.total),
                        (this.loaded * 10000 / this.total) / 100.0);
                return ret;
              }

              @Override
              public void run() throws Exception {
                for (int i = 0; i < 100; i++) {
                  Thread.sleep(1000);
                  loaded++;
                }
              }

              @Override
              public String getLabelString() {
                return getProgress() + " %";
              }
            };
        final ProgressDialog dialog =
            new ProgressDialog(
                pg,
                UIOManager.BUTTONS_HIDE_CANCEL | UIOManager.BUTTONS_HIDE_OK,
                _AWU.T.download_title(),
                _AWU.T.download_msg(),
                AWUTheme.getInstance().getIcon("download", 32)) {
              /** */
              protected boolean isLabelEnabled() {
                // TODO Auto-generated method stub
                return true;
              }
            };
        try {
          Dialog.getInstance().showDialog(dialog);
        } catch (DialogCanceledException ee) {

        } catch (DialogClosedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    };
  }