/**
   * Checks if our WPS can really handle this process inputs and outputs
   *
   * @param pf
   * @param name
   * @return
   */
  Set<Name> getProcessBlacklist() {
    synchronized (PROCESS_BLACKLIST) {
      if (PROCESS_BLACKLIST == Collections.EMPTY_SET) {

        Set<Name> blacklist = new HashSet<Name>();

        for (ProcessFactory pf : Processors.getProcessFactories()) {
          int count = 0;
          for (Name name : pf.getNames()) {
            try {
              // check inputs
              for (Parameter<?> p : pf.getParameterInfo(name).values()) {
                List<ProcessParameterIO> ppios = ProcessParameterIO.findAll(p, context);
                if (ppios.isEmpty()) {
                  LOGGER.log(
                      Level.INFO,
                      "Blacklisting process "
                          + name.getURI()
                          + " as the input "
                          + p.key
                          + " of type "
                          + p.type
                          + " cannot be handled");
                  blacklist.add(name);
                }
              }

              // check outputs
              for (Parameter<?> p : pf.getResultInfo(name, null).values()) {
                List<ProcessParameterIO> ppios = ProcessParameterIO.findAll(p, context);
                if (ppios.isEmpty()) {
                  LOGGER.log(
                      Level.INFO,
                      "Blacklisting process "
                          + name.getURI()
                          + " as the output "
                          + p.key
                          + " of type "
                          + p.type
                          + " cannot be handled");
                  blacklist.add(name);
                }
              }
            } catch (Throwable t) {
              blacklist.add(name);
            }

            if (!blacklist.contains(name)) {
              count++;
            }
          }
          LOGGER.info("Found " + count + " bindable processes in " + pf.getTitle());
        }

        PROCESS_BLACKLIST = blacklist;
      }
    }

    return PROCESS_BLACKLIST;
  }
Esempio n. 2
0
  @Override
  public void onWebSocketClose(final int closeCode, final String message) {

    logger.log(
        Level.INFO,
        "Connection closed with closeCode {0} and message {1}",
        new Object[] {closeCode, message});

    final App app = StructrApp.getInstance(securityContext);

    try (final Tx tx = app.tx()) {

      this.session = null;

      syncController.unregisterClient(this);

      // flush and close open uploads
      for (FileUploadHandler upload : uploads.values()) {

        upload.finish();
      }

      tx.success();
      uploads.clear();

    } catch (FrameworkException fex) {

      logger.log(Level.SEVERE, "Error while closing connection", fex);
    }
  }
Esempio n. 3
0
  /**
   * Method description
   *
   * @param app
   * @param net
   * @throws SSLException
   */
  public void wrap(ByteBuffer app, ByteBuffer net) throws SSLException {
    tlsEngineResult = tlsEngine.wrap(app, net);

    if (log.isLoggable(Level.FINEST)) {
      log.log(
          Level.FINEST,
          "{0}, tlsEngineRsult.getStatus() = {1}, tlsEngineRsult.getHandshakeStatus() = {2}",
          new Object[] {
            debugId, tlsEngineResult.getStatus(), tlsEngineResult.getHandshakeStatus()
          });
    }

    if (tlsEngineResult.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.FINISHED) {
      if (eventHandler != null) {
        eventHandler.handshakeCompleted(this);
      }
    }

    if (tlsEngineResult.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
      doTasks();

      if (log.isLoggable(Level.FINEST)) {
        log.log(
            Level.FINEST,
            "doTasks(): {0}, {1}",
            new Object[] {tlsEngine.getHandshakeStatus(), debugId});
      }
    }
  }
  @Override
  public <T> T execute(Task<T> task) throws Exception {
    long startTime = System.currentTimeMillis();

    logger.log(logLevel, "start executing task " + task);
    try {
      return super.execute(task);
    } catch (Exception e) {
      logger.log(
          logLevel,
          "executing task "
              + task
              + " failed after "
              + (System.currentTimeMillis() - startTime)
              + " ms");
      throw e;
    } finally {
      logger.log(
          logLevel,
          "finished executing task "
              + task
              + " in "
              + (System.currentTimeMillis() - startTime)
              + " ms");
    }
  }
