/**
   * execute, the static version of executing an update or insert on a table in the database.
   *
   * @param query a static SQL statement which updates or inserts.
   */
  public void execute(String query) {
    clearSignals();

    Connection con = null;
    PreparedStatement ps = null;
    try {
      con = ds.getConnection();
      if (con.isClosed()) {
        if (logger.isWarnEnabled()) logger.warn("Connection is closed: EntityDAO.execute!");
        throw new SQLException();
      }
      ps = con.prepareStatement(query);

      if (ps.executeUpdate() != 1) {
        logger.warn("Problem with executing static query, EntityDAO: " + query);
        throw new SQLException();
      } else {
        signalSuccess();
        logger.info("Executing static query, EntityDAO: " + query);
      }
    } catch (SQLException sqle) {
      signalFailure(sqle);
      if (logger.isWarnEnabled()) {
        logger.warn(
            "Exeception while executing static statement, GenericDAO.execute: "
                + query
                + ":message: "
                + sqle.getMessage());
        sqle.printStackTrace();
      }
    } finally {
      this.closeIfNecessary(con, ps);
    }
  }
  // Added by YW, 11-26-2007
  public ArrayList select(String query, Connection con) {
    clearSignals();

    ArrayList results = new ArrayList();
    ResultSet rs = null;
    PreparedStatement ps = null;
    try {
      if (con.isClosed()) {
        if (logger.isWarnEnabled()) logger.warn("Connection is closed: GenericDAO.select!");
        throw new SQLException();
      }

      ps = con.prepareStatement(query);
      rs = ps.executeQuery();
      if (logger.isInfoEnabled()) {
        logger.info("Executing dynamic query, EntityDAO.select:query " + query);
      }
      signalSuccess();
      results = this.processResultRows(rs);

    } catch (SQLException sqle) {
      signalFailure(sqle);
      if (logger.isWarnEnabled()) {
        logger.warn(
            "Exeception while executing dynamic query, GenericDAO.select: "
                + query
                + ":message: "
                + sqle.getMessage());
        sqle.printStackTrace();
      }
    } finally {
      this.closeIfNecessary(rs, ps);
    }
    return results;
  }
  /**
   * Called immediately after an element has been put into the cache and the element already existed
   * in the cache. This is thus an update.
   *
   * <p>The {@link net.sf.ehcache.Cache#put(net.sf.ehcache.Element)} method will block until this
   * method returns.
   *
   * <p>Implementers may wish to have access to the Element's fields, including value, so the
   * element is provided. Implementers should be careful not to modify the element. The effect of
   * any modifications is undefined.
   *
   * @param cache the cache emitting the notification
   * @param element the element which was just put into the cache.
   */
  public final void notifyElementUpdated(final Ehcache cache, final Element element)
      throws CacheException {
    if (notAlive()) {
      return;
    }
    if (!replicateUpdates) {
      return;
    }

    if (replicateUpdatesViaCopy) {
      if (!element.isSerializable()) {
        if (LOG.isWarnEnabled()) {
          LOG.warn(
              "Object with key "
                  + element.getObjectKey()
                  + " is not Serializable and cannot be updated via copy.");
        }
        return;
      }
      addToReplicationQueue(new CacheEventMessage(EventMessage.PUT, cache, element, null));
    } else {
      if (!element.isKeySerializable()) {
        if (LOG.isWarnEnabled()) {
          LOG.warn(
              "Object with key "
                  + element.getObjectKey()
                  + " does not have a Serializable key and cannot be replicated via invalidate.");
        }
        return;
      }
      addToReplicationQueue(
          new CacheEventMessage(EventMessage.REMOVE, cache, null, element.getKey()));
    }
  }
