Beispiel #1
0
  @Override
  protected void doWork() {
    String key = "javaDevguideExampleCounter";
    // Remove document so we have predictable behavior in this example
    try {
      bucket.remove(key);
    } catch (DocumentDoesNotExistException e) {
      // do nothing, the document is already not here
    }

    try {
      bucket.counter(key, 20);
    } catch (DocumentDoesNotExistException e) {
      LOGGER.info(
          "The counter method failed because the counter doesn't exist yet and no initial value was provided");
    }

    JsonLongDocument rv = bucket.counter(key, 20, 100);
    LOGGER.info("Delta=20, Initial=100. Current value is: " + rv.content());

    rv = bucket.counter(key, 1);
    LOGGER.info("Delta=1. Current value is: " + rv.content());

    rv = bucket.counter(key, -50);
    LOGGER.info("Delta=-50. Current value is: " + rv.content());
  }
  public ResPackage loadMainPkg(ResTable resTable, ExtFile apkFile) throws AndrolibException {
    LOGGER.info("Loading resource table...");
    ResPackage[] pkgs = getResPackagesFromApk(apkFile, resTable, sKeepBroken);
    ResPackage pkg = null;

    switch (pkgs.length) {
      case 1:
        pkg = pkgs[0];
        break;
      case 2:
        if (pkgs[0].getName().equals("android")) {
          LOGGER.warning("Skipping \"android\" package group");
          pkg = pkgs[1];
        } else if (pkgs[0].getName().equals("com.htc")) {
          LOGGER.warning("Skipping \"htc\" stupid package group");
          pkg = pkgs[1];
        }
        break;
    }

    if (pkg == null) {
      throw new AndrolibException("Arsc files with zero or multiple packages");
    }

    resTable.addPackage(pkg, true);
    LOGGER.info("Loaded.");
    return pkg;
  }
    @Override
    protected SimulatorOperation newOperation() {
      List testsuiteFiles = options.nonOptionArguments();
      File testSuiteFile;
      if (testsuiteFiles.size() > 1) {
        throw new CommandLineExitException(
            format("Too many TestSuite files specified: %s", testsuiteFiles));
      } else if (testsuiteFiles.size() == 1) {
        testSuiteFile = new File((String) testsuiteFiles.get(0));
      } else {
        testSuiteFile = new File("test.properties");
      }

      LOGGER.info("File:" + testSuiteFile);

      TestSuite suite =
          TestSuite.loadTestSuite(testSuiteFile, "")
              .setDurationSeconds(getDurationSeconds(options, durationSpec))
              .setWorkerQuery(newQuery())
              .setParallel(options.has(parallelSpec))
              .setVerifyEnabled(options.valueOf(verifyEnabledSpec))
              .setFailFast(options.valueOf(failFastSpec));

      if (options.has(warmupSpec)) {
        suite.setWarmupSeconds(getDurationSeconds(options, warmupSpec));
      }

      LOGGER.info("Running testSuite:" + testSuiteFile.getAbsolutePath());
      return new RcTestRunOperation(suite, isAsync(), newQuery());
    }
