Example #1
0
  /**
   * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by
   * the interface (and its superinterfaces) will be invocable.
   */
  public <T> InAppServer(
      String name,
      String portFilename,
      InetAddress inetAddress,
      Class<T> exportedInterface,
      T handler) {
    this.fullName = name + "Server";
    this.exportedInterface = exportedInterface;
    this.handler = handler;

    // In the absence of authentication, we shouldn't risk starting a server as root.
    if (System.getProperty("user.name").equals("root")) {
      Log.warn(
          "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!");
      return;
    }

    try {
      File portFile = FileUtilities.fileFromString(portFilename);
      secretFile = new File(portFile.getPath() + ".secret");
      Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName);
      // If there are no other threads left, the InApp server shouldn't keep us alive.
      serverThread.setDaemon(true);
      serverThread.start();
    } catch (Throwable th) {
      Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th);
    }
    writeNewSecret();
  }
  @Override
  protected Boolean doInBackground(Void... params) {
    File ffmpegFile = new File(FileUtils.getFFmpeg(context));
    if (ffmpegFile.exists() && isDeviceFFmpegVersionOld() && !ffmpegFile.delete()) {
      return false;
    }
    if (!ffmpegFile.exists()) {
      boolean isFileCopied =
          FileUtils.copyBinaryFromAssetsToData(
              context,
              cpuArchNameFromAssets + File.separator + FileUtils.ffmpegFileName,
              FileUtils.ffmpegFileName);

      // make file executable
      if (isFileCopied) {
        if (!ffmpegFile.canExecute()) {
          Log.d("FFmpeg is not executable, trying to make it executable ...");
          if (ffmpegFile.setExecutable(true)) {
            return true;
          }
        } else {
          Log.d("FFmpeg is executable");
          return true;
        }
      }
    }
    return ffmpegFile.exists() && ffmpegFile.canExecute();
  }
Example #3
0
  /**
   * Stop the proxy. Proxy must either implement {@link Closeable} or must have associated {@link
   * RpcInvocationHandler}.
   *
   * @param proxy the RPC proxy object to be stopped
   * @throws HadoopIllegalArgumentException if the proxy does not implement {@link Closeable}
   *     interface or does not have closeable {@link InvocationHandler}
   */
  public static void stopProxy(Object proxy) {
    if (proxy == null) {
      throw new HadoopIllegalArgumentException("Cannot close proxy since it is null");
    }
    try {
      if (proxy instanceof Closeable) {
        ((Closeable) proxy).close();
        return;
      } else {
        InvocationHandler handler = Proxy.getInvocationHandler(proxy);
        if (handler instanceof Closeable) {
          ((Closeable) handler).close();
          return;
        }
      }
    } catch (IOException e) {
      LOG.error("Closing proxy or invocation handler caused exception", e);
    } catch (IllegalArgumentException e) {
      LOG.error("RPC.stopProxy called on non proxy: class=" + proxy.getClass().getName(), e);
    }

    // If you see this error on a mock object in a unit test you're
    // developing, make sure to use MockitoUtil.mockProtocol() to
    // create your mock.
    throw new HadoopIllegalArgumentException(
        "Cannot close proxy - is not Closeable or "
            + "does not provide closeable invocation handler "
            + proxy.getClass());
  }