Example #4
1
  public E get(long index) {
    RandomAccessFile randomSerializeIndexFile = null;
    RandomAccessFile randomSerializeFile = null;
    E result = null;
    Lock lock = readWriteLock.readLock();
    lock.lock();
    Throwable throwable = null;
    long elementsCount = 0;
    try {
      if (!dataFile.canRead() || !indexFile.canRead()) {
        return null;
      }
      randomSerializeIndexFile = new RandomAccessFile(indexFile, "r");
      randomSerializeFile = new RandomAccessFile(dataFile, "r");
      elementsCount = internalGetSize(randomSerializeIndexFile);
      if (index >= 0 && index < elementsCount) {
        long offset = internalOffsetOfElement(randomSerializeIndexFile, index);
        result = internalReadElement(randomSerializeFile, offset);

        return result;
      }
    } catch (Throwable e) {
      throwable = e;
    } finally {
      IOUtilities.closeQuietly(randomSerializeFile);
      IOUtilities.closeQuietly(randomSerializeIndexFile);
      lock.unlock();
    }

    // it's a really bad idea to log while locked *sigh*
    if (throwable != null) {
      if (throwable instanceof ClassNotFoundException
          || throwable instanceof InvalidClassException) {
        if (logger.isWarnEnabled())
          logger.warn("Couldn't deserialize object at index " + index + "!\n" + throwable);
      } else if (throwable instanceof ClassCastException) {
        if (logger.isWarnEnabled())
          logger.warn("Couldn't cast deserialized object at index " + index + "!\n" + throwable);
      } else {
        if (logger.isWarnEnabled())
          logger.warn("Couldn't retrieve element at index " + index + "!", throwable);
      }
      IOUtilities.interruptIfNecessary(throwable);
    } else if (index < 0 || index >= elementsCount) {
      if (logger.isInfoEnabled()) {
        logger.info(
            "index ("
                + index
                + ") must be in the range [0..<"
                + elementsCount
                + "]. Returning null.");
      }
      return null;
    }

    return result;
  }
  /**
   * This method inserts one row for an entity table and gets latestPK of this row.
   *
   * @param query
   * @param variables
   * @param nullVars
   * @author ywang 11-26-2007
   */
  public void executeWithPK(String query, HashMap variables, HashMap nullVars) {
    clearSignals();

    Connection con = null;
    PreparedStatement ps = null;
    PreparedStatementFactory psf = new PreparedStatementFactory(variables, nullVars);
    try {
      con = ds.getConnection();
      if (con.isClosed()) {
        if (logger.isWarnEnabled()) logger.warn("Connection is closed: EntityDAO.execute!");
        throw new SQLException();
      }
      ps = con.prepareStatement(query);
      ps = psf.generate(ps); // enter variables here!
      if (ps.executeUpdate() != 1) {
        logger.warn("Problem with executing dynamic query, EntityDAO: " + query);
        throw new SQLException();

      } else {
        logger.info("Executing dynamic query, EntityDAO: " + query);

        if (getCurrentPKName == null) {
          this.latestPK = 0;
        }

        this.unsetTypeExpected();
        this.setTypeExpected(1, TypeNames.INT);

        ArrayList al = select(digester.getQuery(getCurrentPKName), con);

        if (al.size() > 0) {
          HashMap h = (HashMap) al.get(0);
          this.latestPK = ((Integer) h.get("key")).intValue();
        }
      }

    } catch (SQLException sqle) {
      signalFailure(sqle);
      if (logger.isWarnEnabled()) {
        logger.warn(
            "Exception while executing dynamic statement, EntityDAO.execute: "
                + query
                + ": "
                + sqle.getMessage());
        sqle.printStackTrace();
      }
    } finally {
      this.closeIfNecessary(con, ps);
    }
  }
  /**
   *
   *
   * <pre>
   * 查询总数
   * </pre>
   *
   * @author jundong.xu_C
   * @param page
   * @param parameterObject
   * @param mappedStatement
   * @param connection
   * @throws SQLException
   */
  protected void queryTotalRecord(
      Page<?> page, Object parameterObject, MappedStatement mappedStatement, Connection connection)
      throws SQLException {
    BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
    String sql = boundSql.getSql();
    String countSql = this.buildCountSql(sql);
    if (log.isDebugEnabled()) {
      log.debug("分页时, 生成countSql: " + countSql);
    }

    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    BoundSql countBoundSql =
        new BoundSql(
            mappedStatement.getConfiguration(), countSql, parameterMappings, parameterObject);
    ParameterHandler parameterHandler =
        new DefaultParameterHandler(mappedStatement, parameterObject, countBoundSql);
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = connection.prepareStatement(countSql);
      parameterHandler.setParameters(pstmt);
      rs = pstmt.executeQuery();
      if (rs.next()) {
        long totalRecord = rs.getLong(1);
        int pageSize = page.getPageSize();
        int totalPage = (int) (totalRecord + pageSize - 1) / pageSize;
        page.setTotalSize(totalRecord);
        page.setTotalPage(totalPage);
      }
    } finally {
      if (rs != null)
        try {
          rs.close();
        } catch (Exception e) {
          if (log.isWarnEnabled()) {
            log.warn("关闭ResultSet时异常.", e);
          }
        }
      if (pstmt != null)
        try {
          pstmt.close();
        } catch (Exception e) {
          if (log.isWarnEnabled()) {
            log.warn("关闭PreparedStatement时异常.", e);
          }
        }
    }
  }
 public BufferedImage createGraphImage(
     long nowInSeconds, SourceIdentifier sourceIdentifier, BufferedImage result, boolean showMax) {
   RrdGraphDef graphDef = getGraphDef(nowInSeconds, sourceIdentifier, showMax);
   //noinspection SynchronizationOnLocalVariableOrMethodParameter
   synchronized (graphDef) {
     RrdGraph graph;
     try {
       graph = new RrdGraph(graphDef);
       RrdGraphInfo graphInfo = graph.getRrdGraphInfo();
       int width = graphInfo.getWidth();
       int height = graphInfo.getHeight();
       if (result != null && (result.getWidth() != width || result.getHeight() != height)) {
         if (logger.isInfoEnabled()) logger.info("Flushing previous image because of wrong size.");
         result.flush();
         result = null;
       }
       if (result == null) {
         result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
         if (logger.isInfoEnabled()) logger.info("Created new image.");
       }
       graph.render(result.getGraphics());
     } catch (IOException ex) {
       if (logger.isWarnEnabled()) logger.warn("Exception while creating graph!", ex);
       if (result != null) {
         result.flush();
         result = null;
       }
     }
   }
   return result;
 }