Beispiel #4
0
  /** Creates a hudson.PluginStrategy, looking at the corresponding system property. */
  protected PluginStrategy createPluginStrategy() {
    String strategyName = System.getProperty(PluginStrategy.class.getName());
    if (strategyName != null) {
      try {
        Class<?> klazz = getClass().getClassLoader().loadClass(strategyName);
        Object strategy = klazz.getConstructor(PluginManager.class).newInstance(this);
        if (strategy instanceof PluginStrategy) {
          LOGGER.info("Plugin strategy: " + strategyName);
          return (PluginStrategy) strategy;
        } else {
          LOGGER.warning(
              "Plugin strategy (" + strategyName + ") is not an instance of hudson.PluginStrategy");
        }
      } catch (ClassNotFoundException e) {
        LOGGER.warning("Plugin strategy class not found: " + strategyName);
      } catch (Exception e) {
        LOGGER.log(
            WARNING,
            "Could not instantiate plugin strategy: "
                + strategyName
                + ". Falling back to ClassicPluginStrategy",
            e);
      }
      LOGGER.info("Falling back to ClassicPluginStrategy");
    }

    // default and fallback
    return new ClassicPluginStrategy(this);
  }
    @Override
    public void run() {

      try (RandomAccessFile f = new RandomAccessFile(plotFile.getPlotFile(), "r")) {
        long chunks = plotFile.getPlots() / plotFile.getStaggeramt();
        for (long i = 0; i < chunks; i++) {
          f.seek(
              (i * plotFile.getStaggeramt() * MiningPlot.PLOT_SIZE)
                  + (scoopnum * plotFile.getStaggeramt() * MiningPlot.SCOOP_SIZE));
          byte[] chunk = new byte[(int) (plotFile.getStaggeramt() * MiningPlot.SCOOP_SIZE)];
          f.readFully(chunk);
          if (poolType.equals(POOL_TYPE_URAY)) {
            checkChunkPoolUray(chunk, plotFile.getStartnonce() + (i * plotFile.getStaggeramt()));
          } else if (poolType.equals(POOL_TYPE_OFFICIAL)) {
            checkChunkPoolOfficial(
                chunk, plotFile.getStartnonce() + (i * plotFile.getStaggeramt()));
          }
          if (!running) return;
        }
      } catch (FileNotFoundException e) {
        LOGGER.info("Cannot open file: " + plotFile.getPlotFile().getName());
        e.printStackTrace();
      } catch (IOException e) {
        LOGGER.info("Error reading file: " + plotFile.getPlotFile().getName());
      }

      LOGGER.info("Finished mining {" + plotFile.getUUID() + "}");
      plotFile.addChecked();
      minerThreads.remove(this);
    }
 @Override
 public void run() {
   String shareRequest =
       plotFile.getAddress()
           + ":"
           + nonce
           + ":"
           + processing.getHeight()
           + " deadline {"
           + deadline
           + "}";
   LOGGER.info("Submitting share {" + shareRequest + "}");
   try {
     if (poolType.equals(POOL_TYPE_URAY)) {
       String request =
           poolUrl
               + "/burst?requestType=submitNonce&secretPhrase=pool-mining&nonce="
               + Convert.toUnsignedLong(nonce)
               + "&accountId="
               + Convert.toUnsignedLong(plotFile.getAddress());
       String response = restTemplate.postForObject(request, shareRequest, String.class);
       LOGGER.info("Response {" + response + "}}");
       plotFile.addShare();
     } else if (poolType.equals(POOL_TYPE_OFFICIAL)) {
       shareRequest = plotFile.getAddress() + ":" + nonce + ":" + processing.getHeight() + "\n";
       String response =
           restTemplate.postForObject(poolUrl + "/pool/submitWork", shareRequest, String.class);
       LOGGER.info("Response {" + response + "}}");
       plotFile.addShare();
     }
     lastShareSubmitTime = System.currentTimeMillis();
   } catch (Exception ex) {
     LOGGER.info("Failed to submitShare {" + shareRequest + "}");
   }
 }
Beispiel #7
0
 /* (non-Javadoc)
  * @see java.lang.Thread#run()
  */
 public void run() {
   try {
     LOGGER.info("Start " + getName() + ", (running = " + running + ")");
     while (running) {
       try {
         work();
       } catch (Throwable t) {
         if (running)
           LOGGER.log(
               Level.WARNING,
               "Exception \"" + t + "\" in thread " + getName() + ": running=" + running,
               t);
         else
           LOGGER.info(
               "Exception \""
                   + t
                   + "\" in thread "
                   + getName()
                   + " has successfully stopped socket thread");
       }
     }
   } finally {
     LOGGER.info(getName() + " has terminated (running = " + running + ")");
   }
 }
