コード例 #1
1
ファイル: QueueLogAppender.java プロジェクト: LXGaming/Java
 @PluginFactory
 public static QueueLogAppender createAppender(
     @PluginAttribute("name") String name,
     @PluginElement("Filters") Filter filter,
     @PluginElement("Layout") Layout<? extends Serializable> layout,
     @PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
     @PluginAttribute("target") String target) {
   if (name == null) {
     LOGGER.error("No name provided for QueueLogAppender");
     return null;
   }
   if (target == null) {
     target = name;
   }
   queueLock.writeLock().lock();
   BlockingQueue<String> queue = (BlockingQueue<String>) queues.get(target);
   if (queue == null) {
     queue = new LinkedBlockingQueue<String>();
     queues.put(target, queue);
   }
   queueLock.writeLock().unlock();
   if (layout == null) {
     layout = PatternLayout.createLayout(null, null, null, null, null, false, false, null, null);
   }
   return new QueueLogAppender(name, filter, layout, ignoreExceptions, queue);
 }
コード例 #2
0
ファイル: ReportService.java プロジェクト: jcauthorn/pwm
 @Override
 public void run() {
   reportStatus.setCurrentProcess(ReportStatusInfo.ReportEngineProcess.DredgeTask);
   try {
     updateCacheFromLdap();
   } catch (Exception e) {
     if (e instanceof PwmException) {
       if (((PwmException) e).getErrorInformation().getError()
           == PwmError.ERROR_DIRECTORY_UNAVAILABLE) {
         if (executorService != null) {
           LOGGER.error(
               PwmConstants.REPORTING_SESSION_LABEL,
               "directory unavailable error during background DredgeTask, will retry; error: "
                   + e.getMessage());
           executorService.schedule(new DredgeTask(), 10, TimeUnit.MINUTES);
         }
       } else {
         LOGGER.error(
             PwmConstants.REPORTING_SESSION_LABEL,
             "error during background DredgeTask: " + e.getMessage());
       }
     }
   } finally {
     reportStatus.setCurrentProcess(ReportStatusInfo.ReportEngineProcess.None);
   }
 }
コード例 #3
0
 /* (non-Javadoc)
  * @see com.feinno.message.HttpConvertibleOutput#fromHttpResponse(com.ning.http.client.Response, java.lang.Throwable)
  */
 @Override
 public void fromHttpResponse(Response response, Throwable throwable) {
   if (throwable != null) {
     LOGGER.error(throwable.getMessage());
     return;
   }
   if (response.getStatusCode() == 200) {
     try {
       String content;
       if ((content = response.getResponseBody("UTF-8")) != null) {
         ObjectReader reader = mapper.readerForUpdating(this);
         reader.readValue(content);
       }
     } catch (Exception e) {
       LOGGER.error(e.getMessage());
       error_code = "0";
       setError_msg(e.getMessage());
       return;
     }
   } else {
     try {
       ObjectReader reader = mapper.readerForUpdating(this);
       reader.readValue(response.getResponseBody("UTF-8"));
       return;
     } catch (Exception e) {
       LOGGER.error(response.getStatusCode() + "\n" + e.getMessage());
       error_code = "0";
       return;
     }
   }
 }
コード例 #4
0
  @Override
  public void start() {
    final Map<String, Appender> map = config.getAppenders();
    final List<AppenderControl> appenders = new ArrayList<>();
    for (final AppenderRef appenderRef : appenderRefs) {
      if (map.containsKey(appenderRef.getRef())) {
        appenders.add(
            new AppenderControl(
                map.get(appenderRef.getRef()), appenderRef.getLevel(), appenderRef.getFilter()));
      } else {
        LOGGER.error("No appender named {} was configured", appenderRef);
      }
    }
    if (errorRef != null) {
      if (map.containsKey(errorRef)) {
        errorAppender = new AppenderControl(map.get(errorRef), null, null);
      } else {
        LOGGER.error(
            "Unable to set up error Appender. No appender named {} was configured", errorRef);
      }
    }
    if (appenders.size() > 0) {
      thread = new AsyncThread(appenders, queue);
      thread.setName("AsyncAppender-" + getName());
    } else if (errorRef == null) {
      throw new ConfigurationException("No appenders are available for AsyncAppender " + getName());
    }

    thread.start();
    super.start();
  }
