Exemplo n.º 1
0
 public void dump(long lMethod) {
   Log.log(
       "\ttag = 0x" + Utility.toHexString(tag) + " (" + OptionalParameterTag.toString(tag) + ")",
       0x100000000000000L | lMethod);
   Log.log("\tlength = " + length, 0x100000000000000L | lMethod);
   Log.log("\tvalue(binary) = 0x" + Utility.toHexString(value), 0x100000000000000L | lMethod);
 }
Exemplo n.º 2
0
 /** Log an exception that occurred during the processing of a request or response. */
 public void logException(HNetError e) {
   log.log(String.format("---- ERROR %s", e.getUrl() != null ? e.getUrl() : ""));
   StringWriter sw = new StringWriter();
   e.printStackTrace(new PrintWriter(sw));
   log.log(sw.toString());
   log.log("---- END ERROR");
 }
Exemplo n.º 3
0
 /** Log an exception that occurred during the processing of a request or response. */
 public void logException(Throwable t, String url) {
   log.log(String.format("---- ERROR %s", url != null ? url : ""));
   StringWriter sw = new StringWriter();
   t.printStackTrace(new PrintWriter(sw));
   log.log(sw.toString());
   log.log("---- END ERROR");
 }
Exemplo n.º 4
0
  public Processing(Box root) {
    super(null);

    Log.log("startup.processing", " processing plugin is starting up ");

    frame = new JFrame("Field/Processing");
    __applet =
        new FieldProcessingApplet(
            sizeX,
            sizeY,
            queue,
            this,
            s -> {
              if (getLastErrorOutput() != null) getLastErrorOutput().accept(new Pair<>(-1, s));
            });

    __applet.init();
    __applet.loop();
    frame.add(__applet, BorderLayout.CENTER);
    frame.setSize(sizeX, sizeY);
    frame.setVisible(true);
    frame.validate();

    applet = new FieldProcessingAppletDelgate(__applet);

    this.properties.put(P, applet);

    Log.log("startup.processing", " searching for boxes that need processing support ");

    Log.log("startup.processing", " processing plugin has finished starting up ");
  }
  /**
   * DELETE must be idempotent so we return status 200 even when a bundle doesn't exist with the
   * requested ID, since it may have already been deleted. Only returns error 400 if the request
   * formatting is invalid.
   *
   * @see org.bndtools.runtime.controller.IHandler#handleDelete(java.lang.String[])
   */
  public IResponse handleDelete(String[] queryPath, Properties params) {
    IResponse response;
    if (queryPath.length != 1) {
      response =
          new DefaultResponse(
              IResponse.HTTP_BADREQUEST,
              IResponse.MIME_PLAINTEXT,
              "Bad request format. Required: DELETE /bundles/<BUNDLE_ID>");
    } else {
      try {
        Bundle bundle = findBundle(queryPath[0]);
        bundle.uninstall();
        response = listBundles();
      } catch (NumberFormatException e) {
        response =
            new DefaultResponse(
                IResponse.HTTP_BADREQUEST, IResponse.MIME_PLAINTEXT, e.getMessage());
      } catch (IllegalArgumentException e) {
        log.log(null, LogService.LOG_INFO, "Ignoring error in BundlesHandler.handleDelete()", e);
        response = listBundles();
      } catch (BundleException e) {
        log.log(null, LogService.LOG_INFO, "Ignoring error in BundlesHandler.handleDelete()", e);
        response = listBundles();
      }
    }

    return response;
  }
Exemplo n.º 6
0
  /** Retrieves an object from Preferences (deserialized). */
  @SuppressWarnings("unchecked")
  public static <T> T getObjectFromPrefs(Preferences prefs, String key, T def) {
    ArrayList<byte[]> chunks = new ArrayList<byte[]>();
    byte[] serialBytes = new byte[0];
    int totalLength = 0;
    try {
      for (String chunkKey : prefs.node(key).keys()) {
        byte[] chunk = prefs.node(key).getByteArray(chunkKey, new byte[0]);
        chunks.add(chunk);
        totalLength += chunk.length;
      }
      int pos = 0;
      serialBytes = new byte[totalLength];
      for (byte[] chunk : chunks) {
        System.arraycopy(chunk, 0, serialBytes, pos, chunk.length);
        pos += chunk.length;
      }
    } catch (BackingStoreException ex) {
      Log.log(ex);
    }

    if (serialBytes.length == 0) {
      return def;
    }
    ByteArrayInputStream byteStream = new ByteArrayInputStream(serialBytes);
    try {
      ObjectInputStream objectStream = new ObjectInputStream(byteStream);
      return (T) objectStream.readObject();
    } catch (Exception e) {
      Log.log("Failed to get object from preferences.");
      return def;
    }
  }