Beispiel #8
0
 public void run() {
   String threadName = Thread.currentThread().getName();
   Thread.currentThread().setName("SCM polling for " + job);
   try {
     startTime = System.currentTimeMillis();
     if (runPolling()) {
       AbstractProject p = job.asProject();
       String name = " #" + p.getNextBuildNumber();
       SCMTriggerCause cause;
       try {
         cause = new SCMTriggerCause(getLogFile());
       } catch (IOException e) {
         LOGGER.log(WARNING, "Failed to parse the polling log", e);
         cause = new SCMTriggerCause();
       }
       if (p.scheduleBuild(p.getQuietPeriod(), cause, additionalActions)) {
         LOGGER.info("SCM changes detected in " + job.getName() + ". Triggering " + name);
       } else {
         LOGGER.info(
             "SCM changes detected in " + job.getName() + ". Job is already in the queue");
       }
     }
   } finally {
     Thread.currentThread().setName(threadName);
   }
 }
    @Override
    public void run() {
      LOGGER.info("ClusterManager thread starting.");

      long delay = taskManager.getConfiguration().getNodeRegistrationCycleTime() * 1000L;
      while (canRun) {

        OperationResult result = new OperationResult(ClusterManagerThread.class + ".run");

        try {

          checkSystemConfigurationChanged(result);

          // these checks are separate in order to prevent a failure in one method blocking
          // execution of others
          try {
            checkClusterConfiguration(result); // if error, the scheduler will be stopped
            nodeRegistrar.updateNodeObject(
                result); // however, we want to update repo even in that case
          } catch (Throwable t) {
            LoggingUtils.logException(
                LOGGER,
                "Unexpected exception while checking cluster configuration; continuing execution.",
                t);
          }

          try {
            checkWaitingTasks(result);
          } catch (Throwable t) {
            LoggingUtils.logException(
                LOGGER,
                "Unexpected exception while checking waiting tasks; continuing execution.",
                t);
          }

          try {
            checkStalledTasks(result);
          } catch (Throwable t) {
            LoggingUtils.logException(
                LOGGER,
                "Unexpected exception while checking stalled tasks; continuing execution.",
                t);
          }

        } catch (Throwable t) {
          LoggingUtils.logException(
              LOGGER, "Unexpected exception in ClusterManager thread; continuing execution.", t);
        }

        LOGGER.trace("ClusterManager thread sleeping for " + delay + " msec");
        try {
          Thread.sleep(delay);
        } catch (InterruptedException e) {
          LOGGER.trace("ClusterManager thread interrupted.");
        }
      }

      LOGGER.info("ClusterManager thread stopping.");
    }
 @Override
 public void load() {
   _expTable.clear();
   parseDatapackFile("stats/experience.xml");
   LOGGER.info(getClass().getSimpleName() + ": Loaded " + _expTable.size() + " levels.");
   LOGGER.info(getClass().getSimpleName() + ": Max Player Level is: " + (MAX_LEVEL - 1));
   LOGGER.info(getClass().getSimpleName() + ": Max Pet Level is: " + (MAX_PET_LEVEL - 1));
 }
 @Override
 public void messageSent(IoSession session, Object message) throws Exception {
   LOGGER.info("SenderHandler: messageSent");
   if (message == this.message) {
     LOGGER.info("message == this.message");
     latch.countDown();
   }
 }
  /**
   * @param username
   * @return
   * @throws UsernameNotFoundException
   * @throws DataAccessException
   */
  @Override
  public UserDetails loadUserByUsername(String username)
      throws UsernameNotFoundException, DataAccessException {
    UserDetails user = null;
    String connectionString;

    connectionString = "jdbc:mysql://" + myServer + "/" + myDatabase;
    LOGGER.info("MySQLSecurity: Connection String - " + connectionString);
    Connection conn = null;
    try {
      // Connect to the database
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      conn = DriverManager.getConnection(connectionString, myUsername, myPassword);
      LOGGER.info("MySQLSecurity: Connection established.");

      // Prepare the statement and query the user table
      // TODO: Review userQuery to see if there's a better way to do this
      String userQuery = "SELECT * FROM " + myDataTable + " WHERE " + myUserField + " = ?";
      PreparedStatement statement = conn.prepareStatement(userQuery);
      // statement.setString(1, myDataTable);
      // statement.setString(2, myUserField);
      statement.setString(1, username);
      ResultSet results = statement.executeQuery();
      LOGGER.fine("MySQLSecurity: Query executed.");

      // Grab the first result (should be only user returned)
      if (results.first()) {
        // Build the user detail
        Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>();
        groups.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
        user =
            new MySQLUserDetail(
                username,
                results.getString(myPassField),
                true,
                true,
                true,
                true,
                groups.toArray(new GrantedAuthority[groups.size()]));
      } else {
        LOGGER.warning("MySQLSecurity: Invalid Username or Password");
        throw new UsernameNotFoundException("MySQL: User not found");
      }

    } catch (Exception e) {
      LOGGER.warning("MySQLSecurity Realm Error: " + e.getLocalizedMessage());
    } finally {
      if (conn != null) {
        try {
          conn.close();
          LOGGER.info("MySQLSecurity: Connection closed.");
        } catch (Exception ex) {
          /** Ignore any errors * */
        }
      }
    }
    return user;
  }