Esempio n. 5
0
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Cookie[] cookies = request.getCookies();

    int userID = -1;
    boolean newUser = false;

    // determine whether we've seen this user before
    if (cookies != null) {
      for (Cookie c : cookies) {
        if (c.getName().equals("userID")) {
          userID = Integer.parseInt(c.getValue());
          logger.log(Level.INFO, "Existing user: "******"userID", String.valueOf(userID));
      response.addCookie(c);
      logger.log(Level.INFO, "New user: "******"text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    PrintWriter out = response.getWriter();

    String title = "Cookie Servlet";
    String bootstrapHeader =
        "<!DOCTYPE html>"
            + "<html lang=\"en\">\n"
            + "	<head>\n"
            + "		<title>"
            + title
            + "</title>\n"
            + "		<meta charset=\"utf-8\">\n"
            + "		<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
            + "		<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n"
            + "		<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n"
            + "		<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n"
            + "	</head>\n";

    String body =
        "	<body>\n"
            + "		<div class=\"container\">\n"
            + "			<p>Hello, "
            + (newUser ? "new" : "existing")
            + " user!</p>\n"
            + "		</div>\n"
            + "	</body>\n";

    String footer = "</html>";

    String page = bootstrapHeader + body + footer;
    out.println(page);
  }
Esempio n. 6
0
  @GET
  public Response authorize(@Context HttpServletRequest request) {
    if (context == null) {
      throw new RuntimeException("Servlet Context has not been injected");
    }
    if (identityManager == null) {
      try {
        identityManager = OAuthServerUtil.handleIdentityManager(context);
      } catch (IOException e) {
        log.log(Level.SEVERE, "Identity Manager setup:", e);
        throw new RuntimeException(e);
      }
      if (identityManager == null) {
        throw new RuntimeException("Identity Manager has not been created");
      }
    }

    OAuthResponse response = null;
    try {
      response = OAuthServerUtil.authorizationCodeRequest(request, identityManager);
    } catch (OAuthSystemException e) {
      log.log(Level.SEVERE, "OAuth Server Authorization Processing:", e);
      return Response.serverError().build();
    }
    // Check for successful processing
    String location = response.getLocationUri();
    if (location != null && location.isEmpty() == false) {
      return Response.status(response.getResponseStatus()).location(URI.create(location)).build();
    } else { // We have error
      return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
    }
  }
  @Override
  public Talk convertLineToTalk(String line) {

    if (line == null || line.isEmpty()) {
      throw new IllegalArgumentException("line must not be null or empty");
    }

    line = line.replaceAll("\\s+", " ").trim();
    Pattern pattern = Pattern.compile("(.*)(\\s){1}([0-2]?[0-9]?[0-9]{1}min|lightning)\\b");
    Matcher matcher = pattern.matcher(line);
    if (!matcher.matches()) {
      LOG.log(Level.SEVERE, "Line [{0}] is not recognised by the converter", line);
      throw new ProposalConverterException();
    }

    final String title = matcher.group(1);
    final String duration = matcher.group(3);
    int durationMinutes = 0;

    if (duration.equals(IProposalLineConverter.LIGHTNING_TEXT)) {
      durationMinutes = IProposalLineConverter.LIGHTNING_DURATION;
    } else {
      try {
        durationMinutes = Integer.parseInt(duration.substring(0, duration.indexOf(MINUTE_SUFFIX)));
      } catch (NumberFormatException e) {
        LOG.log(Level.SEVERE, "NumberFormatException while parsing minutes into Integer", e);
        throw new ProposalConverterException();
      }
    }

    return new Talk(title, durationMinutes);
  }
  protected URL lookupBpmPlatformXmlLocationFromJndi() {
    String jndi = "java:comp/env/" + BPM_PLATFORM_XML_LOCATION;

    try {
      String bpmPlatformXmlLocation = InitialContext.doLookup(jndi);

      URL fileLocation = checkValidBpmPlatformXmlResourceLocation(bpmPlatformXmlLocation);

      if (fileLocation != null) {
        LOGGER.log(
            Level.INFO,
            "Found camunda bpm platform configuration in JNDI ["
                + jndi
                + "] at "
                + fileLocation.toString());
      }

      return fileLocation;
    } catch (NamingException e) {
      LOGGER.log(
          Level.FINE,
          "Failed to look up camunda bpm platform configuration in JNDI [" + jndi + "].",
          e);
    }

    return null;
  }
Esempio n. 9
0
 public void setUpSolrFile(String url) throws Exception {
   if (setUpIsDone) {
     return;
   }
   // do the setup
   File testDir = (Paths.get(getClass().getResource("/" + testFile).toURI()).getParent()).toFile();
   ProcessBuilder pb =
       new ProcessBuilder("java", "-Durl=" + url + "/update", "-jar", "post.jar", testFile);
   pb.directory(testDir);
   LOGGER.log(Level.FINE, "Starting SOLR import");
   final Process command = pb.start();
   LOGGER.log(Level.FINE, "Started SOLR import");
   String line;
   BufferedReader bri = new BufferedReader(new InputStreamReader(command.getInputStream()));
   BufferedReader bre = new BufferedReader(new InputStreamReader(command.getErrorStream()));
   while ((line = bri.readLine()) != null) {
     LOGGER.log(Level.FINE, line);
   }
   bri.close();
   while ((line = bre.readLine()) != null) {
     LOGGER.log(Level.FINE, line);
   }
   bre.close();
   int i = command.waitFor();
   assertTrue(i == 0);
   LOGGER.log(Level.FINE, "SOLR import DONE!");
   setUpIsDone = true;
 }
Esempio n. 10
0
  private static String getMessageFromResourceBundle(String key, Locale locale) {
    ResourceBundle bundle;
    String message = "";

    if (locale == null) {
      locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
    }

    try {
      bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale, getCurrentLoader(BUNDLE_NAME));
      if (bundle == null) {
        return NOT_FOUND;
      }
    } catch (MissingResourceException e) {
      LOGGER.log(Level.INFO, e.getMessage(), e);
      return NOT_FOUND;
    }

    try {
      message = bundle.getString(key);
    } catch (Exception e) {
      LOGGER.log(Level.INFO, e.getMessage(), e);
    }
    return message;
  }
Esempio n. 11
0
  public boolean removePlayer(RocketPlayer player) {
    logger.log(Level.INFO, "{0} leaves {1}", new Object[] {player.getName(), this.getName()});

    AppContext.getDataManager().markForUpdate(this);
    Channel tableChannel = tableChannelRef.getForUpdate();
    tableChannel.leave(player.getClientSessionRef().get());

    // The reference created below should be identical to one of the players
    // on our table. I think createReference has some clever logic to
    // not create another reference if one already exists.
    ManagedReference<RocketPlayer> playerRef = AppContext.getDataManager().createReference(player);

    if (playerRef.equals(player1Ref)) {
      player1Ref = null;
    } else if (playerRef.equals(player2Ref)) {
      player2Ref = null;
    } else if (playerRef.equals(player3Ref)) {
      player3Ref = null;
    } else if (playerRef.equals(player4Ref)) {
      player4Ref = null;
    } else {
      logger.log(
          Level.SEVERE, "player " + player.getName() + " doesn't appear to be one of this table!");
      return false;
    }

    setTableAvailable(true);
    maybeChangeStatusOnRemovePlayer();
    return true;
  }
Esempio n. 12
0
  public static ResultSet executeSql(final Statement statement, final String sql) {
    ResultSet results = null;
    if (statement == null) {
      return results;
    }
    if (isBlank(sql)) {
      LOGGER.log(Level.FINE, "No SQL provided", new RuntimeException());
      return results;
    }

    try {
      statement.clearWarnings();

      final boolean hasResults = statement.execute(sql);
      if (hasResults) {
        results = statement.getResultSet();
      } else {
        final int updateCount = statement.getUpdateCount();
        LOGGER.log(
            Level.FINE,
            String.format("No results. Update count of %d for query: %s", updateCount, sql));
      }

      SQLWarning sqlWarning = statement.getWarnings();
      while (sqlWarning != null) {
        LOGGER.log(Level.INFO, sqlWarning.getMessage(), sqlWarning);
        sqlWarning = sqlWarning.getNextWarning();
      }

      return results;
    } catch (final SQLException e) {
      LOGGER.log(Level.WARNING, "Error executing: " + sql, e);
      return null;
    }
  }
Esempio n. 13
0
 public synchronized void checkPayments() throws BitcoinException {
   Bitcoin.TransactionsSinceBlock t =
       monitorBlock == null ? bitcoin.listSinceBlock() : bitcoin.listSinceBlock(monitorBlock);
   for (Bitcoin.Transaction transaction : t.transactions()) {
     if ("receive".equals(transaction.category())) {
       if (!seen.add(transaction.txId())) continue;
       for (BitcoinPaymentListener listener : listeners) {
         try {
           listener.transaction(transaction);
         } catch (Exception ex) {
           logger.log(Level.SEVERE, null, ex);
         }
       }
     }
   }
   if (!t.lastBlock().equals(lastBlock)) {
     seen.clear();
     lastBlock = t.lastBlock();
     updateMonitorBlock();
     for (BitcoinPaymentListener listener : listeners) {
       try {
         listener.block(lastBlock);
       } catch (Exception ex) {
         logger.log(Level.SEVERE, null, ex);
       }
     }
   }
 }
Esempio n. 14
0
  @Post
  public void newReport(Representation value) throws FileUploadException, IOException {

    if (value == null || !MediaType.MULTIPART_FORM_DATA.equals(value.getMediaType(), true)) {
      logger.log(Level.SEVERE, "POST request with no entity.");
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return;
    }

    RequestParam parameters = Util.getParameters(getRequest());

    if (parameters == null) {
      logger.log(Level.SEVERE, "POST request with invalid parameters");
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return;
    }

    Report report = Util.createReport(parameters);

    if (report == null) {
      getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
    } else {
      getResponse().setStatus(Status.SUCCESS_CREATED);
    }

    return;
  }
Esempio n. 15
0
  public void send(final WebSocketMessage message, final boolean clearSessionId) {

    // return session status to client
    message.setSessionValid(isAuthenticated());

    // whether to clear the token (all command except LOGIN (for now) should absolutely do this!)
    if (clearSessionId) {

      message.setSessionId(null);
    }

    // set callback
    message.setCallback(callback);
    if (isAuthenticated() || "STATUS".equals(message.getCommand())) {

      String msg = gson.toJson(message, WebSocketMessage.class);

      logger.log(
          Level.FINE,
          "############################################################ SENDING \n{0}",
          msg);

      try {

        session.getRemote().sendString(msg);

      } catch (Throwable t) {
        logger.log(Level.WARNING, "Unable to send websocket message to remote client");
      }

    } else {

      logger.log(Level.WARNING, "NOT sending message to unauthenticated client.");
    }
  }
Esempio n. 16
0
  /**
   * Find the branch type by branch type id.
   *
   * @param branchTypeId the branch type id.
   * @return the BranchType with the given id, or null if the branchType is not found.
   */
  @Override
  public BranchType findById(Integer branchTypeId) {
    BranchType branchType = null;
    ResultSet resultSet = null;
    PreparedStatement preparedStatement = null;
    try {
      Connection connection = DatabaseManager.getInstance().getConnection();
      preparedStatement =
          connection.prepareStatement(
              FIND_BY_ID, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
      preparedStatement.setInt(1, branchTypeId);

      resultSet = preparedStatement.executeQuery();
      if (resultSet.next()) {
        String branchTypeName = resultSet.getString(2);

        branchType = new BranchType();
        branchType.setBranchTypeId(branchTypeId);
        branchType.setBranchTypeName(branchTypeName);
      }
    } catch (SQLException e) {
      LOGGER.log(Level.SEVERE, "BranchTypeDAOImpl: SQL exception in findById", e);
    } catch (IllegalStateException e) {
      LOGGER.log(Level.SEVERE, "BranchTypeDAOImpl: exception in findById", e);
    } finally {
      closeDbResources(resultSet, preparedStatement);
    }
    return branchType;
  }
Esempio n. 17
0
  /**
   * Find all branch types.
   *
   * @return a List of all the branch types.
   */
  @Override
  public List<BranchType> findAll() {
    List<BranchType> branchTypeList = new ArrayList<>();
    ResultSet resultSet = null;
    PreparedStatement preparedStatement = null;
    try {
      Connection connection = DatabaseManager.getInstance().getConnection();
      preparedStatement =
          connection.prepareStatement(
              FIND_ALL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

      resultSet = preparedStatement.executeQuery();
      while (resultSet.next()) {
        Integer branchTypeId = resultSet.getInt(1);
        String branchTypeName = resultSet.getString(2);

        BranchType branchType = new BranchType();
        branchType.setBranchTypeId(branchTypeId);
        branchType.setBranchTypeName(branchTypeName);

        branchTypeList.add(branchType);
      }
    } catch (SQLException e) {
      LOGGER.log(Level.SEVERE, "BranchTypeDAOImpl: SQL exception in findAll", e);
    } catch (IllegalStateException e) {
      LOGGER.log(Level.SEVERE, "BranchTypeDAOImpl: exception in findAll", e);
    } finally {
      closeDbResources(resultSet, preparedStatement);
    }
    return branchTypeList;
  }
Esempio n. 18
0
  /**
   * Uploads a media file to the Joomla instance.
   *
   * @param subfolder Subfolder to upload the file
   * @param filename Name of the file to upload
   * @param filedata Data contained in the file
   * @return Relative URL of the uploaded file
   * @throws JoomlaException If the file could not be uploaded
   */
  public String uploadMediaFile(String subfolder, String filename, byte[] filedata)
      throws JoomlaException {
    try {
      LOG.log(Level.INFO, "Uploading {0}", new Object[] {filename});
      TimingOutCallback callback = new TimingOutCallback((getTimeout() + 120) * 1000);
      XmlRpcClient client = getXmlRpcClient();

      Object[] params = new Object[] {username, password, subfolder, filename, filedata};

      client.executeAsync(XMLRPC_METHOD_NEW_MEDIA, params, callback);

      String location = (String) callback.waitForResponse();

      LOG.log(Level.INFO, "Media file #{0} uploaded to {1}", new Object[] {filename, location});
      return location;
    } catch (TimeoutException ex) {
      throw new JoomlaException(ex);
    } catch (XmlRpcException ex) {
      throw new JoomlaException(ex);
    } catch (IOException ex) {
      throw new JoomlaException(ex);
    } catch (Throwable t) {
      throw new JoomlaException(t);
    }
  }
  protected String autoCompleteUrl(String url) {
    if (url != null) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Autocompleting url : [" + url + "]");
      }

      if (!url.endsWith(BPM_PLATFORM_XML_FILE)) {
        String appender;
        if (url.contains("/")) {
          appender = "/";
        } else {
          appender = "\\";
        }

        if (!(url.endsWith("/") || url.endsWith("\\\\"))) {
          url += appender;
        }

        url += BPM_PLATFORM_XML_FILE;
      }

      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Autocompleted url : [" + url + "]");
      }
    }

    return url;
  }
Esempio n. 20
0
  private String readGraphVizOpts(final Config config) {
    final String scGraphVizOptsCfg = getStringValue(config, GRAPH_GRAPHVIZ_OPTS, "");
    if (!Utility.isBlank(scGraphVizOptsCfg)) {
      LOGGER.log(
          Level.CONFIG,
          "Using additional GraphViz command-line options from config, " + scGraphVizOptsCfg);
      return scGraphVizOptsCfg;
    }

    final String scGraphVizOptsProp = System.getProperty(SC_GRAPHVIZ_OPTS);
    if (!Utility.isBlank(scGraphVizOptsProp)) {
      LOGGER.log(
          Level.CONFIG,
          "Using additional GraphViz command-line options from SC_GRAPHVIZ_OPTS system property, "
              + scGraphVizOptsProp);
      return scGraphVizOptsProp;
    }

    final String scGraphVizOptsEnv = System.getenv(SC_GRAPHVIZ_OPTS);
    if (!Utility.isBlank(scGraphVizOptsEnv)) {
      LOGGER.log(
          Level.CONFIG,
          "Using additional GraphViz command-line options from SC_GRAPHVIZ_OPTS environmental variable, "
              + scGraphVizOptsEnv);
      return scGraphVizOptsEnv;
    }

    return "";
  }
Esempio n. 21
0
 protected SelectableChannel getSelectableChannel(
     SocketAddress remoteAddress, SocketAddress localAddress) throws IOException {
   SocketChannel newSocketChannel = SocketChannel.open();
   Socket newSocket = newSocketChannel.socket();
   if (receiveBufferSize > 0) {
     try {
       newSocket.setReceiveBufferSize(receiveBufferSize);
     } catch (SocketException se) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setReceiveBufferSize exception ", se);
     } catch (IllegalArgumentException iae) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setReceiveBufferSize exception ", iae);
     }
   }
   if (sendBufferSize > 0) {
     try {
       newSocket.setSendBufferSize(sendBufferSize);
     } catch (SocketException se) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setSendBufferSize exception ", se);
     } catch (IllegalArgumentException iae) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setSendBufferSize exception ", iae);
     }
   }
   newSocket.setReuseAddress(reuseAddress);
   if (localAddress != null) newSocket.bind(localAddress);
   newSocketChannel.configureBlocking(false);
   return newSocketChannel;
 }