Exemplo n.º 7
0
 /** Serializes an object and stores it in Preferences */
 public static void putObjectInPrefs(Preferences prefs, String key, Serializable obj) {
   ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
   try {
     ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);
     objectStream.writeObject(obj);
   } catch (Exception e) {
     Log.log("Failed to save object in Preferences.");
     return;
   }
   int MAX_LENGTH = 3 * Preferences.MAX_VALUE_LENGTH / 4;
   byte[] serialBytes = byteStream.toByteArray();
   int totalLength = serialBytes.length;
   long nChunks = (int) Math.ceil(serialBytes.length / (double) MAX_LENGTH);
   try {
     if (prefs.nodeExists(key)) {
       prefs.node(key).removeNode();
     }
   } catch (BackingStoreException ex) {
     Log.log(ex);
   }
   for (int i = 0; i < nChunks; ++i) {
     int chunkLength = Math.min(MAX_LENGTH, totalLength - i * MAX_LENGTH);
     byte[] chunk = new byte[chunkLength];
     System.arraycopy(serialBytes, i * MAX_LENGTH, chunk, 0, chunkLength);
     prefs.node(key).putByteArray(String.format("%09d", i), chunk);
   }
 }
Exemplo n.º 8
0
  public void inject2(Browser browser) {
    Log.log("glassbrowser.debug", () -> "inject 2 is happening");
    for (String s : playlist) {
      Log.log("glassbrowser.debug", () -> "executing :" + s);
      browser.executeJavaScript(findAndLoad(s, true));
    }
    //		 hide();

    browser.finishBooting();
  }
Exemplo n.º 9
0
  @Test
  public void testTruncates() {
    expect(wrappedLog.log(MESSAGES)).andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a"))).andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b"))).andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c"))).andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c", "d")))
        .andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c", "d", "e")))
        .andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c", "d", "e", "f")))
        .andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("2", "3", "4", "5", "a", "b", "c", "d", "e", "f", "g")))
        .andReturn(FALSE);
    expect(wrappedLog.log(Arrays.asList("3", "4", "5", "a", "b", "c", "d", "e", "f", "g", "h")))
        .andReturn(TRUE);

    replay(wrappedLog);

    bufferedLog.log(MESSAGES);
    bufferedLog.log("a");
    bufferedLog.log("b");
    bufferedLog.log("c");
    bufferedLog.log("d");
    bufferedLog.log("e");
    bufferedLog.log("f");
    bufferedLog.log("g");
    bufferedLog.log("h");
  }
Exemplo n.º 10
0
  private void doAWTRequest(Request request) {

    try {
      request.run.run();
    } catch (Throwable t) {
      Log.log(Log.ERROR, WorkThread.class, "Exception " + "in AWT thread:");
      Log.log(Log.ERROR, WorkThread.class, t);
    }

    awtRequestCount--;
  }
Exemplo n.º 11
0
  @Test
  public void testBufferRetries() {
    List<String> bufferAppended = ImmutableList.<String>builder().addAll(MESSAGES).add("6").build();

    expect(wrappedLog.log(MESSAGES)).andReturn(FALSE);
    expect(wrappedLog.log(bufferAppended)).andReturn(TRUE);

    replay(wrappedLog);
    bufferedLog.log(MESSAGES);
    bufferedLog.log("6");
  }
Exemplo n.º 12
0
 public boolean isValid() {
   if (length <= 0 || length >= 512) {
     Log.log("OptionalParameter.wrap : invalid length !", 0x100600000000000L);
     return false;
   }
   if (value == null || value.length != length) {
     Log.log("OptionalParameter.wrap : invalid valid !", 0x100600000000000L);
     return false;
   } else {
     return true;
   }
 }
Exemplo n.º 13
0
  /**
   * <b>addPanel()</b></br> <i>Removes a panel from the HashMap. Cannot remove a panel while it is
   * the current panel of the entire Window Manager.</i></br>
   *
   * @version Slap 0.1
   * @param identifier name of the panel to be removed.
   */
  public void removePanel(String identifier) {

    if (CURRENT_PANEL_NAME == identifier) {

      LOG.setSubSection("Error");
      LOG.log("Denied the attempt to remove a panel that is currently in use.");
      LOG.useSubSection(false);

    } else {

      LOG.log("Removing panel \"" + identifier + "\"");
      PANELS.remove(identifier);
    }
  }