コード例 #5
0
  /**
   * Create an AsyncAppender.
   *
   * @param appenderRefs The Appenders to reference.
   * @param errorRef An optional Appender to write to if the queue is full or other errors occur.
   * @param blocking True if the Appender should wait when the queue is full. The default is true.
   * @param size The size of the event queue. The default is 128.
   * @param name The name of the Appender.
   * @param includeLocation whether to include location information. The default is false.
   * @param filter The Filter or null.
   * @param config The Configuration.
   * @param ignoreExceptions If {@code "true"} (default) exceptions encountered when appending
   *     events are logged; otherwise they are propagated to the caller.
   * @return The AsyncAppender.
   */
  @PluginFactory
  public static AsyncAppender createAppender(
      @PluginElement("AppenderRef") final AppenderRef[] appenderRefs,
      @PluginAttribute("errorRef") @PluginAliases("error-ref") final String errorRef,
      @PluginAttribute(value = "blocking", defaultBoolean = true) final boolean blocking,
      @PluginAttribute(value = "bufferSize", defaultInt = DEFAULT_QUEUE_SIZE) final int size,
      @PluginAttribute("name") final String name,
      @PluginAttribute(value = "includeLocation", defaultBoolean = false)
          final boolean includeLocation,
      @PluginElement("Filter") final Filter filter,
      @PluginConfiguration final Configuration config,
      @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true)
          final boolean ignoreExceptions) {
    if (name == null) {
      LOGGER.error("No name provided for AsyncAppender");
      return null;
    }
    if (appenderRefs == null) {
      LOGGER.error("No appender references provided to AsyncAppender {}", name);
    }

    return new AsyncAppender(
        name,
        filter,
        appenderRefs,
        errorRef,
        size,
        blocking,
        ignoreExceptions,
        config,
        includeLocation);
  }
コード例 #6
0
    /** Loops on processing a client forever */
    public void run() {
      TProcessor processor = null;
      TTransport inputTransport = null;
      TTransport outputTransport = null;
      TProtocol inputProtocol = null;
      TProtocol outputProtocol = null;
      try {
        processor = processorFactory_.getProcessor(client_);
        inputTransport = inputTransportFactory_.getTransport(client_);
        outputTransport = outputTransportFactory_.getTransport(client_);
        inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
        outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
        // we check stopped_ first to make sure we're not supposed to be shutting
        // down. this is necessary for graceful shutdown.
        while (!stopped_ && processor.process(inputProtocol, outputProtocol)) {}
      } catch (TTransportException ttx) {
        // Assume the client died and continue silently
      } catch (TException tx) {
        LOGGER.error("Thrift error occurred during processing of message.", tx);
      } catch (Exception x) {
        LOGGER.error("Error occurred during processing of message.", x);
      }

      if (inputTransport != null) {
        inputTransport.close();
      }

      if (outputTransport != null) {
        outputTransport.close();
      }
    }
コード例 #7
0
    @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.");
    }
コード例 #8
0
 @Override
 public String get(Class<?> clazz) {
   URL url = clazz.getResource(clazz.getSimpleName() + ".java");
   if (url == null) {
     try {
       url =
           new File("../Shared/src/" + clazz.getName().replace(".", "/") + ".java")
               .toURI()
               .toURL();
     } catch (MalformedURLException e) {
       LOGGER.error("", e);
     }
   }
   if (url != null) {
     try {
       InputStream inputStream = url.openStream();
       if (inputStream == null) {
         return null;
       }
       StringWriter out = new StringWriter();
       IOUtils.copy(inputStream, out);
       return out.toString();
     } catch (IOException e) {
       LOGGER.error("", e);
     }
   }
   return null;
 }