Example #8
0
  private void connect(
      final Integer fromFacebookId,
      final Integer toFacebookId,
      final ConnectionType connectionType) {
    final Transaction transaction = graphDb.beginTx();
    try {
      final Node fromNode = this.getIndexedNode(fromFacebookId);
      final Node toNode = this.getIndexedNode(toFacebookId);

      if (fromNode == null || toNode == null) {
        if (logger.isWarnEnabled()) {
          logger.warn("Can't connect nodes {} <> {} because one or both does not exists.");
        }
        throw new ResourceNotFoundException("One or both sides of the connection does not exists.");
      }

      fromNode.createRelationshipTo(toNode, connectionType);

      if (logger.isInfoEnabled()) {
        logger.info(
            "{} is now Connected to {} with the {} relation.",
            fromNode.getProperty(Neo4JPersonRepository.PROPERTY_NAME),
            toNode.getProperty(Neo4JPersonRepository.PROPERTY_NAME),
            connectionType);
      }

      transaction.success();
    } catch (final Exception e) {
      transaction.failure();
      logger.error("Error connecting " + fromFacebookId + " to " + toFacebookId + ".", e);
      throw e;
    } finally {
      transaction.finish();
    }
  }
Example #9
0
  /**
   * Converts the given process into an unordered set of ActivityElements
   *
   * @param processResource
   */
  public void removeProcessOrder() {
    if (logger.isWarnEnabled()) {
      logger.warn(
          String.format(
              "Giving up all attempts to repair process, %1$s. Treating it as an unordered set of Activities.",
              process.getLabel()));
    }
    Resource startElement = process.getStartElement();
    Resource endElement = process.getEndElement();
    // make sure start element is ready to go with no arcs
    if (null == startElement) {
      // create a start element
      startElement = createStartElement();
    } else {
      isolateElement(startElement);
    }

    // make sure end element is ready to go with no arcs
    if (null == endElement) {
      // create an end element
      endElement = createEndElement();
    } else {
      isolateElement(endElement);
    }
    // isolate activity elements
    Set<Resource> processElements = process.getProcessElements();
    for (Resource r : processElements) {
      // isolate will remove in/out links and delete the element if it's
      // not Activity, Start, or End
      isolateElement(r);
    }

    finalizeProcess();
  }
  /**
   * Initializes (post construction) DataManager, its LocationMapper and Locators, and Context
   *
   * @see org.graphity.util.manager.DataManager
   * @see org.graphity.util.locator
   * @see <a
   *     href="http://jena.apache.org/documentation/javadoc/jena/com/hp/hpl/jena/util/FileManager.html">FileManager</a>
   * @see <a
   *     href="http://jena.apache.org/documentation/javadoc/jena/com/hp/hpl/jena/util/LocationMapper.html">LocationMapper</a>
   * @see <a
   *     href="http://jena.apache.org/documentation/javadoc/jena/com/hp/hpl/jena/util/Locator.html">Locator</a>
   * @see <a
   *     href="http://jena.apache.org/documentation/javadoc/arq/com/hp/hpl/jena/sparql/util/Context.html">Context</a>
   */
  @PostConstruct
  public void init() {
    if (log.isDebugEnabled())
      log.debug(
          "Application.init() with ResourceConfig: {} and SerlvetContext: {}",
          getResourceConfig(),
          getServletContext());
    SysRIOT.wireIntoJena(); // enable RIOT parser
    // WARNING! ontology caching can cause concurrency/consistency problems
    OntDocumentManager.getInstance().setCacheModels(false);

    if (getResourceConfig().getProperty(VoID.sparqlEndpoint.getURI()) == null)
      throw new IllegalArgumentException("No SPARQL endpoint URI specified in web.xml");

    {
      String endpointURI = (String) getResourceConfig().getProperty(VoID.sparqlEndpoint.getURI());
      String authUser = (String) getResourceConfig().getProperty(Service.queryAuthUser.getSymbol());
      String authPwd = (String) getResourceConfig().getProperty(Service.queryAuthPwd.getSymbol());
      if (authUser != null && authPwd != null)
        configureServiceContext(endpointURI, authUser, authPwd);
    }

    if (getResourceConfig().getProperty(GS.sparqlGraphStore.getURI()) != null) {
      String graphStoreURI = (String) getResourceConfig().getProperty(GS.sparqlGraphStore.getURI());
      // reuses SPARQL query endpoint authentication properties -- not ideal
      String authUser = (String) getResourceConfig().getProperty(Service.queryAuthUser.getSymbol());
      String authPwd = (String) getResourceConfig().getProperty(Service.queryAuthPwd.getSymbol());
      if (authUser != null && authPwd != null)
        configureServiceContext(graphStoreURI, authUser, authPwd);
    } else {
      if (log.isWarnEnabled())
        log.warn("No SPARQL Graph Store URI specified in web.xml. The server will be read-only.");
    }
  }
  /**
   * @see com.eyeq.pivot4j.ui.aggregator.AggregatorFactory#createAggregator(java.lang.String,
   *     org.olap4j.Axis, java.util.List, org.olap4j.metadata.Level, org.olap4j.metadata.Measure)
   */
  @Override
  public Aggregator createAggregator(
      String name, Axis axis, List<Member> members, Level level, Measure measure) {
    if (name == null) {
      throw new NullArgumentException("name");
    }

    if (axis == null) {
      throw new NullArgumentException("axis");
    }

    Aggregator aggregator = null;

    if (TotalAggregator.NAME.equals(name)) {
      aggregator = new TotalAggregator(axis, members, level, measure);
    } else if (AverageAggregator.NAME.equals(name)) {
      aggregator = new AverageAggregator(axis, members, level, measure);
    } else if (MinimumAggregator.NAME.equals(name)) {
      aggregator = new MinimumAggregator(axis, members, level, measure);
    } else if (MaximumAggregator.NAME.equals(name)) {
      aggregator = new MaximumAggregator(axis, members, level, measure);
    } else if (CountAggregator.NAME.equals(name)) {
      aggregator = new CountAggregator(axis, members, level, measure);
    }

    if (aggregator == null) {
      Logger logger = LoggerFactory.getLogger(getClass());
      if (logger.isWarnEnabled()) {
        logger.warn("Unknown aggregator name : " + name);
      }
    }

    return aggregator;
  }