Exemplo n.º 14
0
 public static double getJavaVersion() {
   String version = System.getProperty("java.version");
   Log.log(Log.INFO, "version:" + version);
   int pos = 0, count = 0;
   for (; pos < version.length() && count < 2; pos++) {
     if (version.charAt(pos) == '.') {
       count++;
     }
   }
   --pos;
   double dversion = Double.parseDouble(version.substring(0, pos));
   Log.log(Log.INFO, "Java Version:" + dversion);
   return dversion;
 }
Exemplo n.º 15
0
  public static void addURL(URL u) throws IOException {

    URLClassLoader loader = (URLClassLoader) JavaUtils.class.getClassLoader();
    Class<?> sysclass = URLClassLoader.class;

    try {
      Method method = sysclass.getDeclaredMethod("addURL", parameters);
      method.setAccessible(true);
      method.invoke(loader, new Object[] {u});
      Log.log("Added URL to system class loader: " + u);
    } catch (Throwable t) {
      Log.log("Failed to add URL to system class loader: " + u);
      throw new IOException("Failed to add URL to system class loader: " + u);
    } // end try catch
  } // end method
  public void run() {
    try {
      while (true) {
        sleep(INTERVAL);

        try {
          SwingUtilities.invokeLater(task);
        } catch (final Throwable t) {
          Log.log(Log.SYS, t);
        }
      }
    } catch (final InterruptedException ie) {
      Log.log(Log.SYS, ie);
    }
  }
Exemplo n.º 17
0
  /**
   * <b>setCurrentPanel()</b></br> <i>Sets the overall current panel object. Window must be
   * refreshed to actually change the panel that the Window displays.</i></br>
   *
   * @version Slap 0.1
   * @param name string name of panel from the panel map to be set as the current panel.
   */
  public void setCurrentPanel(String name) {

    if (PANELS.containsKey(name)) {

      LOG.log("Setting current panel to \"" + name + "\".");
      CURRENT_PANEL = PANELS.get(name);
      CURRENT_PANEL_NAME = name;

    } else {

      LOG.setSubSection("Error");
      LOG.log("Attempted current panel does not exist in the HashMap.");
      LOG.useSubSection(false);
    }
  }
Exemplo n.º 18
0
  public static String readTextFile(String filepath) {
    File f = new File(filepath);
    if (!f.exists()) {
      return null;
    }

    StringBuilder contents = new StringBuilder();

    try {
      // use buffering, reading one line at a time
      // FileReader always assumes default encoding is OK!
      BufferedReader input = new BufferedReader(new FileReader(filepath));
      try {
        String line; // not declared within while loop
        /*
         * readLine is a bit quirky :
         * it returns the content of a line MINUS the newline.
         * it returns null only for the END of the stream.
         * it returns an empty String if two newlines appear in a row.
         */
        while ((line = input.readLine()) != null) {
          contents.append(line);
          contents.append(System.getProperty("line.separator"));
        }
      } finally {
        input.close();
      }
    } catch (IOException ex) {
      Log.log(ex);
    }

    return contents.toString();
  }
Exemplo n.º 19
0
		void runTask() {
			status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "newAlbm", new Object[] { album.getName(), g.toString() }));

			try {
				List<NameValuePair> formparams = new ArrayList<NameValuePair>();
				JSONObject jsonEntity = new JSONObject();
				jsonEntity.put("type", "album");
				if (album.getName() != null)
					jsonEntity.put("name", album.getName());
				if (album.getTitle() != null)
					jsonEntity.put("title", album.getTitle());
				if (album.getDescription() != null)
					jsonEntity.put("description", album.getDescription());
				formparams.add(new BasicNameValuePair("entity", jsonEntity.toJSONString()));

				BufferedReader entityReader = sendRequest(album.getParentAlbum().getUrl(), "post", formparams);

				String url = ((JSONObject) JSONValue.parse(entityReader)).get("url").toString();
				status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "crateAlbmOk"));
				album.setUrl(url);

				Log.log(Log.LEVEL_INFO, "Created album " + album.toString());
			} catch (IOException ioe) {
				Log.logException(Log.LEVEL_ERROR, MODULE, ioe);
				Object[] params2 = {ioe.toString()};
				error(su, GRI18n.getString(MODULE, "error", params2));
			}
		}
Exemplo n.º 20
0
 private static void endInterpreter(String contextId) throws EvalError {
   Interpreter i = interpreters.get(contextId);
   if (i == null) return;
   i.eval("clear();"); // can't hurt to tell bsh to clean up internally
   interpreters.remove(contextId); // now wait for GC
   Log.log("Destroyed context: " + contextId + " (" + i + ")");
 }