コード例 #9
0
  /**
   * Create an AsyncAppender. This method is retained for backwards compatibility. New code should
   * use the {@link Builder} instead. This factory will use {@link ArrayBlockingQueueFactory} by
   * default as was the behavior pre-2.7.
   *
   * @param appenderRefs The Appenders to reference.
   * @param errorRef An optional Appender to write to if the queue is full or other errors occur.
   * @param blocking True if the Appender should wait when the queue is full. The default is true.
   * @param shutdownTimeout How many milliseconds the Appender should wait to flush outstanding log
   *     events in the queue on shutdown. The default is zero which means to wait forever.
   * @param size The size of the event queue. The default is 128.
   * @param name The name of the Appender.
   * @param includeLocation whether to include location information. The default is false.
   * @param filter The Filter or null.
   * @param config The Configuration.
   * @param ignoreExceptions If {@code "true"} (default) exceptions encountered when appending
   *     events are logged; otherwise they are propagated to the caller.
   * @return The AsyncAppender.
   * @deprecated use {@link Builder} instead
   */
  @Deprecated
  public static AsyncAppender createAppender(
      final AppenderRef[] appenderRefs,
      final String errorRef,
      final boolean blocking,
      final long shutdownTimeout,
      final int size,
      final String name,
      final boolean includeLocation,
      final Filter filter,
      final Configuration config,
      final boolean ignoreExceptions) {
    if (name == null) {
      LOGGER.error("No name provided for AsyncAppender");
      return null;
    }
    if (appenderRefs == null) {
      LOGGER.error("No appender references provided to AsyncAppender {}", name);
    }

    return new AsyncAppender(
        name,
        filter,
        appenderRefs,
        errorRef,
        size,
        blocking,
        ignoreExceptions,
        shutdownTimeout,
        config,
        includeLocation,
        new ArrayBlockingQueueFactory<LogEvent>());
  }
コード例 #10
0
  /**
   * Determine the right DockerClientConfig to use for building clients by trial-and-error.
   *
   * @return a working DockerClientConfig, as determined by successful execution of a ping command
   */
  static DockerClientConfig getFirstValidConfig(List<DockerConfigurationStrategy> strategies) {
    Map<DockerConfigurationStrategy, Exception> configurationFailures = new LinkedHashMap<>();

    for (DockerConfigurationStrategy strategy : strategies) {
      try {
        LOGGER.info("Looking for Docker environment. Trying {}", strategy.getDescription());
        return strategy.provideConfiguration();
      } catch (Exception e) {
        configurationFailures.put(strategy, e);
      }
    }

    LOGGER.error(
        "Could not find a valid Docker environment. Please check configuration. Attempted configurations were:");
    for (Map.Entry<DockerConfigurationStrategy, Exception> entry :
        configurationFailures.entrySet()) {
      LOGGER.error(
          "    {}: failed with exception message: {}",
          entry.getKey().getDescription(),
          entry.getValue().getMessage());
    }
    LOGGER.error("As no valid configuration was found, execution cannot continue");

    throw new IllegalStateException(
        "Could not find a valid Docker environment. Please see logs and check configuration");
  }
コード例 #11
0
    @Override
    public void run() {

      BufferedReader in = null;
      PrintWriter out = null;

      try {
        in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
        OutputStream outputStream = socket.getOutputStream();
        out = new PrintWriter(outputStream);

        String line = in.readLine();
        CommandRequest request = CommandRequest.parse(line);

        out.print("HTTP/1.1 200 OK\r\n\r\n");
        out.flush();
        if (StringUtils.isEmpty(request.getCommand())) {
          out.println("Command is blank");
          out.flush();
          return;
        }

        CommandProcessor commandProcessor = getCommandProcessor(request.getCommand());
        if (commandProcessor != null) {
          commandProcessor.execute(outputStream, request);
        } else {
          out.println("Can not find the command:[" + request.getCommand() + "]");
        }
        out.flush();

      } catch (Throwable t) {
        LOGGER.error("EventRunnable error", t);

        try {
          if (out != null) {
            out.println("CommandCenter error, message is " + t.getMessage());
            out.flush();
          }
        } catch (Exception e) {
          LOGGER.error("EventRunnable error", t);
        }

      } finally {
        try {
          if (out != null) {
            out.close();
          }
          if (in != null) {
            in.close();
          }
          socket.close();
        } catch (Exception e) {
          LOGGER.error("EventRunnable close resource error", e);
        }
      }
    }
コード例 #12
0
ファイル: GroupController.java プロジェクト: xabe/Spring
 public String downloadImportLog() {
   try {
     importer.downloadImporterLog();
   } catch (IOException e) {
     LOGGER.error("Error al importar log de subida de fichero de rest " + e.getMessage());
   } catch (IllegalAccessException e) {
     LOGGER.error("Error al importar log de subida de fichero de rest " + e.getMessage());
   }
   return null;
 }