Example #12
0
  @Override
  public void testLog(String level) throws IOException {

    log.error(
        String.format(
            "Initiate logging with log set to: error %s, warn: %s, info %s, debug %s, trace %s",
            log.isErrorEnabled(),
            log.isWarnEnabled(),
            log.isInfoEnabled(),
            log.isDebugEnabled(),
            log.isTraceEnabled()));

    String msg = "Now I'm logging at level: %s";

    if (level.equalsIgnoreCase("error")) {
      log.error(String.format(msg, level));
    } else if (level.equalsIgnoreCase("warn")) {
      log.warn(String.format(msg, level));
    } else if (level.equalsIgnoreCase("info")) {
      log.info(String.format(msg, level));
    } else if (level.equalsIgnoreCase("debug")) {
      log.debug(String.format(msg, level));
    } else if (level.equalsIgnoreCase("trace")) {
      log.trace(String.format(msg, level));
    }
  }
Example #13
0
 @Override
 @Deprecated
 public void warn(String message, Throwable throwable) {
   if (logger.isWarnEnabled()) {
     logger.warn(message, throwable);
   }
 }
Example #14
0
  private void throwSecurityViolationIfNotAllowed(final IObject i) {

    final String type = i.getClass().getName();
    final Details d = i.getDetails();
    final long user = d.getOwner().getId();
    final long group = d.getGroup().getId();

    final EventContext ec = getSecuritySystem().getEventContext();
    final boolean root = ec.isCurrentUserAdmin();
    final List<Long> leaderof = ec.getLeaderOfGroupsList();
    final boolean pi = leaderof.contains(group);
    final boolean own = ec.getCurrentUserId().equals(user);

    if (!own && !root && !pi) {
      if (log.isWarnEnabled()) {
        log.warn(
            String.format(
                "User %d attempted to delete " + type + " %d belonging to User %d",
                ec.getCurrentUserId(),
                i.getId(),
                user));
      }
      throw new SecurityViolation(
          String.format("User %s cannot delete %s %d ", ec.getCurrentUserName(), type, i.getId()));
    }
  }
Example #15
0
 /**
  * Generate header.
  *
  * @param logEventPack the log event pack
  * @return the log header
  */
 private RecordHeader generateHeader(LogEventPack logEventPack) {
   RecordHeader logHeader = null;
   if (header != null) {
     logHeader = new RecordHeader();
     for (LogHeaderStructureDto field : header) {
       switch (field) {
         case KEYHASH:
           logHeader.setEndpointKeyHash(logEventPack.getEndpointKey());
           break;
         case TIMESTAMP:
           logHeader.setTimestamp(System.currentTimeMillis());
           break;
         case TOKEN:
           logHeader.setApplicationToken(applicationToken);
           break;
         case VERSION:
           logHeader.setHeaderVersion(LOG_HEADER_VERSION);
           break;
         case LSVERSION:
           logHeader.setLogSchemaVersion(logEventPack.getLogSchema().getVersion());
           break;
         default:
           if (LOG.isWarnEnabled()) {
             LOG.warn("Current header field [{}] doesn't support", field);
           }
           break;
       }
     }
   }
   return logHeader;
 }