Esempio n. 22
0
  /**
   * Return the appropriate {@link javax.faces.webapp.FacesServlet} mapping based on the servlet
   * path of the current request.
   *
   * @param servletPath the servlet path of the request
   * @param pathInfo the path info of the request
   * @return the appropriate mapping based on the current request
   * @see javax.servlet.http.HttpServletRequest#getServletPath()
   */
  private static String getMappingForRequest(String servletPath, String pathInfo) {

    if (servletPath == null) {
      return null;
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "servletPath " + servletPath);
      LOGGER.log(Level.FINE, "pathInfo " + pathInfo);
    }
    // If the path returned by HttpServletRequest.getServletPath()
    // returns a zero-length String, then the FacesServlet has
    // been mapped to '/*'.
    if (servletPath.length() == 0) {
      return "/*";
    }

    // presence of path info means we were invoked
    // using a prefix path mapping
    if (pathInfo != null) {
      return servletPath;
    } else if (servletPath.indexOf('.') < 0) {
      // if pathInfo is null and no '.' is present, assume the
      // FacesServlet was invoked using prefix path but without
      // any pathInfo - i.e. GET /contextroot/faces or
      // GET /contextroot/faces/
      return servletPath;
    } else {
      // Servlet invoked using extension mapping
      return servletPath.substring(servletPath.lastIndexOf('.'));
    }
  }
  /**
   * Check if a configuration update is needed.
   *
   * <p>There are two main reasons that can trigger a configuration update. Either there is a
   * configuration update happening in the cluster, or operations added to the queue can not find
   * their corresponding node. For the latter, see the {@link #pastReconnThreshold()} method for
   * further details.
   *
   * <p>If a configuration update is needed, a resubscription for configuration updates is
   * triggered. Note that since reconnection takes some time, the method will also wait a time
   * period given by {@link #getMinReconnectInterval()} before the resubscription is triggered.
   */
  void checkConfigUpdate() {
    if (needsReconnect || pastReconnThreshold()) {
      long now = System.currentTimeMillis();
      long intervalWaited = now - this.configProviderLastUpdateTimestamp;
      if (intervalWaited < this.getMinReconnectInterval()) {
        LOGGER.log(
            Level.FINE,
            "Ignoring config update check. Only {0}ms out"
                + " of a threshold of {1}ms since last update.",
            new Object[] {intervalWaited, this.getMinReconnectInterval()});
        return;
      }

      if (doingResubscribe.compareAndSet(false, true)) {
        resubConfigUpdate();
      } else {
        LOGGER.log(Level.CONFIG, "Duplicate resubscribe for config updates" + " suppressed.");
      }
    } else {
      LOGGER.log(
          Level.FINE,
          "No reconnect required, though check requested."
              + " Current config check is {0} out of a threshold of {1}.",
          new Object[] {configThresholdCount, maxConfigCheck});
    }
  }
 public void onCreate$tipoAbonoMttoWindow(Event event) throws Exception {
   logger.log(Level.INFO, "[TipoAbonoMttoCtrl][onCreate$tipoAbonoMttoWindow]");
   try {
     doOnCreateCommon(this.tipoAbonoMttoWindow, event);
     MensajeMultilinea.doSetTemplate();
     if (this.args.containsKey("gestorTipoAbonoCtrl")) {
       tipoAbonoListaCtrl = (GestorTipoAbonoCtrl) this.args.get("gestorTipoAbonoCtrl");
     } else {
       tipoAbonoListaCtrl = null;
     }
     if (this.args.containsKey("accion")) {
       accion = (Integer) this.args.get("accion");
     } else {
       accion = Constants.ACCION_MANTTO_NEW;
     }
     if (this.args.containsKey("tipoAbonoSelected")) {
       tipoAbonoSelected = (TipoAbono) this.args.get("tipoAbonoSelected");
     } else {
       tipoAbonoSelected = new TipoAbono();
     }
     cargarDatosIniciales();
     tipoAbonoMttoWindow.doModal();
     verificarEstadoBotones();
   } catch (Exception e) {
     logger.log(Level.SEVERE, e.getLocalizedMessage());
     e.printStackTrace();
   }
 }