コード例 #13
0
    /**
     * Create the RollingRandomAccessFileManager.
     *
     * @param name The name of the entity to manage.
     * @param data The data required to create the entity.
     * @return a RollingFileManager.
     */
    @Override
    public RollingRandomAccessFileManager createManager(final String name, final FactoryData data) {
      final File file = new File(name);
      final File parent = file.getParentFile();
      if (null != parent && !parent.exists()) {
        parent.mkdirs();
      }

      if (!data.append) {
        file.delete();
      }
      final long size = data.append ? file.length() : 0;
      final long time = file.exists() ? file.lastModified() : System.currentTimeMillis();

      final boolean writeHeader = !data.append || !file.exists();
      RandomAccessFile raf = null;
      try {
        raf = new RandomAccessFile(name, "rw");
        if (data.append) {
          final long length = raf.length();
          LOGGER.trace("RandomAccessFile {} seek to {}", name, length);
          raf.seek(length);
        } else {
          LOGGER.trace("RandomAccessFile {} set length to 0", name);
          raf.setLength(0);
        }
        return new RollingRandomAccessFileManager(
            data.getLoggerContext(),
            raf,
            name,
            data.pattern,
            NullOutputStream.getInstance(),
            data.append,
            data.immediateFlush,
            data.bufferSize,
            size,
            time,
            data.policy,
            data.strategy,
            data.advertiseURI,
            data.layout,
            writeHeader);
      } catch (final IOException ex) {
        LOGGER.error("Cannot access RandomAccessFile " + ex, ex);
        if (raf != null) {
          try {
            raf.close();
          } catch (final IOException e) {
            LOGGER.error("Cannot close RandomAccessFile {}", name, e);
          }
        }
      }
      return null;
    }
    public void run() {
      HTTPXMessageRefactorer refactorer = new HTTPXMessageRefactorer();
      HTTPXActionMessage request = null;
      try {
        request =
            refactorer.createActionMessageFromStream(
                this.toStream(packet.getData(), packet.getLength()));
      } catch (HTTPXProtocolViolationException e) {
        LOGGER.error(e);
        e.printStackTrace();
      } catch (IOException e) {
        LOGGER.error(e);
        e.printStackTrace();
      }
      request.setPort(packet.getPort());
      request.setHost(packet.getAddress().getHostName());

      LOGGER.debug(HTTPXConstants.HTTPU + " Request:\r\n" + request.toString());

      boolean bFound = false;
      Path tmpPath = new Path(request.getPath().getString());
      try {
        do {
          for (Tuple element : registration) {
            if ((element.handler instanceof HTTPXPlainActionMessageHandler)
                && element.filter.doesPass(
                    request.getProtocol(),
                    request.getHost(),
                    request.getPort(),
                    tmpPath,
                    request.getQueryAsString())) {
              LOGGER.debug("void Handler was found : " + element.handler);
              ((HTTPXPlainActionMessageHandler) element.handler).handlePlain(request);
              bFound = true;
              break;
            }
          } // for
          if (!bFound) {
            String strTmp = tmpPath.getString();
            tmpPath.removeLastToken();
            // check wheter path is root
            if (strTmp.equalsIgnoreCase(tmpPath.getString())) {
              break;
            }
          }
        } while (!bFound);
      } catch (IOException e) {
        LOGGER.error(e);
        e.printStackTrace();
      }
    }
コード例 #15
0
ファイル: CellNucleus.java プロジェクト: sureddy/dcache
    @Override
    public void innerRun() {
      EventLogger.queueEnd(_event);

      if (_event instanceof LastMessageEvent) {
        LOGGER.trace("messageThread : LastMessageEvent arrived");
        _cell.messageArrived((MessageEvent) _event);
      } else if (_event instanceof RoutedMessageEvent) {
        LOGGER.trace("messageThread : RoutedMessageEvent arrived");
        _cell.messageArrived((RoutedMessageEvent) _event);
      } else if (_event instanceof MessageEvent) {
        MessageEvent msgEvent = (MessageEvent) _event;
        LOGGER.trace("messageThread : MessageEvent arrived");
        CellMessage msg;
        try {
          msg = msgEvent.getMessage().decode();
        } catch (SerializationException e) {
          CellMessage envelope = msgEvent.getMessage();
          LOGGER.error(
              String.format(
                  "Discarding a malformed message from %s with UOID %s and session [%s]: %s",
                  envelope.getSourcePath(),
                  envelope.getUOID(),
                  envelope.getSession(),
                  e.getMessage()),
              e);
          return;
        }

        CDC.setMessageContext(msg);
        try {
          LOGGER.trace("messageThread : delivering message: {}", msg);
          _cell.messageArrived(new MessageEvent(msg));
          LOGGER.trace("messageThread : delivering message done: {}", msg);
        } catch (RuntimeException e) {
          if (!msg.isReply()) {
            try {
              msg.revertDirection();
              msg.setMessageObject(e);
              sendMessage(msg);
            } catch (NoRouteToCellException f) {
              LOGGER.error("PANIC : Problem returning answer: {}", f);
            }
          }
          throw e;
        } finally {
          CDC.clearMessageContext();
        }
      }
    }