Example #4
0
 /* Uses resource to create default file, if file does not yet exist */
 public boolean createDefaultFileFromResource(String resourcename, File deffile) {
   if (deffile.canRead()) return true;
   Log.info(deffile.getPath() + " not found - creating default");
   InputStream in = getClass().getResourceAsStream(resourcename);
   if (in == null) {
     Log.severe("Unable to find default resource - " + resourcename);
     return false;
   } else {
     FileOutputStream fos = null;
     try {
       fos = new FileOutputStream(deffile);
       byte[] buf = new byte[512];
       int len;
       while ((len = in.read(buf)) > 0) {
         fos.write(buf, 0, len);
       }
     } catch (IOException iox) {
       Log.severe("ERROR creatomg default for " + deffile.getPath());
       return false;
     } finally {
       if (fos != null)
         try {
           fos.close();
         } catch (IOException iox) {
         }
       if (in != null)
         try {
           in.close();
         } catch (IOException iox) {
         }
     }
     return true;
   }
 }
  /** Handle receiving a MMS message */
  private void handleMmsReceived(Intent intent) {
    if (Log.DEBUG) Log.v("MMS received!");
    SmsMmsMessage mmsMessage = null;
    int count = 0;

    // Ok this is super hacky, but fixes the case where this code
    // runs before the system MMS transaction service (that stores
    // the MMS details in the database). This should really be
    // a content listener that waits for a while then gives up...
    while (mmsMessage == null && count < MESSAGE_RETRY) {

      mmsMessage = SmsPopupUtils.getMmsDetails(context);

      if (mmsMessage != null) {
        if (Log.DEBUG) Log.v("MMS found in content provider");
        notifyMessageReceived(mmsMessage);
      } else {
        if (Log.DEBUG) Log.v("MMS not found, sleeping (count is " + count + ")");
        count++;
        try {
          Thread.sleep(MESSAGE_RETRY_PAUSE);
        } catch (InterruptedException e) {
          // e.printStackTrace();
        }
      }
    }
  }
Example #6
0
  public void init() throws ServletException {
    try {
      // Load configuration (from classpath or WEB-INF root path)
      String webInfPath = getServletContext().getRealPath("/") + "/WEB-INF";
      Config.load(webInfPath);
      Log.init();
      // Start
      Log.info(
          "init() Pushlet Webapp - version="
              + Version.SOFTWARE_VERSION
              + " built="
              + Version.BUILD_DATE);
      // Start session manager
      SessionManager.getInstance().start();
      // Start event Dispatcher
      Dispatcher.getInstance().start();

      if (Config.getBoolProperty(Config.SOURCES_ACTIVATE)) {
        EventSourceManager.start(webInfPath);
      } else {
        Log.info("Not starting local event sources");
      }
    } catch (Throwable t) {
      throw new ServletException("Failed to initialize Pushlet framework " + t, t);
    }
  }
Example #7
0
    /**
     * May be called from within timeReached(), but schedule() is better there.
     *
     * @param timeoutMs
     * @param useEarliestTime if its already scheduled, use the earlier of the two timeouts, else
     *     use the later
     */
    public synchronized void reschedule(long timeoutMs, boolean useEarliestTime) {
      final long now = System.currentTimeMillis();
      long oldTimeout;
      boolean scheduled = _state == TimedEventState.SCHEDULED;
      if (scheduled) oldTimeout = _nextRun - now;
      else oldTimeout = timeoutMs;

      // don't bother rescheduling if within _fuzz ms
      if ((oldTimeout - _fuzz > timeoutMs && useEarliestTime)
          || (oldTimeout + _fuzz < timeoutMs && !useEarliestTime)
          || (!scheduled)) {
        if (scheduled && (now + timeoutMs) < _nextRun) {
          if (_log.shouldLog(Log.INFO))
            _log.info(
                "Re-scheduling: "
                    + this
                    + " timeout = "
                    + timeoutMs
                    + " old timeout was "
                    + oldTimeout
                    + " state: "
                    + _state);
          cancel();
        }
        schedule(timeoutMs);
      }
    }
Example #8
0
  public void handleMoving(String[] fields) {
    String volunteerString = fields[1];
    String startString = fields[2];
    String destinationString = fields[3];
    int transitTime = Integer.parseInt(fields[4]);

    Log.i(
        "MOVING: volunteer=%s start=%s destination=%s transitTime=%d",
        volunteerString, startString, destinationString, transitTime);

    Volunteer volunteer = model.getVolunteerByName(volunteerString);
    if (volunteer == null) {
      Log.w("Haven't seen moving volunteer %s yet", volunteerString);
      return;
    }

    Location start = model.getLocationByName(startString);
    if (start == null) {
      Log.w("Haven't see start location %s yet", startString);
      return;
    }

    Location destination = model.getLocationByName(destinationString);
    if (destination == null) {
      Log.w("Haven't seen destination location %s yet", destinationString);
      return;
    }

    if (!start.getName().equals(startString))
      Log.w(
          "MOVING violation: %s not at %s but rather at %s",
          volunteerString, startString, start.getName());

    volunteer.startMoving(destination, transitTime);
  }