Example #16
0
  @Override
  public String toString() {
    final StringBuilder result = new StringBuilder();
    final String newLine = System.getProperty("line.separator");

    result.append(this.getClass().getName());
    result.append(" Object {");
    result.append(newLine);

    // determine fields declared in this class only (no fields of superclass)
    final Field[] fields = this.getClass().getDeclaredFields();

    // print field names paired with their values
    for (final Field field : fields) {
      result.append("  ");
      try {
        result.append(field.getName());
        result.append(": ");
        // requires access to private field:
        result.append(field.get(this));
      } catch (final IllegalAccessException ex) {
        if (LOGGER.isWarnEnabled()) {
          LOGGER.warn("Caught exception while processing field " + field, ex);
        }
      }
      result.append(newLine);
    }
    result.append("}");

    return result.toString();
  }
Example #17
0
  /**
   * Gets the xML schema.
   *
   * @param partMeta the part meta
   * @return the xML schema
   * @throws Exception the exception
   */
  private static File getXMLSchema(ObjectPartType partMeta) throws Exception {
    final String FILE_SEPARATOR = System.getProperty("file.separator");
    final String XML_SCHEMA_EXTENSION = ".xsd";
    final String SCHEMAS_DIR = "schemas";

    File schemaFile = null;

    //
    // Look for an XML Schema (.xsd) file for the incoming part payload
    //
    String serverRoot = ServiceMain.getInstance().getServerRootDir();
    String schemasDir = serverRoot + FILE_SEPARATOR + SCHEMAS_DIR + FILE_SEPARATOR;
    //
    // Send a warning to the log file if the XML Schema file is missing
    //
    String schemaName = schemasDir + partMeta.getLabel() + XML_SCHEMA_EXTENSION;
    try {
      schemaFile = new File(schemaName);
    } catch (Exception e) {
      if (logger.isWarnEnabled() == true) {
        logger.warn("Missing schema file for incoming payload: " + schemaName);
      }
    }

    return schemaFile;
  }
  public void reduce(
      Text key,
      Iterator<NutchWritable> values,
      OutputCollector<Text, Text> output,
      Reporter reporter)
      throws IOException {
    StringBuffer dump = new StringBuffer();

    dump.append("\nRecno:: ").append(recNo++).append("\n");
    dump.append("URL:: " + key.toString() + "\n");
    while (values.hasNext()) {
      Writable value = values.next().get(); // unwrap
      if (value instanceof CrawlDatum) {
        dump.append("\nCrawlDatum::\n").append(((CrawlDatum) value).toString());
      } else if (value instanceof Content) {
        dump.append("\nContent::\n").append(((Content) value).toString());
      } else if (value instanceof ParseData) {
        dump.append("\nParseData::\n").append(((ParseData) value).toString());
      } else if (value instanceof ParseText) {
        dump.append("\nParseText::\n").append(((ParseText) value).toString());
      } else if (LOG.isWarnEnabled()) {
        LOG.warn("Unrecognized type: " + value.getClass());
      }
    }
    output.collect(key, new Text(dump.toString()));
  }