コード例 #16
0
  /**
   * Rename file.
   *
   * @param source current file name.
   * @param destination new file name.
   * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files.
   * @return true if successfully renamed.
   */
  public static boolean execute(
      final File source, final File destination, final boolean renameEmptyFiles) {
    if (renameEmptyFiles || source.length() > 0) {
      final File parent = destination.getParentFile();
      if (parent != null && !parent.exists()) {
        // LOG4J2-679: ignore mkdirs() result: in multithreaded scenarios,
        // if one thread succeeds the other thread returns false
        // even though directories have been created. Check if dir exists instead.
        parent.mkdirs();
        if (!parent.exists()) {
          LOGGER.error("Unable to create directory {}", parent.getAbsolutePath());
          return false;
        }
      }
      try {
        if (!source.renameTo(destination)) {
          try {
            copyFile(source, destination);
            return source.delete();
          } catch (final IOException iex) {
            LOGGER.error(
                "Unable to rename file {} to {} - {}",
                source.getAbsolutePath(),
                destination.getAbsolutePath(),
                iex.getMessage());
          }
        }
        return true;
      } catch (final Exception ex) {
        try {
          copyFile(source, destination);
          return source.delete();
        } catch (final IOException iex) {
          LOGGER.error(
              "Unable to rename file {} to {} - {}",
              source.getAbsolutePath(),
              destination.getAbsolutePath(),
              iex.getMessage());
        }
      }
    } else {
      try {
        source.delete();
      } catch (final Exception ex) {
        LOGGER.error("Unable to delete empty file " + source.getAbsolutePath());
      }
    }

    return false;
  }
コード例 #17
0
    @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;
          }
        }
      }
    }
コード例 #18
0
  /**
   * Constructor that accepts a list of <MultiplexerArgs> to register provided services(processors)
   * with lookup registry and multiplexer
   *
   * @param list
   */
  public TLookupMultiplexer(List<MultiplexerArgs> list) {

    // creating multiplexer using arguments
    super(list);

    // creating factory
    factory = TRegistryFactory.createFactory();

    // creating list of URIContext from argumentList
    List<URIContext> urilist = new ArrayList<URIContext>();
    for (MultiplexerArgs arg : list) {
      urilist.add(arg.getUricontext());
    }

    // configuring lookup service
    MultiplexerArgs arg =
        new MultiplexerArgs(
            factory.getService(urilist),
            new URIContext(TConstants.LOOKUP_CONTEXT, "Lookup Service"));

    try {

      // registering lookup service with multiplexer
      super.registerProcessor(arg);

    } catch (InvalidInputException e) {
      LOGGER.error("LOOKUP SERVICE REGISTRATION FAILED. DETAILS : " + e.what + "||" + e.why);
    }
  }
コード例 #19
0
    /** Only pnfs-based messages are stored. */
    private void saveToBacklog(Serializable message) {
      String pnfsid;
      String pool;
      String type;

      if (message instanceof CorruptFileMessage) {
        CorruptFileMessage specific = (CorruptFileMessage) message;
        pnfsid = specific.getPnfsId().toString();
        pool = specific.getPool();
        type = CorruptFileMessage.class.getSimpleName();
      } else if (message instanceof PnfsClearCacheLocationMessage) {
        PnfsClearCacheLocationMessage specific = (PnfsClearCacheLocationMessage) message;
        pnfsid = specific.getPnfsId().toString();
        pool = specific.getPoolName();
        type = PnfsClearCacheLocationMessage.class.getSimpleName();
      } else if (message instanceof PnfsAddCacheLocationMessage) {
        PnfsAddCacheLocationMessage specific = (PnfsAddCacheLocationMessage) message;
        pnfsid = specific.getPnfsId().toString();
        pool = specific.getPoolName();
        type = PnfsAddCacheLocationMessage.class.getSimpleName();
      } else {
        return;
      }

      pw.println(type + "," + pnfsid + "," + pool);

      if (pw.checkError()) {
        LOGGER.error("Problem saving ({} {} {}) to file; skipped.", type, pnfsid, pool);
      }
    }