Example #9
0
  public void handleRequest(String[] fields) {
    String requesterName = fields[1];
    String startString = fields[2];
    String destinationString = fields[3];
    int value = Integer.parseInt(fields[4]);

    Log.i(
        "REQUEST: requester=%s start=%s, destination=%s value=%d",
        requesterName, startString, destinationString, value);

    // Remove any old request with the same name...
    Request request = model.getRequestByName(requesterName);
    if (request != null) model.removeRequest(request);

    Location start = model.getLocationByName(startString);
    Location destination = model.getLocationByName(destinationString);

    if (start == null) {
      Log.w("Haven't see the request start location %s yet", startString);
      return;
    }

    if (destination == null) {
      Log.w("Haven't see the request destination location %s yet", destinationString);
      return;
    }

    new Request(model, requesterName, start, destination, value);
  }
Example #10
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 ");
  }
Example #11
0
  private String exec(final String... cmd) throws IOException, InterruptedException {
    assert cmd != null;

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    Log.trace("Running: ", cmd);

    Process p = Runtime.getRuntime().exec(cmd);

    InputStream in = null;
    InputStream err = null;
    OutputStream out = null;
    try {
      int c;
      in = p.getInputStream();
      while ((c = in.read()) != -1) {
        bout.write(c);
      }
      err = p.getErrorStream();
      while ((c = err.read()) != -1) {
        bout.write(c);
      }
      out = p.getOutputStream();
      p.waitFor();
    } finally {
      close(in, out, err);
    }

    String result = bout.toString();

    Log.trace("Result: ", result);

    return result;
  }
  public void recalculateCodebooks() throws IOException {
    String dir =
        "/Users/thomaskaiser/Documents/MCM/MC480_Project_I/SVN/trunk/Implementation/ProjectFiles/mobile phone folder structure";
    HashMap<String, String> sampleDirectories = readSampleDirectories(dir);
    Set<String> keySet = sampleDirectories.keySet();

    for (String speakerId : keySet) {
      Log.d("Recalculating codebook for %s", speakerId);
      FeatureVector pl = null;
      try {
        pl = readFeatureVectorFile(sampleDirectories.get(speakerId));
      } catch (Exception e) {
        Log.e("Error reading feature vector", e);
      }

      KMeans kmeans = new KMeans(Constants.CLUSTER_COUNT, pl, Constants.CLUSTER_MAX_ITERATIONS);
      Log.d("Prepared k means clustering");
      long start = System.currentTimeMillis();
      kmeans.run();
      Log.d("Clustering finished, total time = " + (System.currentTimeMillis() - start) + "ms");

      Codebook cb = makeCodebook(kmeans);

      writeCodebook(sampleDirectories.get(speakerId), cb);
    }
  }
Example #13
0
 // Return null when we cannot instantiate a BlobCache, e.g.:
 // there is no SD card found.
 // This can only be called from data thread.
 public static BlobCache getCache(
     Context context, String filename, int maxEntries, int maxBytes, int version) {
   synchronized (sCacheMap) {
     if (!sOldCheckDone) {
       removeOldFilesIfNecessary(context);
       sOldCheckDone = true;
     }
     BlobCache cache = sCacheMap.get(filename);
     if (cache == null) {
       /// M: [BEHAVIOR.MODIFY] @{
       /*File cacheDir = context.getExternalCacheDir();*/
       File cacheDir = FeatureHelper.getExternalCacheDir(context);
       if (cacheDir == null) {
         Log.e(TAG, "<getCache> failed to get cache dir");
         return null;
       }
       /// @}
       String path = cacheDir.getAbsolutePath() + "/" + filename;
       try {
         /// M: [DEBUG.ADD] @{
         Log.i(TAG, "<getCache> new BlobCache, path = " + path);
         /// @}
         cache = new BlobCache(path, maxEntries, maxBytes, false, version);
         sCacheMap.put(filename, cache);
       } catch (IOException e) {
         Log.e(TAG, "Cannot instantiate cache!", e);
       }
     }
     return cache;
   }
 }