Example #19
0
  public void add(E element) {
    RandomAccessFile randomSerializeIndexFile = null;
    RandomAccessFile randomSerializeFile = null;
    Throwable throwable = null;
    Lock lock = readWriteLock.writeLock();
    lock.lock(); // FindBugs "Multithreaded correctness - Method does not release lock on all
    // exception paths" is a false positive
    try {
      randomSerializeIndexFile = new RandomAccessFile(indexFile, "rw");
      randomSerializeFile = new RandomAccessFile(dataFile, "rw");
      long elementsCount = internalGetSize(randomSerializeIndexFile);

      long offset = 0;
      if (elementsCount > 0) {
        long prevElement = elementsCount - 1;
        offset = internalOffsetOfElement(randomSerializeIndexFile, prevElement);
        offset = offset + internalReadElementSize(randomSerializeFile, offset) + 4;
      }
      internalWriteElement(randomSerializeFile, offset, element);
      internalWriteOffset(randomSerializeIndexFile, elementsCount, offset);
    } catch (IOException e) {
      throwable = e;
    } finally {
      IOUtilities.closeQuietly(randomSerializeFile);
      IOUtilities.closeQuietly(randomSerializeIndexFile);
      lock.unlock();
    }
    if (throwable != null) {
      // it's a really bad idea to log while locked *sigh*
      if (logger.isWarnEnabled()) logger.warn("Couldn't write element!", throwable);
      IOUtilities.interruptIfNecessary(throwable);
    }
  }
  private static boolean isLive(String aServer) {
    try {
      URL url = new URL(aServer + "health");
      HttpURLConnection uc = (HttpURLConnection) url.openConnection();

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(BUNDLE.get("TC_STATUS_CHECK"), url);
      }

      if (uc.getResponseCode() == 200) {
        Document xml = new Builder().build(uc.getInputStream());
        Element response = (Element) xml.getRootElement();
        Element health = response.getFirstChildElement("health");
        String status = health.getValue();

        if (status.equals("dying") || status.equals("sick")) {
          if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(BUNDLE.get("TC_SERVER_STATUS"), status);
          }

          return true;
        } else if (status.equals("ok")) {
          return true;
        } else {
          LOGGER.error(BUNDLE.get("TC_UNEXPECTED_STATUS"), status);
        }
      }
    } catch (UnknownHostException details) {
      LOGGER.error(BUNDLE.get("TC_UNKNOWN_HOST"), details.getMessage());
    } catch (Exception details) {
      LOGGER.error(details.getMessage());
    }

    return false;
  }
  public MdsRestFacade getRestFacade(String entityName, String moduleName, String namespace) {
    String restId = ClassName.restId(entityName, moduleName, namespace);

    MdsRestFacade restFacade = null;
    try {
      String filter = String.format("(org.eclipse.gemini.blueprint.bean.name=%s)", restId);
      Collection<ServiceReference<MdsRestFacade>> refs =
          bundleContext.getServiceReferences(MdsRestFacade.class, filter);

      if (refs != null && refs.size() > 1 && LOGGER.isWarnEnabled()) {
        LOGGER.warn(
            "More then one Rest Facade matching for entityName={}, module={}, namespace={}. "
                + "Using first one available.",
            entityName,
            moduleName,
            namespace);
      }

      if (refs != null && refs.size() > 0) {
        ServiceReference<MdsRestFacade> ref = refs.iterator().next();
        restFacade = bundleContext.getService(ref);
      }
    } catch (InvalidSyntaxException e) {
      throw new IllegalArgumentException("Invalid Syntax for Rest Facade retrieval", e);
    }

    if (restFacade == null) {
      throw new RestNotSupportedException(entityName, moduleName, namespace);
    }

    return restFacade;
  }
  protected void propertyConcurrentModificationCheck(
      AuditConfiguration auditConfiguration,
      Session session,
      AuditEvent e,
      Long loadAuditTransactionId,
      AuditObject auditObject) {
    List<AuditTypeField> fieldsToCheck = new ArrayList<AuditTypeField>();
    for (AuditObjectProperty auditObjectProperty : auditObject.getAuditObjectProperties()) {
      fieldsToCheck.add(auditObjectProperty.getAuditField());
    }

    if (fieldsToCheck.isEmpty()) {
      // there are no fields that we are going to modify - this means that the event is a delete
      // event for the whole object - include all properties
      fieldsToCheck.addAll(auditObject.getAuditType().getAuditFields());
    }

    List<AuditTypeField> modifiedAuditTypeFields =
        getModifiedAuditTypeFields(session, e, loadAuditTransactionId, fieldsToCheck);
    Iterator<AuditTypeField> modifiedAuditTypeFieldsIterator = modifiedAuditTypeFields.iterator();

    if (modifiedAuditTypeFieldsIterator.hasNext()) {
      AuditTypeField firstDetectedmodifiedAuditTypeField = modifiedAuditTypeFieldsIterator.next();

      if (ConcurrentModificationBehavior.THROW_EXCEPTION.equals(
          auditConfiguration
              .getExtensionManager()
              .getConcurrentModificationProvider()
              .getCheckBehavior())) {
        if (session.getTransaction().isActive()) {
          session.getTransaction().rollback();
        }
        throw new PropertyConcurrentModificationException(
            firstDetectedmodifiedAuditTypeField.getOwnerType().getClassName(),
            firstDetectedmodifiedAuditTypeField.getName(),
            firstDetectedmodifiedAuditTypeField.getOwnerType().getLabel(),
            firstDetectedmodifiedAuditTypeField.getLabel(),
            e.getEntityId());
      } else if (ConcurrentModificationBehavior.LOG.equals(
          auditConfiguration
              .getExtensionManager()
              .getConcurrentModificationProvider()
              .getCheckBehavior())) {
        if (log.isWarnEnabled()) {
          log.warn(
              "Concurrent modification detected: className="
                  + firstDetectedmodifiedAuditTypeField.getOwnerType().getClassName()
                  + ",field name="
                  + firstDetectedmodifiedAuditTypeField.getName()
                  + ",class label="
                  + firstDetectedmodifiedAuditTypeField.getOwnerType().getLabel()
                  + ",field label="
                  + firstDetectedmodifiedAuditTypeField.getLabel()
                  + ",entity id="
                  + e.getEntityId());
        }
      }
    }
  }
 private void resetConnection() {
   _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_EXCEPTION);
   if (log.isWarnEnabled())
     log.warn(this.getName() + " - Closing RabbitMQ connection and channel due to exception.");
   RabbitMQUtil.close(_Connection, _Channel);
   _Connection = null;
   _Channel = null;
 }