コード例 #20
0
 @Override
 public void mouseClicked(MouseEvent arg0) {
   int col = tableFiles.columnAtPoint(arg0.getPoint());
   if (col == 0) {
     int row = tableFiles.rowAtPoint(arg0.getPoint());
     row = tableFiles.convertRowIndexToModel(row);
     MediaFile mf = mediaFileEventList.get(row);
     // open the video file in the desired player
     if (mf.isVideo()) {
       try {
         TmmUIHelper.openFile(mf.getFile());
       } catch (Exception e) {
         LOGGER.error("open file", e);
         MessageManager.instance.pushMessage(
             new Message(
                 MessageLevel.ERROR,
                 mf,
                 "message.erroropenfile",
                 new String[] {":", e.getLocalizedMessage()}));
       }
     }
     // open the graphic in the lightbox
     if (mf.isGraphic()) {
       MainWindow.getActiveInstance()
           .createLightbox(mf.getPath() + File.separator + mf.getFilename(), "");
     }
   }
 }
コード例 #21
0
 private void whenRemoveTargetIsSelected() {
   try {
     selected = locationSelector.selectRemoveTarget(collection, null);
   } catch (Exception e) {
     LOGGER.error("{}", new ExceptionMessage(e));
   }
 }
コード例 #22
0
 public void run() {
   try {
     publishStatisticsToCloud();
   } catch (Exception e) {
     LOGGER.error("error publishing statistics to cloud: " + e.getMessage());
   }
 }
コード例 #23
0
 protected void issueCommand(String command, String content) {
   T response = null;
   String body = issueHttpRequest(command, content);
   try {
     response = context.getMapper().readValue(body, clazz);
   } catch (Exception e) {
     LOGGER.error("cannot parse response body", e);
     throw new TaskletException(); // mark termination
   }
   if (!response.isSucc()) {
     String msg = "driver report error: HTTP {} - {}";
     LOGGER.error(msg, response.getCode(), response.getError());
     throw new TaskletException(); // mark termination
   }
   handleResponse(response); // specific response handling
 }
コード例 #24
0
ファイル: TCP.java プロジェクト: gitvod/traffic_control
    @Override
    public void run() {
      try {
        final InetAddress client = socket.getInetAddress();

        final DataInputStream is = new DataInputStream(socket.getInputStream());
        final DataOutputStream os = new DataOutputStream(socket.getOutputStream());

        final int length = is.readUnsignedShort();
        final byte[] request = new byte[length];
        is.readFully(request);

        final byte[] response = query(client, request);
        os.writeShort(response.length);
        os.write(response);
      } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
      } finally {
        try {
          socket.close();
        } catch (final IOException e) {
          LOGGER.debug(e.getMessage(), e);
        }
      }
    }
コード例 #25
0
 protected Audit waitForAuditToComplete(Audit audit) {
   LOGGER.debug(
       "WAIT FOR AUDIT TO COMPLETE:"
           + audit
           + ","
           + (long) (audit.getDateOfCreation().getTime() / 1000));
   Long token = new Date().getTime();
   this.getAuditExecutionList().put(audit, token);
   // while the audit is not seen as completed or crashed
   while (!this.getAuditCompletedList().containsKey(token)
       && !this.getAuditCrashedList().containsKey(token)) {
     try {
       Thread.sleep(500);
     } catch (InterruptedException ex) {
       LOGGER.error("", ex);
     }
   }
   if ((audit = this.getAuditCompletedList().get(token)) != null) {
     this.getAuditCompletedList().remove(token);
     return audit;
   }
   if ((audit = this.getAuditCrashedList().get(token).getKey()) != null) {
     this.getAuditCrashedList().remove(token);
     return audit;
   }
   return null;
 }