Example #14
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));
			}
		}
  /** Validate basic store return values. */
  public boolean testAStoreReturnedSystemRecord() {
    if (!setupOK) addTag(Tag.MISSINGDEP, "failed some dependency");
    addTag(Tag.SMOKE);
    addTag(Tag.REGRESSION);
    addTag(Tag.QUICK);
    addTag(Tag.SMOKE);
    addTag(HoneycombTag.EMULATOR);

    addBug(
        "6187594",
        "client API isn't returning data hash; "
            + "can't query on data hash (md hash not supported by design)");

    addBug(
        "6216444",
        "On successful store or storeMetadata, "
            + "SystemRecord.getDigestAlgorithm() returns null");

    if (excludeCase()) return false;

    String errors = HoneycombTestClient.validateSystemRecord(storeResult.sr, getFilesize());
    if (!errors.equals("")) {
      Log.ERROR("Test failed for the following reasons: " + errors);
      return (false);
    }

    Log.INFO("Successfully verified the return result from store");
    return (true);
  }
Example #16
0
  @Override
  public final void verify(Log log) {
    // *** const_double ***
    // Connection should go up, down and back up
    log.matchConnections(const_double, true, false, true);
    // Value should remain the same, but change alarm
    log.matchValues(
        const_double,
        ALL,
        const_double_value,
        newVDouble(
            const_double_value.getValue(),
            newAlarm(AlarmSeverity.UNDEFINED, "Disconnected"),
            const_double_value,
            const_double_value),
        const_double_value);
    // No errors
    log.matchErrors(const_double);

    // *** const_string ***
    // Connection should go up, down and back up
    // log.matchConnections(const_string, true, false, true);
    // Value should remain the same, but change alarm
    //        log.matchValues(const_string, ALL,
    //                const_string_value,
    //                newVString(const_string_value.getValue(), newAlarm(AlarmSeverity.UNDEFINED,
    // "Disconnected"), const_string_value),
    //                const_string_value);
    //        // No errors
    //        log.matchErrors(const_string);
  }
  public void handleEvent(GameEvent event, V086Controller.V086ClientHandler clientHandler) {
    handledCount++;

    GameTimeoutEvent timeoutEvent = (GameTimeoutEvent) event;
    KailleraUser player = timeoutEvent.getUser();
    KailleraUser user = clientHandler.getUser();

    if (player.equals(user)) {
      log.debug(
          user
              + " received timeout event "
              + timeoutEvent.getTimeoutNumber()
              + " for "
              + timeoutEvent.getGame()
              + ": resending messages...");
      clientHandler.resend(timeoutEvent.getTimeoutNumber());
    } else {
      log.debug(
          user
              + " received timeout event "
              + timeoutEvent.getTimeoutNumber()
              + " from "
              + player
              + " for "
              + timeoutEvent.getGame());
    }
  }
Example #18
0
 public static Alarm calculateNextAlert(final Context context) {
   Alarm alarm = null;
   long minTime = Long.MAX_VALUE;
   long now = System.currentTimeMillis();
   Cursor cursor = getFilteredAlarmsCursor(context.getContentResolver());
   if (cursor != null) {
     if (cursor.moveToFirst()) {
       do {
         Alarm a = new Alarm(context, cursor);
         // A time of 0 indicates this is a repeating alarm, so
         // calculate the time to get the next alert.
         if (a.time == 0) {
           a.time = calculateAlarm(a);
         } else if (a.time < now) {
           Log.v("Disabling expired alarm set for " + Log.formatTime(a.time));
           // Expired alarm, disable it and move along.
           enableAlarmInternal(context, a, false);
           continue;
         }
         if (a.time < minTime) {
           minTime = a.time;
           alarm = a;
         }
       } while (cursor.moveToNext());
     }
     cursor.close();
   }
   return alarm;
 }