Example #24
0
  @Override
  public void warn(Throwable t, String format, Object... args) {
    if (logger.isWarnEnabled()) {
      String message = formatMessage(format, args);

      logger.warn(message, t);
    }
  }
  protected void entityConcurrentModificationCheck(
      AuditConfiguration auditConfiguration,
      Session session,
      Long loadAuditTransactionId,
      AuditObject auditObject) {
    AuditType auditType = null;
    String targetEntityId = null;

    if (auditObject instanceof EntityAuditObject) {
      // only check the entities - the components are
      // going to be check on field level check
      EntityAuditObject entityAuditObject = (EntityAuditObject) auditObject;
      auditType = entityAuditObject.getAuditType();
      targetEntityId = entityAuditObject.getTargetEntityId();
    } else {
      ComponentAuditObject component = (ComponentAuditObject) auditObject;
      AuditObject entity = component.getParentAuditObject();

      while (entity != null && entity instanceof ComponentAuditObject) {
        entity = ((ComponentAuditObject) entity).getParentAuditObject();
      }

      auditType = component.getAuditType();
      targetEntityId = ((EntityAuditObject) entity).getTargetEntityId();
    }

    Long latestEntityTransactionId =
        HibernateAudit.getLatestAuditTransactionIdByEntityAndAfterAuditTransactionId(
            session, auditType, targetEntityId, loadAuditTransactionId);
    if (latestEntityTransactionId != null
        && !latestEntityTransactionId.equals(loadAuditTransactionId)) {
      if (ConcurrentModificationBehavior.THROW_EXCEPTION.equals(
          auditConfiguration
              .getExtensionManager()
              .getConcurrentModificationProvider()
              .getCheckBehavior())) {
        if (session.getTransaction().isActive()) {
          session.getTransaction().rollback();
        }
        throw new ObjectConcurrentModificationException(
            auditType.getClassName(), auditType.getLabel(), targetEntityId);
      } else if (ConcurrentModificationBehavior.LOG.equals(
          auditConfiguration
              .getExtensionManager()
              .getConcurrentModificationProvider()
              .getCheckBehavior())) {
        if (log.isWarnEnabled()) {
          log.warn(
              "Concurrent modification detected: className="
                  + auditType.getClassName()
                  + ",label="
                  + auditType.getLabel()
                  + ",targetEntityId="
                  + targetEntityId);
        }
      }
    }
  }
  /**
   * See Interface for functional description.
   *
   * @see UserAccountDaoInterface #retrieveGrants(java.lang.String, int, int,
   *     UserGroupHandlerInterface)
   */
  @Override
  public List<RoleGrant> retrieveGrants(
      final String criterias,
      final int offset,
      final int maxResults,
      final UserGroupHandlerInterface userGroupHandler)
      throws InvalidSearchQueryException, SystemException {
    final List<RoleGrant> result;

    if (criterias != null && criterias.length() > 0) {
      final RoleGrantFilter filter = new RoleGrantFilter(criterias);
      final Set<String> userIds = filter.getUserIds();
      final Set<String> groupIds = filter.getGroupIds();

      // check if userId and groupId was provided
      if (userIds != null && !userIds.isEmpty() && groupIds != null && !groupIds.isEmpty()) {
        throw new InvalidSearchQueryException(
            "you may not provide a userId and a groupId at the same " + "time");
      }

      // if userIds or groupIds are provided,
      // get all groups the given users/groups belong to
      if (userIds != null && !userIds.isEmpty()) {
        for (final String userId : userIds) {
          try {
            groupIds.addAll(userGroupHandler.retrieveGroupsForUser(userId));
          } catch (final UserAccountNotFoundException e) {
            // Dont do anything because null-query is given
            if (LOGGER.isWarnEnabled()) {
              LOGGER.warn("Error on retrieving groups for user.");
            }
            if (LOGGER.isDebugEnabled()) {
              LOGGER.debug("Error on retrieving groups for user.", e);
            }
          }
        }
        filter.setGroupIds(groupIds);

      } else if (groupIds != null && !groupIds.isEmpty()) {
        for (final String groupId : groupIds) {
          groupIds.addAll(userGroupHandler.retrieveGroupsForGroup(groupId));
        }
        filter.setGroupIds(groupIds);
      }
      result = getHibernateTemplate().findByCriteria(filter.toSql(), offset, maxResults);
    } else {
      try {
        final DetachedCriteria detachedCriteria =
            DetachedCriteria.forClass(RoleGrant.class, "roleGrant");

        result = getHibernateTemplate().findByCriteria(detachedCriteria, offset, maxResults);
      } catch (final DataAccessException e) {
        throw new SqlDatabaseSystemException(e);
      }
    }
    return result;
  }