コード例 #26
0
 @Override
 public void auditCrashed(Audit audit, Exception exception) {
   String url = "";
   if (audit.getSubject() != null) {
     url = audit.getSubject().getURL();
   }
   LOGGER.error(
       "AUDIT CRASHED:"
           + audit
           + ","
           + url
           + ","
           + (long) (audit.getDateOfCreation().getTime() / 1000),
       exception);
   Audit auditCrashed = null;
   for (Audit auditRunning : this.auditExecutionList.keySet()) {
     if (auditRunning.getId().equals(audit.getId())
         && (long) (auditRunning.getDateOfCreation().getTime() / 1000)
             == (long) (audit.getDateOfCreation().getTime() / 1000)) {
       auditCrashed = auditRunning;
       break;
     }
   }
   if (auditCrashed != null) {
     Long token = this.auditExecutionList.get(auditCrashed);
     this.auditExecutionList.remove(auditCrashed);
     this.auditCrashedList.put(token, new AbstractMap.SimpleImmutableEntry<>(audit, exception));
     this.exception = exception;
   }
 }
コード例 #27
0
  @Override
  public void stop() {
    LOGGER.debug("Stopping LoggerContext[name={}, {}]...", getName(), this);
    configLock.lock();
    try {
      if (this.isStopped()) {
        return;
      }

      this.setStopping();
      try {
        Server.unregisterLoggerContext(getName()); // LOG4J2-406, LOG4J2-500
      } catch (final Exception ex) {
        LOGGER.error("Unable to unregister MBeans", ex);
      }
      if (shutdownCallback != null) {
        shutdownCallback.cancel();
        shutdownCallback = null;
      }
      final Configuration prev = configuration;
      configuration = NULL_CONFIGURATION;
      updateLoggers();
      prev.stop();
      externalContext = null;
      LogManager.getFactory().removeContext(this);
      this.setStopped();
    } finally {
      configLock.unlock();
    }
    LOGGER.debug("Stopped LoggerContext[name={}, {}]...", getName(), this);
  }
コード例 #28
0
ファイル: Role_model.java プロジェクト: amirbawab/PMExpert
  public boolean deleteRoleById(int roleId) {
    // Open
    this.open();

    // Query
    sql = "DELETE FROM role WHERE role_id = ?";

    try {

      // Prepare
      this.prepareStatement();

      // Data
      ps.setInt(1, roleId);

      // Run
      affectedRows = ps.executeUpdate();

      // Check if deleted
      return (affectedRows == 1);

      // Error
    } catch (SQLException e) {
      LOGGER.error("Could not delete role --- detailed info: " + e.getMessage());

      // Close
    } finally {
      this.close();
    }

    return false;
  }
コード例 #29
0
ファイル: ReportService.java プロジェクト: jcauthorn/pwm
 @Override
 public void run() {
   try {
     initTempData();
   } catch (LocalDBException | PwmUnrecoverableException e) {
     LOGGER.error(
         PwmConstants.REPORTING_SESSION_LABEL, "error during initialization: " + e.getMessage());
     status = STATUS.CLOSED;
     return;
   }
   final long secondsUntilNextDredge =
       settings.getJobOffsetSeconds()
           + TimeDuration.fromCurrent(Helper.nextZuluZeroTime()).getTotalSeconds();
   executorService.scheduleAtFixedRate(
       new DredgeTask(),
       secondsUntilNextDredge,
       TimeDuration.DAY.getTotalSeconds(),
       TimeUnit.SECONDS);
   executorService.scheduleAtFixedRate(
       new RolloverTask(),
       secondsUntilNextDredge + 1,
       TimeDuration.DAY.getTotalSeconds(),
       TimeUnit.SECONDS);
   executorService.submit(new RolloverTask());
 }
 public void run() {
   while (running) {
     try {
       // create a buffer for the datagram packet
       byte[] buf = new byte[XMOSLedTilePacketPayload.MAX_PAYLOAD_SIZE];
       // receive a packet
       DatagramPacket packet = new DatagramPacket(buf, buf.length);
       socket.receive(packet);
       LOGGER.debug("Packet received {}", packet);
       // analyze the data if it is a XMOS packet
       byte[] data = packet.getData();
       // we must have at least XMOS + package ID
       if (data.length > 5) {
         byte[] magicString = new byte[MAGIC_STRING.length()];
         System.arraycopy(data, 0, magicString, 0, MAGIC_STRING.length());
         String packageMagicString = new String(magicString);
         if (MAGIC_STRING.equals(packageMagicString)) {
           LOGGER.info(
               "Retrieved a XMOS package from {}:{}",
               packet.getAddress(),
               packet.getSocketAddress());
           addPacket(packet);
         }
       }
     } catch (IOException e) {
       LOGGER.error("Unable to retrieve packet, ignoring it.", e);
     }
   }
 }