Example #19
0
  /** Servlet GET request: handles event requests. */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Event event = null;

    try {
      // Event parm identifies event type from the client
      String eventType = Servlets.getParameter(request, P_EVENT);

      // Always must have an event type
      if (eventType == null) {
        Log.warn("Pushlet.doGet(): bad request, no event specified");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No eventType specified");
        return;
      }
      // Create Event and set attributes from parameters
      event = new Event(eventType);
      for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
        String nextAttribute = (String) e.nextElement();
        event.setField(nextAttribute, request.getParameter(nextAttribute));
      }
    } catch (Throwable t) {
      // Error creating event
      Log.warn("Pushlet: Error creating event in doGet(): ", t);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    // Handle parsed request
    doRequest(event, request, response);
  }
  /**
   * Version-dependent support for generating a dummy disk store from the given cache and disk store
   * configuration.
   */
  protected static void generateDummyDiskStore(
      Cache dummyCache, String diskStoreConfig, String fn, Map XmlDiskStoreConfigs) {
    DiskStoreDescription dsd = DiskStoreHelper.getDiskStoreDescription(diskStoreConfig);
    DiskStoreFactory dummyFactory = ((CacheCreation) dummyCache).createDiskStoreFactory();
    dsd.configure(dummyFactory);
    String diskStoreName = dsd.getName();
    DiskStore dummyDiskStore = null;
    try {
      dummyDiskStore = dummyFactory.create(diskStoreName);
    } catch (IllegalStateException e) {
      String msg = "A disk store named \"" + diskStoreName + "\" already exists.";
      if (e.getMessage().equals(msg)) {
        if (!XmlDiskStoreConfigs.values().contains(diskStoreConfig)) {
          String s =
              "DiskStore with configuration "
                  + diskStoreConfig
                  + " named "
                  + diskStoreName
                  + " was already created without CacheHelper XML using"
                  + " an unknown, and possibly different, configuration";
          throw new HydraRuntimeException(s);
        } // else the configuration was done here, which is fine
      } else {
        throw e;
      }
    }
    if (Log.getLogWriter().infoEnabled()) {
      Log.getLogWriter()
          .info("Added dummy disk store: " + DiskStoreHelper.diskStoreToString(dummyDiskStore));
    }

    // save the disk store config for future reference
    XmlDiskStoreConfigs.put(fn, diskStoreConfig);
  }
Example #21
0
  public ConfigurationNode getWorldConfiguration(World world) {
    ConfigurationNode finalConfiguration = new ConfigurationNode();
    finalConfiguration.put("name", world.getName());
    finalConfiguration.put("title", world.getName());

    ConfigurationNode worldConfiguration = getWorldConfigurationNode(world.getName());

    // Get the template.
    ConfigurationNode templateConfiguration = null;
    if (worldConfiguration != null) {
      String templateName = worldConfiguration.getString("template");
      if (templateName != null) {
        templateConfiguration = getTemplateConfigurationNode(templateName);
      }
    }

    // Template not found, using default template.
    if (templateConfiguration == null) {
      templateConfiguration = getDefaultTemplateConfigurationNode(world);
    }

    // Merge the finalConfiguration, templateConfiguration and worldConfiguration.
    finalConfiguration.extend(templateConfiguration);
    finalConfiguration.extend(worldConfiguration);

    Log.verboseinfo("Configuration of world " + world.getName());
    for (Map.Entry<String, Object> e : finalConfiguration.entrySet()) {
      Log.verboseinfo(e.getKey() + ": " + e.getValue());
    }

    return finalConfiguration;
  }
Example #22
0
  private static void startWebSocketServer() {
    WebSocketCallback callback = new WebSocketCallback();

    String ip = "0.0.0.0";
    try {
      Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        // filters out 127.0.0.1 and inactive interfaces
        if (iface.isLoopback() || !iface.isUp()) continue;

        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress addr = addresses.nextElement();
          ip = addr.getHostAddress();
          Log.info(iface.getDisplayName() + " " + ip);
        }
      }
    } catch (SocketException e) {
      throw new RuntimeException(e);
    }

    Log.info("Starting server...");
    final String host = "0.0.0.0";
    Undertow server =
        Undertow.builder()
            .addHttpListener(8081, host)
            .setHandler(path().addPrefixPath("/ev3", websocket(callback)))
            .build();
    server.start();
    Log.info("Server started.");
    Log.info("Listening on " + ip + ":8081/ev3");
  }