Beispiel #13
0
  @SuppressWarnings({"unchecked"})
  private void handleIssueRequest(
      PersistenceManager pm, HttpServletRequest req, HttpServletResponse resp, String uri)
      throws IOException {
    if (req.getParameter("embed") == null) {
      show404(resp);
      return;
    }
    Pattern p = Pattern.compile("/issues/([^/?]+)");
    Matcher m = p.matcher(uri);
    if (!m.matches()) {
      show404(resp);
      return;
    }
    String hash = m.group(1);
    Map<String, DbIssue> map = persistenceHelper.findIssues(pm, Lists.<String>newArrayList(hash));
    DbIssue issue = map.get(hash);
    if (issue == null) {
      printHtmlPreface(resp);
      resp.getWriter()
          .println("<p>This issue has not been submitted to the " + getCloudName() + "</p>");
      LOGGER.info("Not in cloud");
      return;
    }

    List<DbEvaluation> list = Lists.newArrayList(sortAndFilterEvaluations(issue.getEvaluations()));
    LOGGER.info("Issue " + issue.getPrimaryClass() + " - " + list.size() + " comments");
    if (list.isEmpty()) {
      printHtmlPreface(resp);
      resp.getWriter().println("<p>No comments have been submitted for this issue</p>");
      return;
    }
    Collections.reverse(list);

    PrintWriter out = resp.getWriter();
    printHtmlPreface(resp);
    out.println("<table border=0 class=popup-evals cellspacing=15>");
    for (DbEvaluation evaluation : list) {
      out.println("<tr>");
      out.println(
          "<td>"
              + StringEscapeUtils.escapeHtml(evaluation.getEmail())
              + "<br><span class=timestamp>"
              + TIMESTAMP_FORMAT().format(new Date(evaluation.getWhen()))
              + " </span></td>");

      out.println(
          "<td><strong>"
              + StringEscapeUtils.escapeHtml(evaluation.getDesignation())
              + "</strong>"
              + " &mdash; "
              + StringEscapeUtils.escapeHtml(evaluation.getComment())
              + "</td>");
      out.println("</tr>");
    }
    out.println("</table>");
  }
 /** Test whether GetFeature returns wfs:FeatureCollection. */
 public void testGetFeature() {
   Document doc = getAsDOM("wfs?request=GetFeature&typename=gsml:MappedFeature");
   LOGGER.info("WFS GetFeature&typename=gsml:MappedFeature response:\n" + prettyString(doc));
   assertEquals("wfs:FeatureCollection", doc.getDocumentElement().getNodeName());
   // non-feature type should return nothing/exception
   doc = getAsDOM("wfs?request=GetFeature&typename=gsml:CompositionPart");
   LOGGER.info(
       "WFS GetFeature&typename=gsml:CompositionPart response, exception expected:\n"
           + prettyString(doc));
   assertEquals("ows:ExceptionReport", doc.getDocumentElement().getNodeName());
 }
 @Override
 public void evaluate() throws Throwable {
   tcpServer.start();
   LOGGER.info("TCP server started");
   try {
     super.evaluate();
   } finally {
     LOGGER.info("TCP server stopped");
     tcpServer.stop();
   }
 }
  @Test
  public void encodeAndDecodeTest() throws BrutException, IOException {

    LOGGER.info("Building testapp.apk...");
    File testApk = new File(sTmpDir, "testapp.apk");
    new Androlib().build(sTestOrigDir, testApk, BuildAndDecodeTest.returnStock(), "");

    LOGGER.info("Decoding testapp.apk...");
    ApkDecoder apkDecoder = new ApkDecoder(testApk);
    apkDecoder.setOutDir(sTestNewDir);
    apkDecoder.decode();
  }
  @Override
  protected Element executeProcessor(Element response, Element request) {

    LOGGER.info(format(GENERIC_LOG_FORMAT, this.getClass(), METHOD_NAME, METHOD_ENTERED));

    if (doesElementExist(request, "social")) {

      System.out.println("process social elements");
    }

    LOGGER.info(format(GENERIC_LOG_FORMAT, this.getClass(), METHOD_NAME, METHOD_EXIT));

    return null;
  }