Exemplo n.º 21
0
  /**
   * <b>setNextPanel()</b></br> <i>Triggers to Window Manager to do actions that would be done upon
   * completion of a panel's actions. This method should be fired by the current panel in order to
   * alert the Window Manager that it is done.</i></br>
   *
   * @version Slap 0.1
   */
  public void sendProgressFinish() {

    LOG.log("Progress finished signal recieved.");
    setCurrentPanel(NEXT_PANEL_NAME);
    NEXT_PANEL_NAME = "";
    setTrackProgress(false);
  }
Exemplo n.º 22
0
 public void wrap(SMPPPacket packet) throws BufferException {
   Log.log("OptionalParameter.wrap : wrap elements !", 0x100800000000000L);
   dump(0x800000000000L);
   packet.addShort((short) (tag & 0xffff));
   packet.addShort((short) (length & 0xffff));
   packet.addBytes(value);
 }
Exemplo n.º 23
0
  /** Download a file to the disk */
  public static void downloadFileToDisk(String address, String filename)
      throws MalformedURLException {
    URLConnection urlConn;
    InputStream in = null;
    OutputStream out = null;
    try {
      URL url = new URL(address);
      urlConn = url.openConnection();
      in = urlConn.getInputStream();
      out = new BufferedOutputStream(new FileOutputStream(filename));

      byte[] byteBuffer = new byte[1024];

      int numRead;
      while ((numRead = in.read(byteBuffer)) != -1) {
        out.write(byteBuffer, 0, numRead);
      }
    } catch (IOException ex) {
      Log.logErrorRB("IO exception");
      Log.log(ex);
    } finally {
      try {
        if (in != null) {
          in.close();
        }

        if (out != null) {
          out.close();
        }
      } catch (IOException ex) {
        // munch this
      }
    }
  }
Exemplo n.º 24
0
  public static String getScriptDir() {
    // If the script directory has already been determined, return it
    if (m_scriptDir != null) return m_scriptDir;

    m_scriptDir = getConfigDir() + SCRIPT_DIR + File.separator;

    try {
      // Check if the directory exists
      File dir = new File(m_scriptDir);
      if (!dir.exists()) {
        // Create the directory
        boolean created = dir.mkdirs();

        // If the directory could not be created,
        // set the script directory to config directory
        if (!created) {
          Log.logErrorRB("SU_SCRIPT_DIR_CREATE_ERROR");
          m_scriptDir = getConfigDir();
        }
      }
    } catch (SecurityException e) {
      // The system doesn't want us to write where we want to write
      // reset the script dir to the current config dir
      m_scriptDir = getConfigDir();

      // log the exception, but only after the script dir has been reset
      Log.logErrorRB("SU_SCRIPT_DIR_CREATE_ERROR");
      Log.log(e.toString());
    }
    return m_scriptDir;
  }
Exemplo n.º 25
0
  protected Browser make(int w, int h, Box b) {
    Log.log("OutputBox.debug", () -> "initializing browser");

    Browser browser =
        (Browser)
            find(Templates.templateChild, both())
                .findFirst()
                .map(x -> x.apply(b, "html output"))
                .orElseGet(() -> new Browser());

    Rect f = b.properties.get(frame);

    float inset = 10;
    browser.properties.put(Box.frame, new Rect(f.x + f.w - inset, f.y + f.h - inset, w, h));
    browser.properties.put(Boxes.dontSave, true);
    b.connect(browser);
    browser.loaded();
    this.properties.put(Boxes.dontSave, true);

    browser.properties.put(Box.name, "outputbox");
    styles = findAndLoad(styleSheet, false);

    long[] t = {0};

    boot(browser);

    browser.pauseForBoot();

    TextEditorExecution ed = new TextEditorExecution(browser);
    ed.connect(browser);

    return browser;
  }
Exemplo n.º 26
0
  /**
   * @param docContents should be == doc.get() (just optimizing if the user already did that
   *     before).
   */
  public static void setOnlyDifferentCode(IDocument doc, String docContents, String newContents) {
    String contents = docContents;
    if (contents == null) {
      contents = doc.get();
    }
    int minorLen;
    int contentsLen = contents.length();
    if (contentsLen > newContents.length()) {
      minorLen = newContents.length();
    } else {
      minorLen = contentsLen;
    }
    int applyFrom = 0;
    for (; applyFrom < minorLen; applyFrom++) {
      if (contents.charAt(applyFrom) == newContents.charAt(applyFrom)) {
        continue;
      } else {
        // different
        break;
      }
    }

    if (applyFrom >= contentsLen) {
      // Document is the same.
      return;
    }
    try {
      doc.replace(applyFrom, contentsLen - applyFrom, newContents.substring(applyFrom));
    } catch (BadLocationException e) {
      Log.log(e);
    }
  }