Example #23
0
  protected void unpackComponents() throws IOException, FileNotFoundException {
    File applicationPackage = new File(getApplication().getPackageResourcePath());
    File componentsDir = new File(sGREDir, "components");
    if (componentsDir.lastModified() == applicationPackage.lastModified()) return;

    componentsDir.mkdir();
    componentsDir.setLastModified(applicationPackage.lastModified());

    GeckoAppShell.killAnyZombies();

    ZipFile zip = new ZipFile(applicationPackage);

    byte[] buf = new byte[32768];
    try {
      if (unpackFile(zip, buf, null, "removed-files")) removeFiles();
    } catch (Exception ex) {
      // This file may not be there, so just log any errors and move on
      Log.w(LOG_FILE_NAME, "error removing files", ex);
    }

    // copy any .xpi file into an extensions/ directory
    Enumeration<? extends ZipEntry> zipEntries = zip.entries();
    while (zipEntries.hasMoreElements()) {
      ZipEntry entry = zipEntries.nextElement();
      if (entry.getName().startsWith("extensions/") && entry.getName().endsWith(".xpi")) {
        Log.i("GeckoAppJava", "installing extension : " + entry.getName());
        unpackFile(zip, buf, entry, entry.getName());
      }
    }
  }
  /**
   * Scan all output dirs for artifacts and remove those files (artifacts?) that are not recognized
   * as such, in the javac_state file.
   */
  public void removeUnidentifiedArtifacts() {
    Set<File> allKnownArtifacts = new HashSet<>();
    for (Package pkg : prev.packages().values()) {
      for (File f : pkg.artifacts().values()) {
        allKnownArtifacts.add(f);
      }
    }
    // Do not forget about javac_state....
    allKnownArtifacts.add(javacState);

    for (File f : binArtifacts) {
      if (!allKnownArtifacts.contains(f)) {
        Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state.");
        f.delete();
      }
    }
    for (File f : headerArtifacts) {
      if (!allKnownArtifacts.contains(f)) {
        Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state.");
        f.delete();
      }
    }
    for (File f : gensrcArtifacts) {
      if (!allKnownArtifacts.contains(f)) {
        Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state.");
        f.delete();
      }
    }
  }
Example #25
0
 private KeyboardEvent getKeyboardEventFromRegistry(String path) {
   NullCheck.notNull(path, "path");
   final Settings.HotKey proxy = Settings.createHotKey(registry, path);
   KeyboardEvent.Special special = null;
   char c = ' ';
   final String specialStr = proxy.getSpecial("");
   if (!specialStr.trim().isEmpty()) {
     special = KeyboardEvent.translateSpecial(specialStr);
     if (special == null) {
       Log.error(
           "core",
           "registry path "
               + path
               + " tries to use an unknown special keyboard code \'"
               + specialStr
               + "\'");
       return null;
     }
   } else {
     final String charStr = proxy.getCharacter("");
     if (charStr.isEmpty()) {
       Log.error(
           "core",
           "registry path "
               + path
               + " does not contain neither \'special\' nor \'character\' values");
       return null;
     }
     c = charStr.charAt(0);
   }
   final boolean withControl = proxy.getWithControl(false);
   final boolean withShift = proxy.getWithShift(false);
   final boolean withAlt = proxy.getWithAlt(false);
   return new KeyboardEvent(special != null, special, c, withShift, withControl, withAlt);
 }