Beispiel #18
0
  /** TODO: revisit where/how to expose this. This is an experiment. */
  public void dynamicLoad(File arc)
      throws IOException, InterruptedException, RestartRequiredException {
    LOGGER.info("Attempting to dynamic load " + arc);
    final PluginWrapper p = strategy.createPluginWrapper(arc);
    String sn = p.getShortName();
    if (getPlugin(sn) != null)
      throw new RestartRequiredException(
          Messages._PluginManager_PluginIsAlreadyInstalled_RestartRequired(sn));

    if (p.supportsDynamicLoad() == YesNoMaybe.NO)
      throw new RestartRequiredException(
          Messages._PluginManager_PluginDoesntSupportDynamicLoad_RestartRequired(sn));

    // there's no need to do cyclic dependency check, because we are deploying one at a time,
    // so existing plugins can't be depending on this newly deployed one.

    plugins.add(p);
    activePlugins.add(p);

    try {
      p.resolvePluginDependencies();
      strategy.load(p);

      Jenkins.getInstance().refreshExtensions();

      p.getPlugin().postInitialize();
    } catch (Exception e) {
      failedPlugins.add(new FailedPlugin(sn, e));
      activePlugins.remove(p);
      plugins.remove(p);
      throw new IOException("Failed to install " + sn + " plugin", e);
    }

    // run initializers in the added plugin
    Reactor r = new Reactor(InitMilestone.ordering());
    r.addAll(
        new InitializerFinder(p.classLoader) {
          @Override
          protected boolean filter(Method e) {
            return e.getDeclaringClass().getClassLoader() != p.classLoader || super.filter(e);
          }
        }.discoverTasks(r));
    try {
      new InitReactorRunner().run(r);
    } catch (ReactorException e) {
      throw new IOException("Failed to initialize " + sn + " plugin", e);
    }
    LOGGER.info("Plugin " + sn + " dynamically installed");
  }
    @Override
    public void startNow() throws IOException{
        this.process = startProcess();
        Runtime.getRuntime().addShutdownHook(shutdownHook);

        logWatcher = new JenkinsLogWatcher(getLogId(),process,logFile);
        logWatcher.start();
        try {
            LOGGER.info("Waiting for Jenkins to become running in "+ this);
            this.logWatcher.waitTillReady();
            LOGGER.info("Jenkins is running in " + this);
        } catch (Exception e) {
            diagnoseFailedLoad(e);
        }
    }
  public boolean buildManifest(ExtFile appDir, Map<String, Object> usesFramework)
      throws BrutException {
    try {
      if (!new File(appDir, "AndroidManifest.xml").exists()) {
        return false;
      }
      if (!apkOptions.forceBuildAll) {
        LOGGER.info("Checking whether resources has changed...");
      }

      File apkDir = new File(appDir, APK_DIRNAME);

      if (apkOptions.debugMode) {
        mAndRes.remove_application_debug(new File(apkDir, "AndroidManifest.xml").getAbsolutePath());
      }

      if (apkOptions.forceBuildAll
          || isModified(
              newFiles(APK_MANIFEST_FILENAMES, appDir), newFiles(APK_MANIFEST_FILENAMES, apkDir))) {
        LOGGER.info("Building AndroidManifest.xml...");

        File apkFile = File.createTempFile("APKTOOL", null);
        apkFile.delete();

        File ninePatch = new File(appDir, "9patch");
        if (!ninePatch.exists()) {
          ninePatch = null;
        }

        mAndRes.aaptPackage(
            apkFile,
            new File(appDir, "AndroidManifest.xml"),
            null,
            ninePatch,
            null,
            parseUsesFramework(usesFramework));

        Directory tmpDir = new ExtFile(apkFile).getDirectory();
        tmpDir.copyToDir(apkDir, APK_MANIFEST_FILENAMES);
      }
      return true;
    } catch (IOException | DirectoryException ex) {
      throw new AndrolibException(ex);
    } catch (AndrolibException ex) {
      LOGGER.warning("Parse AndroidManifest.xml failed, treat it as raw file.");
      return buildManifestRaw(appDir);
    }
  }