Exemplo n.º 27
0
  /**
   * Initialize the preferences system. This will load
   *
   * <ul>
   *   <li>general user prefs
   *   <li>user filter settings
   *   <li>user segmentation settings
   * </ul>
   *
   * from existing files in {@link StaticUtils#getConfigDir()} (and others for general prefs; see
   * {@link #getPreferencesFile()}) and set things up to create them via {@link #save()} if they
   * don't yet exist.
   *
   * <p>When the preferences system is required but actual user preferences shouldn't be loaded or
   * altered (testing scenarios), use {@link TestPreferencesInitializer} methods or be sure to set
   * the config dir with {@link RuntimePreferences#setConfigDir(String)} before calling this method.
   */
  public static synchronized void init() {
    if (didInit) {
      return;
    }
    didInit = true;
    File srxFile = new File(StaticUtils.getConfigDir(), SRX.CONF_SENTSEG);
    SRX srx = SRX.loadSRX(srxFile);
    if (srx == null) {
      srx = SRX.getDefault();
    }
    m_srx = srx;

    File filtersFile = new File(StaticUtils.getConfigDir(), FilterMaster.FILE_FILTERS);
    Filters filters = null;
    try {
      filters = FilterMaster.loadConfig(filtersFile);
    } catch (Exception ex) {
      Log.log(ex);
    }
    if (filters == null) {
      filters = FilterMaster.createDefaultFiltersConfig();
    }
    m_filters = filters;

    File loadFile = getPreferencesFile();
    File saveFile = new File(StaticUtils.getConfigDir(), Preferences.FILE_PREFERENCES);
    m_preferences = new PreferencesImpl(new PreferencesXML(loadFile, saveFile));
  }
Exemplo n.º 28
0
  /**
   * Adds a line to the document.
   *
   * @param doc the document
   * @param endLineDelim the delimiter that should be used
   * @param contents what should be added (the end line delimiter may be added before or after those
   *     contents (depending on what are the current contents of the document).
   * @param afterLine the contents should be added after the line specified here.
   */
  public static void addLine(IDocument doc, String endLineDelim, String contents, int afterLine) {
    try {

      int offset = -1;
      if (doc.getNumberOfLines() > afterLine) {
        offset = doc.getLineInformation(afterLine + 1).getOffset();

      } else {
        offset = doc.getLineInformation(afterLine).getOffset();
      }

      if (doc.getNumberOfLines() - 1 == afterLine) {
        contents = endLineDelim + contents;
      }

      if (!contents.endsWith(endLineDelim)) {
        contents += endLineDelim;
      }

      if (offset >= 0) {
        doc.replace(offset, 0, contents);
      }
    } catch (BadLocationException e) {
      Log.log(e);
    }
  }
Exemplo n.º 29
0
  public static boolean isSpam(User poster, String body, String ip) {
    Date lastPost = poster.getLastPost();
    Date curTime = new Date();
    DateFormat formatter =
        DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US);
    Date joinDate;

    if (poster.getIsMod()) return false;

    try {
      joinDate = formatter.parse(poster.getJoinDate());
    } catch (Exception e) {
      joinDate = new Date();
    }

    if (lastPost != null) {
      long diff = curTime.getTime() - lastPost.getTime();
      long userLen = curTime.getTime() - joinDate.getTime();
      long minInterval =
          (userLen < (Config.spamProbationPeriodDays * 1000 * 60 * 60 * 24))
              ? Config.spamPostIntervalMinsProbation
              : Config.spamPostIntervalMinsStandard;
      minInterval *= 1000 * 60;
      if (diff < minInterval) {
        Log.log("Filtered post from " + poster.getUsername(), Log.DEBUG);
        return true;
      }
    }

    poster.setLastPost(curTime);
    return false;
  }
Exemplo n.º 30
0
 public void unwrap(SMPPPacket packet) throws BufferException {
   Log.log("OptionalParameter.unwrap : unwrap elements !", 0x100800000000000L);
   tag = packet.getShort();
   length = packet.getShort();
   value = packet.getBytes(length);
   dump(0x800000000000L);
 }