Example #26
0
  /**
   * Test that applying data as an operation to get back a copy of the data works correctly.
   *
   * <p>The other tests assume that this test always passes.
   *
   * @param numIterations
   */
  public void testDataOperationEquivalence(int numIterations) {
    log.info("TESTING testDataOperationEquivalence");
    Random r = new Random(0);

    for (int iteration = 0; iteration < numIterations; iteration++) {
      log.info("Iteration: " + iteration);

      D d1 = domain.initialState();

      try {
        for (int i = 0; i < INITIAL_MUTATION_COUNT; i++) {
          O op = generator.randomOperation(d1, r);
          domain.apply(op, d1);

          D d2 = domain.initialState();
          domain.apply(domain.asOperation(d1), d2);

          if (!domain.equivalent(d1, d2)) {
            log.inconsistent(
                "DATA-AS-OPERATION BUG",
                "Subiteration: " + i,
                "Op from data: " + domain.asOperation(d1),
                "Data: " + d1,
                "Result of op on fresh state: " + d2);
          }
        }
      } catch (OperationException e) {
        logException("DATA-AS-OPERATION BUG? Operation exception", e);
      } catch (RuntimeException e) {
        logException("DATA-AS-OPERATION BUG? Runtime exception", e);
      }
    }
  }
 private void a(CircuitBreaker circuitBreaker, byte[] bArr, String str) {
   if (!circuitBreaker.b()) {
     try {
       OutputStream bufferedOutputStream = new BufferedOutputStream(a(str));
       try {
         a(bufferedOutputStream, bArr);
         try {
           bufferedOutputStream.flush();
           bufferedOutputStream.close();
         } catch (IOException e) {
         }
       } catch (IOException e2) {
         try {
           Log.w(a, "Caught IOException while writing asset to disk: %s", new Object[] {str});
           circuitBreaker.a();
           try {
             bufferedOutputStream.flush();
             bufferedOutputStream.close();
           } catch (IOException e3) {
           }
         } catch (Throwable th) {
           try {
             bufferedOutputStream.flush();
             bufferedOutputStream.close();
           } catch (IOException e4) {
           }
         }
       }
     } catch (IOException e5) {
       Log.e(a, "Could not write an asset to disk: %s", new Object[] {str});
       circuitBreaker.a();
     }
   }
 }
 public static void setReminder(
     Context context,
     long id,
     String title,
     long dueDate,
     long listId,
     long reminderDate,
     long reminderInterval) {
   String actionName = context.getResources().getString(R.string.intent_action_alarm);
   Intent alarmIntent = new Intent(actionName);
   alarmIntent.putExtra(NotificationUtils.ID, id);
   alarmIntent.putExtra(NotificationUtils.TITLE, title);
   alarmIntent.putExtra(NotificationUtils.DUE_DATE, dueDate);
   alarmIntent.putExtra(NotificationUtils.LIST_ID, listId);
   PendingIntent alarmPendingIntent =
       PendingIntent.getBroadcast(context, getNotificationId(id), alarmIntent, 0);
   AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   if (reminderInterval > 0) {
     alarmManager.setRepeating(
         AlarmManager.RTC_WAKEUP, reminderDate, reminderInterval, alarmPendingIntent);
     if (Log.LOGV) Log.v("TaskDetailDialog set recurring reminder at " + dueDate);
   } else {
     alarmManager.set(AlarmManager.RTC_WAKEUP, reminderDate, alarmPendingIntent);
     if (Log.LOGV) Log.v("TaskDetailDialog set reminder at " + dueDate);
   }
 }
Example #29
0
    // Register  protocol and its impl for rpc calls
    void registerProtocolAndImpl(RpcKind rpcKind, Class<?> protocolClass, Object protocolImpl) {
      String protocolName = RPC.getProtocolName(protocolClass);
      long version;

      try {
        version = RPC.getProtocolVersion(protocolClass);
      } catch (Exception ex) {
        LOG.warn("Protocol " + protocolClass + " NOT registered as cannot get protocol version ");
        return;
      }

      getProtocolImplMap(rpcKind)
          .put(
              new ProtoNameVer(protocolName, version),
              new ProtoClassProtoImpl(protocolClass, protocolImpl));
      LOG.debug(
          "RpcKind = "
              + rpcKind
              + " Protocol Name = "
              + protocolName
              + " version="
              + version
              + " ProtocolImpl="
              + protocolImpl.getClass().getName()
              + " protocolClass="
              + protocolClass.getName());
    }
  /**
   * 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;
  }