Esempio n. 25
0
 @Override
 public void entryAdded(EntryEvent<String, BpmEvent> event) {
   BpmEvent bpmEvent = event.getValue();
   logger.log(
       Level.INFO,
       "BpmEventListener.entryAdded executor {0}",
       new Object[] {bpmEvent.getExecutor()});
   try {
     BpmEvent.EXECUTOR executor = bpmEvent.getExecutor();
     switch (executor) {
       case ACTOR_RESOLVER:
         InternalAPI.get().executeActorResolver(bpmEvent.getCaseId(), bpmEvent.getTaskId());
         break;
       case CONNECTOR:
         InternalAPI.get().executeConnectorOut(bpmEvent.getCaseId(), bpmEvent.getTaskId());
         break;
       case JOIN:
         InternalAPI.get()
             .executeJoin(bpmEvent.getCaseId(), bpmEvent.getTaskId(), bpmEvent.getJoinId());
         break;
       case TRANSITION:
         InternalAPI.get().executeTransition(bpmEvent.getCaseId(), bpmEvent.getTaskId());
         break;
     }
     HazelcastServer.removeBpmEvent(bpmEvent);
   } catch (Exception ex) {
     logger.log(Level.SEVERE, ex.getMessage(), ex);
   }
 }
Esempio n. 26
0
  /**
   * Create a new Server object to listen to connections on the given port
   *
   * @param port Port for the server to listen on.
   * @return New Server object
   */
  public static Server createServer(int port) {

    logger.log(Level.INFO, "Starting server on port {0}", port);
    logger.log(Level.INFO, "Server version: {0}", SERVER_VERSION);

    return new Server(port);
  }