Example #27
0
 /**
  * Run this task through transactions until it succeeds without an optimistic concurrency failure.
  */
 public static void repeatInTransaction(Transactable t) {
   while (true) {
     try {
       runInTransaction(t);
       break;
     } catch (ConcurrentModificationException ex) {
       if (log.isWarnEnabled()) log.warn("Optimistic concurrency failure for " + t + ": " + ex);
     }
   }
 }
  public byte[] modify(
      ClassLoader classLoader,
      String javassistClassName,
      ProtectionDomain protectedDomain,
      byte[] classFileBuffer) {
    if (logger.isInfoEnabled()) {
      logger.info("Modifying. {}", javassistClassName);
    }

    try {
      InstrumentClass statementClass =
          byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer);

      Interceptor interceptor = new StatementExecuteQueryInterceptor();
      statementClass.addGroupInterceptor(
          "executeQuery", new String[] {"java.lang.String"}, interceptor, MYSQLScope.SCOPE_NAME);

      // FIXME
      Interceptor executeUpdateInterceptor1 = new StatementExecuteUpdateInterceptor();
      statementClass.addGroupInterceptor(
          "executeUpdate",
          new String[] {"java.lang.String"},
          executeUpdateInterceptor1,
          MYSQLScope.SCOPE_NAME);

      Interceptor executeUpdateInterceptor2 = new StatementExecuteUpdateInterceptor();
      statementClass.addGroupInterceptor(
          "executeUpdate",
          new String[] {"java.lang.String", "int"},
          executeUpdateInterceptor2,
          MYSQLScope.SCOPE_NAME);

      Interceptor executeUpdateInterceptor3 = new StatementExecuteUpdateInterceptor();
      statementClass.addGroupInterceptor(
          "execute",
          new String[] {"java.lang.String"},
          executeUpdateInterceptor3,
          MYSQLScope.SCOPE_NAME);

      Interceptor executeUpdateInterceptor4 = new StatementExecuteUpdateInterceptor();
      statementClass.addGroupInterceptor(
          "execute",
          new String[] {"java.lang.String", "int"},
          executeUpdateInterceptor4,
          MYSQLScope.SCOPE_NAME);

      statementClass.addTraceValue(DatabaseInfoTraceValue.class);
      return statementClass.toBytecode();
    } catch (InstrumentException e) {
      if (logger.isWarnEnabled()) {
        logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e);
      }
      return null;
    }
  }
Example #29
0
 private void sendEvent(String sessionId, OutputWampEventMessage msg)
     throws SerializationException {
   WampConnection con = getConnection(sessionId);
   if (con != null)
     try {
       con.sendMessage(msg);
     } catch (IOException e) {
       if (log.isErrorEnabled()) log.error("Unable to send event message : " + e.getMessage());
     }
   else if (log.isWarnEnabled()) log.warn("Unable to find connection : " + sessionId);
 }
  public Iterable<Resource> extractResources(String sourceUrl, String html) {

    Set<Resource> resources = Sets.newHashSet();
    String prefixForInternalLinks = URLHandler.createPrefixForInternalLinks(sourceUrl);

    List<Element> elements = new ArrayList<Element>();

    Document doc = Jsoup.parse(html);
    Elements scripts = doc.select("script");

    elements.addAll(doc.select("iframe[src]"));
    elements.addAll(doc.select("link[href]"));
    elements.addAll(doc.select("img[src]"));
    elements.addAll(scripts);

    String uri;

    for (Element element : elements) {
      uri = element.attr("src").trim();
      if (!uri.contains(".")) {
        uri = element.attr("href").trim();
      }

      if (uri.contains(".")) {
        uri = URLHandler.expandIfInternalLink(prefixForInternalLinks, uri);
        try {
          uri = URLHandler.extractHost(uri);
          resources.add(new Resource(uri, type(element.tag().toString())));
        } catch (MalformedURLException e) {
          if (LOG.isWarnEnabled()) {
            LOG.warn("Malformed URL: \"" + uri + "\"");
          }
        }
      }
    }

    List<String> javaScriptUrlCandidates = new ArrayList<String>();
    for (Element script : scripts) {
      try {
        String scriptContents = script.data();
        if (scriptContents.length() > 1) {
          ParserRunner.ParseResult parseResult = javascriptParser.parse(scriptContents);
          findUrlCandidates(parseResult.ast, javaScriptUrlCandidates);
        }
      } catch (Exception e) {
      }
    }

    List<String> splittedUrlCandidates = findUrlsInCode(javaScriptUrlCandidates);

    resources.addAll(resourcesFromCandidates(splittedUrlCandidates));

    return resources;
  }