Beispiel #21
0
 @Override
 public void configurationEvent(ConfigurationEvent event) {
   LOGGER.info("Configuration event received: {}", event);
   if (event.getPid().equals(pid) && ConfigurationEvent.CM_UPDATED == event.getType()) {
     updated = true;
   }
 }
    @Override
    public void run() {
      if (!backlogStore.exists()) {
        return;
      }

      try (BufferedReader fr = new BufferedReader(new FileReader(backlogStore))) {
        while (!Thread.interrupted()) {
          String line = fr.readLine();
          if (line == null) {
            break;
          }

          try {
            messageHandler.processBackloggedMessage(fromString(line));
          } catch (IllegalStateException e) {
            LOGGER.debug("Unable to reload message; {}", e.getMessage());
          }
        }

        backlogStore.delete();
      } catch (FileNotFoundException e) {
        LOGGER.error("Unable to reload checkpoint file: {}", e.getMessage());
      } catch (IOException e) {
        LOGGER.error("Unrecoverable error during reload checkpoint file: {}", e.getMessage());
      }

      LOGGER.info("Done reloading backlogged messages.");
    }
Beispiel #23
0
 /**
  * is invoked in an implementation-specific fashion to determine if an instance is still valid
  * to be returned by the pool. It will only be invoked on an "activated" instance.
  *
  * @param an instance of {@link Session} maintained by this pool.
  * @return <code>true</code> if the connection is still alive and operative (checked by asking
  *     its user name), <code>false</code> otherwise.
  */
 @Override
 public boolean validateObject(Object obj) {
   ISession session = (ISession) obj;
   boolean valid = !session.isClosed();
   // MAKE PROPER VALIDITY CHECK HERE as for GEOT-1273
   if (valid) {
     try {
       if (LOGGER.isLoggable(Level.FINEST)) {
         LOGGER.finest("    Validating SDE Connection " + session);
       }
       /*
        * Validate the connection's health with testServer instead of getUser. The
        * former is lighter weight, getUser() forced a server round trip and under
        * heavy concurrency ate about 30% the time
        */
       session.testServer();
     } catch (IOException e) {
       LOGGER.info(
           "Can't validate SeConnection, discarding it: "
               + session
               + ". Reason: "
               + e.getMessage());
       valid = false;
     }
   }
   return valid;
 }
  @Override
  protected void handleObjectPut(Object object) throws Exception {
    String workspace = getAttribute("workspace");
    String datastore = getAttribute("datastore");

    DataStoreInfo ds = (DataStoreInfo) object;
    DataStoreInfo original = catalog.getDataStoreByName(workspace, datastore);

    // ensure this is not a name or workspace change
    if (ds.getName() != null && !ds.getName().equals(original.getName())) {
      throw new RestletException("Can't change name of data store.", Status.CLIENT_ERROR_FORBIDDEN);
    }
    if (ds.getWorkspace() != null && !ds.getWorkspace().equals(original.getWorkspace())) {
      throw new RestletException(
          "Can't change workspace of data store.", Status.CLIENT_ERROR_FORBIDDEN);
    }

    new CatalogBuilder(catalog).updateDataStore(original, ds);

    catalog.validate(original, false).throwIfInvalid();
    catalog.save(original);

    clear(original);

    LOGGER.info("PUT data store " + workspace + "," + datastore);
  }
  public void decodeManifest(ResTable resTable, ExtFile apkFile, File outDir)
      throws AndrolibException {

    Duo<ResFileDecoder, AXmlResourceParser> duo = getManifestFileDecoder();
    ResFileDecoder fileDecoder = duo.m1;

    // Set ResAttrDecoder
    duo.m2.setAttrDecoder(new ResAttrDecoder());
    ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder();

    // Fake ResPackage
    attrDecoder.setCurrentPackage(new ResPackage(resTable, 0, null));

    Directory inApk, out;
    try {
      inApk = apkFile.getDirectory();
      out = new FileDirectory(outDir);

      LOGGER.info("Decoding AndroidManifest.xml with only framework resources...");
      fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml");

    } catch (DirectoryException ex) {
      throw new AndrolibException(ex);
    }
  }
 public void onTimeoutExpire(User user, Server server) {
   String serverId = server.getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   if (storage != null) {
     ServerTimeout timeout = storage.getTimeouts().remove(user.getId());
     if (timeout != null) {
       saveServerConfig(serverConfig);
       LOGGER.info(
           "Expiring timeout for {} ({}) in {} ({})",
           user.getUsername(),
           user.getId(),
           server.getName(),
           server.getId());
       if (apiClient.getUserById(user.getId(), server) != NO_USER) {
         apiClient.sendMessage(
             loc.localize("message.mod.timeout.expire", user.getId()), server.getId());
       }
       removeTimeoutRole(user, server, apiClient.getChannelById(server.getId()));
       return;
     }
   }
   LOGGER.warn(
       "Unable to expire: find server or timeout entry for {} ({}) in {} ({})",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
 }
 private void refreshTimeoutOnEvade(User user, Server server) {
   ServerTimeout timeout =
       SafeNav.of(serverStorage.get(server.getId()))
           .next(TempServerConfig::getServerTimeouts)
           .next(ServerTimeoutStorage::getTimeouts)
           .next(timeouts -> timeouts.get(user.getId()))
           .get();
   if (timeout == null) {
     LOGGER.warn(
         "Attempted to refresh a timeout on a user who was not timed out! {} ({})",
         user.getUsername(),
         user.getId());
     return;
   }
   LOGGER.info(
       "User {} ({}) attempted to evade a timeout on {} ({})!",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
   Channel channel = apiClient.getChannelById(server.getId(), server);
   apiClient.sendMessage(
       loc.localize(
           "listener.mod.timeout.on_evasion",
           user.getId(),
           formatDuration(Duration.between(Instant.now(), timeout.getEndTime())),
           formatInstant(timeout.getEndTime())),
       channel);
   applyTimeoutRole(user, server, channel);
 }
 private void stopTimeout(MessageContext context, String args) {
   if (args.isEmpty()) {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
     return;
   }
   String uid = args;
   if (uid.length() > 4) {
     if (uid.startsWith("<@")) {
       uid = uid.substring(2, uid.length() - 1);
     }
     Server server = context.getServer();
     User user = apiClient.getUserById(uid, server);
     if (user == NO_USER) {
       user = new User("UNKNOWN", uid, "", null);
     }
     LOGGER.info(
         "{} ({}) is attempting to cancel timeout for {} ({}) in {} ({})",
         context.getAuthor().getUsername(),
         context.getAuthor().getId(),
         user.getUsername(),
         user.getId(),
         server.getName(),
         server.getId());
     cancelTimeout(user, server, context.getChannel());
   } else {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
   }
 }
    @Override
    public void shutdownCompleted(ShutdownSignalException cause) {
      // Only hard error means loss of connection
      if (!cause.isHardError()) {
        return;
      }

      synchronized (operationOnConnectionMonitor) {
        // No action to be taken if factory is already closed
        // or already connecting
        if (state == State.CLOSED || state == State.CONNECTING) {
          return;
        }
        changeState(State.CONNECTING);
      }
      LOGGER.error("Connection to {}:{} lost", getHost(), getPort());
      while (state == State.CONNECTING) {
        try {
          establishConnection();
          return;
        } catch (IOException e) {
          LOGGER.info("Next reconnect attempt in {} ms", CONNECTION_ESTABLISH_INTERVAL_IN_MS);
          try {
            Thread.sleep(CONNECTION_ESTABLISH_INTERVAL_IN_MS);
          } catch (InterruptedException ie) {
            // that's fine, simply stop here
            return;
          }
        }
      }
    }
    @Override
    public void completed(Set<URI> uris) {
      try {
        descriptor.close();

        FileAttributes fileAttributesForNotification = getFileAttributesForNotification(uris);

        infoMsg.setStorageInfo(fileAttributesForNotification.getStorageInfo());

        PnfsId pnfsId = getFileAttributes().getPnfsId();
        notifyNamespace(pnfsId, fileAttributesForNotification);

        try {
          repository.setState(pnfsId, ReplicaState.CACHED);
        } catch (IllegalTransitionException ignored) {
          /* Apparently the file is no longer precious. Most
           * likely it got deleted, which is fine, since the
           * flush already succeeded.
           */
        }
        done(null);

        LOGGER.info("Flushed {} to nearline storage: {}", pnfsId, Joiner.on(' ').join(uris));
      } catch (Exception e) {
        done(e);
      }
    }