Esempio n. 27
0
  static {
    // check if we have JAI and or ImageIO

    // if these classes are here, then the runtine environment has
    // access to JAI and the JAI ImageI/O toolbox.
    boolean available = true;
    try {
      Class.forName("javax.media.jai.JAI");
    } catch (Throwable e) {
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
      available = false;
    }
    JAIAvailable = available;

    available = true;
    try {
      Class<?> clazz = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi");
      readerSpi = (ImageReaderSpi) clazz.newInstance();
      Class<?> clazz1 = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriterSpi");
      writerSpi = (ImageWriterSpi) clazz1.newInstance();

    } catch (Throwable e) {
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
      readerSpi = null;
      writerSpi = null;
      available = false;
    }
    TiffAvailable = available;

    final HashSet<String> tempSet = new HashSet<String>(2);
    tempSet.add(".tfw");
    tempSet.add(".tiffw");
    tempSet.add(".wld");
    TIFF_WORLD_FILE_EXT = Collections.unmodifiableSet(tempSet);
  }
Esempio n. 28
0
  /** Assume the frame size is 4. */
  public byte[] reverseFrames(byte[] data) {
    byte[] reversed = new byte[data.length];
    byte[] frame = new byte[4];

    for (int ii = 0; ii < data.length / 4; ii++) {
      int first = (data.length) - ((ii + 1) * 4) + 0;
      int last = (data.length) - ((ii + 1) * 4) + 3;
      frame[0] = data[first];
      frame[1] = data[(data.length) - ((ii + 1) * 4) + 1];
      frame[2] = data[(data.length) - ((ii + 1) * 4) + 2];
      frame[3] = data[last];

      reversed[ii * 4 + 0] = frame[0];
      reversed[ii * 4 + 1] = frame[1];
      reversed[ii * 4 + 2] = frame[2];
      reversed[ii * 4 + 3] = frame[3];
      if (ii < 5 || ii > (data.length / 4) - 5) {
        logger.log(Level.FINER, "From \t" + first + " \tlast " + last);
        logger.log(Level.FINER, "To \t" + ((ii * 4) + 0) + " \tlast " + ((ii * 4) + 3));
      }
    }

    /*
     * for (int ii=0; ii<data.length; ii++) { reversed[ii] =
     * data[data.length-1-ii]; }
     */

    return reversed;
  }
Esempio n. 29
0
 /**
  * @param sql the sql query
  * @param data the items to update in the sql query in place of question marks
  * @param findExisting whether to first check if the data already exists before updating
  * @return insert id
  * @throws SQLException
  */
 public long executeUpdate(String sql, List<Object> data, boolean findExisting)
     throws SQLException {
   // Convert the UPDATE query into a SELECT query to find the ID
   String select =
       sql.toLowerCase()
           .replaceAll("update (.*) set (.*) where (.*)", "SELECT * FROM $1 WHERE $2 AND $3");
   select = select.replace(",", " AND ");
   if (findExisting) {
     try {
       long firstCol = queryFirstColumn(select, data);
       if (firstCol != -1) {
         return firstCol;
       }
     } catch (SQLException e) {
       LOGGER.log(Level.WARNING, "Querying existing ID failed", e);
     }
   }
   PreparedStatement ps = prepare(sql, data);
   if (debugMode) {
     LOGGER.finer("Debug mode: returned -1 as update ID");
     return -1;
   }
   ps.executeUpdate();
   try {
     return queryFirstColumn(select, data);
   } catch (SQLException e) {
     LOGGER.log(Level.WARNING, "Querying existing ID failed", e);
   }
   return -1;
 }
 /**
  * Tell the user about, and log, an exception.
  *
  * @param except the exception in question
  * @param filename what file was being read
  */
 private void printError(final Exception except, final String filename) {
   if (except instanceof MapVersionException) {
     LOGGER.log(Level.SEVERE, "Map version in " + filename + " not acceptable to reader", except);
     printParagraph("ERROR: Map version not acceptable to reader", ERROR_COLOR);
   } else if (except instanceof FileNotFoundException || except instanceof NoSuchFileException) {
     printParagraph("ERROR: File not found", ERROR_COLOR);
     LOGGER.log(Level.SEVERE, filename + " not found", except);
   } else if (except instanceof IOException) {
     //noinspection HardcodedFileSeparator
     printParagraph("ERROR: I/O error reading file", ERROR_COLOR);
     //noinspection HardcodedFileSeparator
     LOGGER.log(Level.SEVERE, "I/O error reading " + filename, except);
   } else if (except instanceof XMLStreamException) {
     printParagraph(
         "ERROR: Malformed XML in the file" + "; see following error message for details",
         ERROR_COLOR);
     final String message =
         NullCleaner.valueOrDefault(except.getLocalizedMessage(), "(message was null)");
     printParagraph(message, ERROR_COLOR);
     LOGGER.log(Level.SEVERE, "Malformed XML in file " + filename, except);
   } else if (except instanceof SPFormatException) {
     printParagraph(
         "ERROR: SP map format error at line "
             + ((SPFormatException) except).getLine()
             + "; see following error message for details",
         ERROR_COLOR);
     final String message =
         NullCleaner.valueOrDefault(except.getLocalizedMessage(), "(message was null)");
     printParagraph(message, ERROR_COLOR);
     LOGGER.log(Level.SEVERE, "SP map format error reading " + filename, except);
   } else {
     throw new IllegalStateException("Unhandled exception class");
   }
 }