@Override
 public void onPacketReceived(PacketReceived potentialArp) {
   Arp arp = ArpResolverUtils.getArpFrom(potentialArp);
   if (arp != null) {
     if (arp.getOperation() != ArpOperation.REPLY.intValue()) {
       LOG.trace("Packet is not ARP REPLY packet.");
       return;
     }
     if (LOG.isTraceEnabled()) {
       LOG.trace("ARP REPLY received - {}", ArpUtils.getArpToStringFormat(arp));
     }
     NodeKey nodeKey = potentialArp.getIngress().getValue().firstKeyOf(Node.class, NodeKey.class);
     if (nodeKey == null) {
       LOG.info("Unknown source node of ARP packet: {}", potentialArp);
       return;
     }
     Ipv4Address gatewayIpAddress = ArpUtils.bytesToIp(arp.getSenderProtocolAddress());
     MacAddress gatewayMacAddress = ArpUtils.bytesToMac(arp.getSenderHardwareAddress());
     ArpResolverMetadata candidateGatewayIp = gatewayToArpMetadataMap.get(gatewayIpAddress);
     if (candidateGatewayIp != null) {
       LOG.debug(
           "Resolved MAC for Gateway Ip {} is {}",
           gatewayIpAddress.getValue(),
           gatewayMacAddress.getValue());
       candidateGatewayIp.setGatewayMacAddress(gatewayMacAddress);
       resetFlowToRemove(gatewayIpAddress, candidateGatewayIp);
     }
   }
 }
  public static void main(String[] args) throws IOException {
    log.info("I'm starting the http server");

    NHttpServer nhs =
        Http.createServer(
            (req, resp) -> {
              log.trace("Http request incoming. Url:{}", req.getRequestLine().getUri());
              resp.addHeader("Content-Type", "text/html; charset=utf-8");
              resp.write("Hello World!<br/>");
              resp.end("request page: " + req.getRequestLine().getUri());
            });
    nhs.onSocketClose(
        (sock) -> {
          log.trace("connection close " + sock.getCloseReason());
        });
    nhs.listen(80)
        .whenComplete(
            (ok, ex) -> {
              if (ex != null) {
                log.error("Error binding to port ", ex);
              }
            });
    nhs.onError(
        ex -> {
          log.error("Socket error ", ex);
        });
    // Check server load on port 8181
    Http.createServerStatus(8181);
  }
 private synchronized void doOptions(String url)
     throws NotFoundException, java.net.ConnectException, NotAuthorizedException,
         java.net.UnknownHostException, SocketTimeoutException, IOException,
         com.ettrema.httpclient.HttpException {
   notifyStartRequest();
   String uri = url;
   log.trace("doOptions: {}", url);
   HttpOptions m = new HttpOptions(uri);
   InputStream in = null;
   try {
     int res = Utils.executeHttpWithStatus(client, m, null);
     log.trace("result code: " + res);
     if (res == 301 || res == 302) {
       return;
     }
     Utils.processResultCode(res, url);
   } catch (ConflictException ex) {
     throw new RuntimeException(ex);
   } catch (BadRequestException ex) {
     throw new RuntimeException(ex);
   } finally {
     Utils.close(in);
     notifyFinishRequest();
   }
 }
Example #4
0
  private Capacidad buscarCapacidad(int capacityCode) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getCapacidadUrl());
    get.addRequestHeader("Accept", "application/xml");
    Capacidad ret = null;
    try {
      int result = httpclient.executeMethod(get);
      if (logger.isTraceEnabled()) logger.trace("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      if (logger.isTraceEnabled()) logger.trace("Response body: " + xmlString);

      ret = importCapacidad(xmlString, capacityCode);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
Example #5
0
  @Test
  public void dgetauthorizedSchoolDatas() {
    SchoolI sc = new SchoolE();

    sc.getAuthenticationToken().setUserName("user1");
    sc.setTimezone("2");
    sc.setSchoolName("SOUTHFIELD SENIOR HIGH SCHOOL");
    /*sc.setSubRegionalOffice("12");
    sc.setSchoolName("Binghamton High School");*/

    schoolService = TestUtils.getSchoolServiceContext();
    Result r = schoolService.getSchools(sc);
    requestId = new StringBuilder((String) r.getResult());

    LOG.trace("data Request--" + requestId);

    assertNotNull(requestId);

    LOG.trace("Checking testcase for status");
    statusService = TestUtils.getStatusServiceContext();
    boolean status = getStatus(requestId.toString(), sc);

    Result res = schoolService.getSchoolsDataForMDB(sc);
    ;
    List<SchoolI> schoolsData = (List<SchoolI>) res.getResult();

    /*List<SchoolDTO> schoolsData = schoolService.getSchoolsData(requestId, sc);

    LOG.trace("Size : " + schoolsData.size());
    assertTrue("Ivalid Data", schoolsData.size() >= 1);*/
  }
  @Override
  @Interceptors({CartInterceptor.class})
  @RolesAllowed({"admin", "guest"})
  public CartModel[] getCustomerCarts(String username) throws EntityNotFoundException {
    LOG.trace("ENTER getCustomerCarts(customer)");

    try {
      final TypedQuery<CustomerModel> customerQuery =
          entityManager.createNamedQuery(CustomerEntity.QUERY_USERNAME, CustomerModel.class);
      customerQuery.setParameter("username", username);
      CustomerModel customer = customerQuery.getSingleResult();

      final TypedQuery<CartEntity> customerCartsQuery =
          entityManager.createNamedQuery(CartEntity.QUERY_SELECT_ALL_CUSTOMER, CartEntity.class);
      customerCartsQuery.setParameter("customerInfo", customer);
      final List<CartEntity> resultsList = customerCartsQuery.getResultList();

      if (LOG.isDebugEnabled()) {
        LOG.debug("Result Set Size: {}", resultsList.size());
      }

      final CartModel[] results = new CartModel[resultsList.size()];

      int counter = 0;
      for (final CartModel model : resultsList) results[counter++] = model;

      return results;
    } finally {
      LOG.trace("EXIT getCustomerCarts(customer)");
    }
  }
Example #7
0
  public Object getValueFromField(Object target, Method getter) {
    log.trace(
        "Get value with getter {} from instance {} of class {}",
        getter.getName(),
        target,
        getter.getDeclaringClass().getCanonicalName());

    Object value = null;

    if (target != null) {
      try {
        value = getter.invoke(target);
      } catch (Exception e) {
        throw new AchillesException(
            "Cannot invoke '"
                + getter.getName()
                + "' of type '"
                + getter.getDeclaringClass().getCanonicalName()
                + "' on instance '"
                + target
                + "'",
            e);
      }
    }

    log.trace("Found value : {}", value);
    return value;
  }
Example #8
0
  @Override
  public DatasetMetadata queryMetadata(String uri, String referential) throws IOException {

    DatasetMetadata md = new DatasetMetadata();

    // Coordinate system
    Dataset dataset = findDataset(uri, referential);
    if (dataset == null) {
      throw new IOException(String.format("Could not find dataset %s", uri));
    }
    log.trace("Querying spatial axes of {}", dataset);
    List<TimeSlice> tss = datasetDao.getTimeSlices(dataset.getId());

    GridProjected grid = queryGrid(dataset, tss);
    TimeAxis timeAxis = queryTimeAxis(dataset, tss);
    md.setCsys(new QueryCoordinateSystem(grid, timeAxis));

    // Variable names
    log.trace("Querying variable names of {}", dataset);
    List<String> bandNames = new ArrayList<>();
    for (Band b : datasetDao.getBands(dataset.getId())) {
      bandNames.add(b.getName());
    }
    // In the current RSA, all datasets have coordinate axes (1D variables)
    // x, y and time
    bandNames.add("time");
    bandNames.add("y");
    bandNames.add("x");
    md.setVariables(bandNames);

    return md;
  }
    @Override
    public OFMeterFeaturesStatsReply readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property version == 5
      byte version = bb.readByte();
      if (version != (byte) 0x5)
        throw new OFParseError("Wrong version: Expected=OFVersion.OF_14(5), got=" + version);
      // fixed value property type == 19
      byte type = bb.readByte();
      if (type != (byte) 0x13)
        throw new OFParseError("Wrong type: Expected=OFType.STATS_REPLY(19), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 32) throw new OFParseError("Wrong length: Expected=32(32), got=" + length);
      if (bb.readableBytes() + (bb.readerIndex() - start) < length) {
        // Buffer does not have all data yet
        bb.readerIndex(start);
        return null;
      }
      if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length);
      long xid = U32.f(bb.readInt());
      // fixed value property statsType == 11
      short statsType = bb.readShort();
      if (statsType != (short) 0xb)
        throw new OFParseError(
            "Wrong statsType: Expected=OFStatsType.METER_FEATURES(11), got=" + statsType);
      Set<OFStatsReplyFlags> flags = OFStatsReplyFlagsSerializerVer14.readFrom(bb);
      // pad: 4 bytes
      bb.skipBytes(4);
      OFMeterFeatures features = OFMeterFeaturesVer14.READER.readFrom(bb);

      OFMeterFeaturesStatsReplyVer14 meterFeaturesStatsReplyVer14 =
          new OFMeterFeaturesStatsReplyVer14(xid, flags, features);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", meterFeaturesStatsReplyVer14);
      return meterFeaturesStatsReplyVer14;
    }
  public ImmutableMap<String, Method> build() {

    final ImmutableMap.Builder<String, Method> lResultBuilder =
        new ImmutableMap.Builder<String, Method>();

    // iterate based on mMethodsOrdered to maintain
    // the order
    for (String lBeanPropName : mMethodsOrdered) {

      final NavigableSet<Method> lAllMethods = mMethodCache.getUnchecked(lBeanPropName);
      final Method lMostPreciseMethod = lAllMethods.last();

      LOGGER.trace(
          "propName [{}] selected method [{}] all methods[{}]",
          new Object[] {lBeanPropName, lMostPreciseMethod, lAllMethods});

      if (mBeanMethodFilter.accepts(lMostPreciseMethod, lBeanPropName)) {
        lResultBuilder.put(lBeanPropName, lMostPreciseMethod);
      } else {
        LOGGER.trace("rejected [{}]", lBeanPropName);
      }
    }

    return lResultBuilder.build();
  }
 private boolean isManaged(
     RepositoryConnection conn, Resource subject, URI predicate, Value object, String operation) {
   try {
     if (conn.hasStatement(subject, predicate, object, true, managedContext)) {
       // Ignore/Strip any triple that is already present in the mgmt-context (i.e. "unchanged"
       // props).
       if (log.isTraceEnabled()) {
         log.trace(
             "[{}] filtering out statement that is already present in the managed context: {}",
             operation,
             new StatementImpl(subject, predicate, object));
       }
       return true;
     } else if (this.subject.equals(subject) && managedProperties.contains(predicate)) {
       // We do NOT allow changing server-managed properties.
       if (log.isTraceEnabled()) {
         log.trace(
             "[{}] filtering out statement with managed propterty {}: {}",
             operation,
             predicate,
             new StatementImpl(subject, predicate, object));
       }
       deniedProperties.add(predicate);
       return true;
     }
   } catch (RepositoryException e) {
     log.error("Error while filtering server managed properties: {}", e.getMessage());
   }
   return false;
 }
  /** {@inheritDoc} */
  public synchronized void destroy() {

    String s = config.getInitParameter(ApplicationConfig.SHARED);
    if (s != null && s.equalsIgnoreCase("true")) {
      logger.warn(
          "Factory shared, will not be destroyed. That can possibly cause memory leaks if"
              + "Broadcaster where created. Make sure you destroy them manually.");
      return;
    }

    Enumeration<Broadcaster> e = store.elements();
    Broadcaster b;
    // We just need one when shared.
    BroadcasterConfig bc = null;
    while (e.hasMoreElements()) {
      try {
        b = e.nextElement();
        b.resumeAll();
        b.destroy();
        bc = b.getBroadcasterConfig();
      } catch (Throwable t) {
        // Shield us from any bad behaviour
        logger.trace("Destroy", t);
      }
    }

    try {
      if (bc != null) bc.forceDestroy();
    } catch (Throwable t) {
      logger.trace("Destroy", t);
    }

    store.clear();
    factory = null;
  }
 public Object intercept(Request request, ProxyChain chain) throws Throwable {
   TransactionManager tm = getTransactionManager();
   Transaction tx = tm.getTransaction();
   boolean create = (tx == null);
   if (create) {
     LOG.trace("Creating transaction");
     tm.begin();
   }
   try {
     Object ret = chain.proceed(request);
     if (create) {
       LOG.trace("Commiting transaction");
       tm.commit();
     }
     return ret;
   } catch (Exception e) {
     if (create) {
       try {
         LOG.trace("Rolling back transaction");
         tm.rollback();
       } catch (Exception e1) {
         LOG.error("Error on rollback, It will not raise", e1);
       }
     }
     throw e;
   }
 }
Example #14
0
  /**
   * Method waits until the given {@code list} has reached the given {@code targetSize} or if the
   * given {@code timeoutMillis} has passed. If the timeout has pased without the size beeing
   * reached, the method throws an Exception.
   *
   * @param list
   * @param targetSize
   * @param timeoutMillis how many millis to wait for result. If ZERO, we will wait forever
   * @throws InterruptedException
   * @throws TimeoutException if the timeout exceeded
   */
  public void waitUntilSize(final List<?> list, final int targetSize, final long timeoutMillis)
      throws InterruptedException, TimeoutException {
    Thread.sleep(
        100); // wait a bit, because the processor need not only to increase list.size(), but also
              // flag the package as "processed"

    int retryCount = 0;

    final long beginTS = SystemTime.millis();
    int lastSize = -1;
    int size = list.size();
    retryCount++;

    while (size < targetSize) {
      long currentTS = SystemTime.millis();
      if (lastSize != -1 && timeoutMillis > 0) {
        final long elapsedMillis = currentTS - beginTS;
        if (elapsedMillis >= timeoutMillis) {
          throw new TimeoutException(
              "Timeout while waiting for " + list + "to have at least " + targetSize + " items");
        }
      }

      Thread.sleep(200);

      size = list.size();
      lastSize = size;
      retryCount++;

      logger.trace("Retry " + retryCount + " => size=" + size);
    }
    logger.trace("Finished after " + retryCount + " retries => size=" + size);
    Thread.sleep(200); // without further delay, the future we wait for might still not be "done"
  }
  protected PortletWindowData getOrCreateDefaultPortletWindowData(
      HttpServletRequest request,
      IPortletEntityId portletEntityId,
      IPortletWindowId portletWindowId,
      IPortletWindowId delegationParentId) {
    // Sync on session map to make sure duplicate PortletWindowData is never created
    final PortletWindowCache<PortletWindowData> portletWindowDataMap =
        getPortletWindowDataMap(request);
    // Check if there portlet window data cached in the session
    PortletWindowData portletWindowData = portletWindowDataMap.getWindow(portletWindowId);
    if (portletWindowData != null) {
      logger.trace(
          "Found PortletWindowData {} in session cache", portletWindowData.getPortletWindowId());
      return portletWindowData;
    }

    // Create new window data for and initialize
    portletWindowData = new PortletWindowData(portletWindowId, portletEntityId, delegationParentId);
    this.initializePortletWindowData(request, portletWindowData);

    // Store in the session cache
    portletWindowData = portletWindowDataMap.storeIfAbsentWindow(portletWindowData);
    logger.trace(
        "Created PortletWindowData {} and stored session cache, wrapping as IPortletWindow and returning",
        portletWindowData.getPortletWindowId());

    return portletWindowData;
  }
  private static void decorateContentNode(
      final DocumentReader docReader, final DocumentWriter docWriter) {
    if (!docReader.getMixinTypeNames().contains(FEDORA_BINARY)) {
      LOGGER.trace("Adding mixin: {}, to {}", FEDORA_BINARY, docReader.getDocumentId());
      docWriter.addMixinType(FEDORA_BINARY);
    }

    if (null == docReader.getProperty(CONTENT_DIGEST)) {
      final BinaryValue binaryValue = getBinaryValue(docReader);
      final String dsChecksum = binaryValue.getHexHash();
      final String dsURI = asURI("SHA-1", dsChecksum).toString();

      LOGGER.trace(
          "Adding {} property of {} to {}", CONTENT_DIGEST, dsURI, docReader.getDocumentId());
      docWriter.addProperty(CONTENT_DIGEST, dsURI);
    }

    if (null == docReader.getProperty(CONTENT_SIZE)) {
      final BinaryValue binaryValue = getBinaryValue(docReader);
      final long binarySize = binaryValue.getSize();

      LOGGER.trace(
          "Adding {} property of {} to {}", CONTENT_SIZE, binarySize, docReader.getDocumentId());
      docWriter.addProperty(CONTENT_SIZE, binarySize);
    }

    LOGGER.debug("Decorated data property at path: {}", docReader.getDocumentId());
  }
Example #17
0
  // Emits one tuple per record
  // @return true if tuple was emitted
  private boolean emitTupleIfNotEmitted(ConsumerRecord<K, V> record) {
    final TopicPartition tp = new TopicPartition(record.topic(), record.partition());
    final KafkaSpoutMessageId msgId = new KafkaSpoutMessageId(record);

    if (acked.containsKey(tp) && acked.get(tp).contains(msgId)) { // has been acked
      LOG.trace("Tuple for record [{}] has already been acked. Skipping", record);
    } else if (emitted.contains(msgId)) { // has been emitted and it's pending ack or fail
      LOG.trace("Tuple for record [{}] has already been emitted. Skipping", record);
    } else {
      boolean isScheduled = retryService.isScheduled(msgId);
      if (!isScheduled
          || retryService.isReady(
              msgId)) { // not scheduled <=> never failed (i.e. never emitted) or ready to be
                        // retried
        final List<Object> tuple = tuplesBuilder.buildTuple(record);
        kafkaSpoutStreams.emit(collector, tuple, msgId);
        emitted.add(msgId);
        numUncommittedOffsets++;
        if (isScheduled) { // Was scheduled for retry, now being re-emitted. Remove from schedule.
          retryService.remove(msgId);
        }
        LOG.trace("Emitted tuple [{}] for record [{}]", tuple, record);
        return true;
      }
    }
    return false;
  }
Example #18
0
  private static Set<Method> findSetterMethods(
      Class<?> clazz, String name, Object value, boolean allowBuilderPattern) {
    Set<Method> candidates = findSetterMethods(clazz, name, allowBuilderPattern);

    if (candidates.isEmpty()) {
      return candidates;
    } else if (candidates.size() == 1) {
      // only one
      return candidates;
    } else {
      // find the best match if possible
      LOG.trace("Found {} suitable setter methods for setting {}", candidates.size(), name);
      // prefer to use the one with the same instance if any exists
      for (Method method : candidates) {
        if (method.getParameterTypes()[0].isInstance(value)) {
          LOG.trace(
              "Method {} is the best candidate as it has parameter with same instance type",
              method);
          // retain only this method in the answer
          candidates.clear();
          candidates.add(method);
          return candidates;
        }
      }
      // fallback to return what we have found as candidates so far
      return candidates;
    }
  }
  @Override
  @Interceptors({CartItemInterceptor.class})
  public CartItemModel addCartItem(String cartUid, String productCode, Integer quantity)
      throws EntityNotFoundException, ModelValidationException {
    LOG.trace("ENTER addCartItem(cartUid, productCode, price, quantity)");
    final CartItemEntity cartItemEntity = new CartItemEntity();
    try {
      // Get Cart Entity
      final TypedQuery<CartModel> cartQuery =
          entityManager.createNamedQuery(CartEntity.QUERY_UUID, CartModel.class);
      cartQuery.setParameter("uuid", UUIDUtils.getIdAsByte(UUIDUtils.fromString(cartUid)));
      final CartModel cart = cartQuery.getSingleResult();

      LOG.debug("cart = {}", cart.toString());

      // Get Product Entity
      final TypedQuery<ProductModel> productQuery =
          entityManager.createNamedQuery(ProductEntity.QUERY_PRODUCT_CODE, ProductModel.class);
      productQuery.setParameter("productCode", productCode);
      final ProductModel productInfo = productQuery.getSingleResult();

      LOG.debug("productInfo = {}", productInfo.toString());

      cartItemEntity.setCart(cart);
      cartItemEntity.setProductInfo(productInfo);
      cartItemEntity.setPrice(productInfo.getProductPrice());
      cartItemEntity.setQuantity(quantity);

      cartItemEJB.persist(cartItemEntity);
      return cartItemEntity;
    } finally {
      LOG.trace("EXIT addCartItem(cartUid, productCode, price, quantity)");
    }
  }
  @Override
  public String processForm(Map<String, String> parameters, Map<String, FileItem> files)
      throws BadRequestException, NotAuthorizedException, ConflictException {
    log.trace("process");
    try {
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      Request request = HttpManager.request();
      IOUtils.copy(request.getInputStream(), bout);
      String iCalText = bout.toString("UTF-8");
      if (log.isTraceEnabled()) {
        log.trace("Freebusy query: " + iCalText);
      }
      List<SchedulingResponseItem> respItems = queryFreeBusy(iCalText);

      String xml = schedulingHelper.generateXml(respItems);
      xmlResponse = xml.getBytes(StringUtils.UTF8);
      if (log.isTraceEnabled()) {
        log.trace("FreeBusy response= " + xml);
      }

    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
    return null;
  }
  @Override
  public void populateCamelHeaders(
      HttpResponse response,
      Map<String, Object> headers,
      Exchange exchange,
      NettyHttpConfiguration configuration)
      throws Exception {
    LOG.trace("populateCamelHeaders: {}", response);

    headers.put(Exchange.HTTP_RESPONSE_CODE, response.getStatus().getCode());
    headers.put(Exchange.HTTP_RESPONSE_TEXT, response.getStatus().getReasonPhrase());

    for (String name : response.headers().names()) {
      // mapping the content-type
      if (name.toLowerCase().equals("content-type")) {
        name = Exchange.CONTENT_TYPE;
      }
      // add the headers one by one, and use the header filter strategy
      List<String> values = response.headers().getAll(name);
      Iterator<?> it = ObjectHelper.createIterator(values);
      while (it.hasNext()) {
        Object extracted = it.next();
        LOG.trace("HTTP-header: {}", extracted);
        if (headerFilterStrategy != null
            && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
          NettyHttpHelper.appendHeader(headers, name, extracted);
        }
      }
    }
  }
Example #22
0
  /** 在访问被拒绝 */
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
      throws Exception {
    if (isLoginRequest(request, response)) {
      if (isLoginSubmission(request, response)) {
        if (log.isTraceEnabled()) {
          log.trace("Login submission detected.  Attempting to execute login.");
        }
        return executeLogin(request, response);
      } else {
        if (log.isTraceEnabled()) {
          log.trace("Login page view.");
        }
        return true;
      }
    } else {
      if (log.isTraceEnabled()) {
        log.trace(
            "Attempting to access a path which requires authentication.  Forwarding to the "
                + "Authentication url ["
                + getLoginUrl()
                + "]");
      }

      saveRequestAndRedirectToLogin(request, response);
      return false;
    }
  }
  private String urlEncodeQueryParams(String url) {
    final StringBuilder sb = new StringBuilder((int) (url.length() * 1.2));

    final int pos = url.indexOf('?');
    if (pos > 0) {
      // split url into base and query expression
      final String queryExpr = url.substring(pos + 1);
      LOG.trace("queryExpr {}", queryExpr);

      final Pattern p =
          Pattern.compile(
              "\\G([A-Za-z0-9-_]+)=([A-Za-z0-9-+:#|^\\.,<>;%*\\(\\)_/\\[\\]\\{\\}\\\\ ]+)[&]?");
      final Matcher m = p.matcher(queryExpr);
      while (m.find()) {
        LOG.trace("group 1: {}   group 2: {}", m.group(1), m.group(2));
        if (sb.length() > 0) {
          sb.append("&");
        }
        sb.append(m.group(1));
        sb.append("=");
        try {
          // URL Encode the value of each query parameter
          sb.append(URLEncoder.encode(m.group(2), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          // Ignore - We know UTF-8 is supported
        }
      }

      LOG.trace("new query Expr: {}", sb.toString());

      sb.insert(0, url.substring(0, pos + 1));
    }
    return sb.toString();
  }
    @Override
    public OFInstructionIdBsnRequireVlanXlate readFrom(ChannelBuffer bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property type == 65535
      short type = bb.readShort();
      if (type != (short) 0xffff)
        throw new OFParseError(
            "Wrong type: Expected=OFInstructionType.EXPERIMENTER(65535), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 12) throw new OFParseError("Wrong length: Expected=12(12), got=" + length);
      if (bb.readableBytes() + (bb.readerIndex() - start) < length) {
        // Buffer does not have all data yet
        bb.readerIndex(start);
        return null;
      }
      if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length);
      // fixed value property experimenter == 0x5c16c7L
      int experimenter = bb.readInt();
      if (experimenter != 0x5c16c7)
        throw new OFParseError(
            "Wrong experimenter: Expected=0x5c16c7L(0x5c16c7L), got=" + experimenter);
      // fixed value property subtype == 0x8L
      int subtype = bb.readInt();
      if (subtype != 0x8)
        throw new OFParseError("Wrong subtype: Expected=0x8L(0x8L), got=" + subtype);

      if (logger.isTraceEnabled())
        logger.trace("readFrom - returning shared instance={}", INSTANCE);
      return INSTANCE;
    }
  /**
   * checks again for the necessary file and makes sure that they exist
   *
   * @throws IOException error processing
   */
  public void execute() throws IOException {
    // get from the in record and translate
    int translated = 0;
    int passed = 0;

    for (Record r : this.inStore) {
      if (this.force || r.needsProcessed(this.getClass())) {
        log.trace("Translating Record " + r.getID());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        xmlTranslate(
            new ByteArrayInputStream(r.getData().getBytes("UTF-8")),
            baos,
            new ByteArrayInputStream(this.translationString.getBytes()));
        this.outStore.addRecord(r.getID(), baos.toString(), this.getClass());
        r.setProcessed(this.getClass());
        baos.close();
        translated++;
      } else {
        log.trace("No Translation Needed: " + r.getID());
        passed++;
      }
    }
    log.info(Integer.toString(translated) + " records translated.");
    log.info(Integer.toString(passed) + " records did not need translation");
  }
Example #26
0
  /**
   * Adjust the command to suit the environment.
   *
   * @param command The command to run.
   * @return The adjusted command.
   */
  public List<String> prepareCommand(List<String> command) {
    ApplicationContext appContext = ApplicationContextProvider.getApplicationContext();
    NdgConfigManager ndgConfigManager = (NdgConfigManager) appContext.getBean("ndgConfigManager");

    String loc = ndgConfigManager.getConfig().getGdalLocation();
    if (loc == null) throw new IllegalStateException("GDAL location is not configured.");

    Path gdalBinDir = Paths.get(loc, "bin");
    Path gdalCmdPath = gdalBinDir.resolve(command.get(0));

    // Patch in path to GDAL, if appropriate.
    ArrayList<String> cmd = new ArrayList<String>();
    cmd.add(gdalCmdPath.toString());

    log.trace("cma [0] = {}", command.get(0));

    // Remove windows-style backslashes.
    for (int i = 1; i < command.size(); ++i) {
      log.trace("cma [{}] = {}", i, command.get(i));
      String s = command.get(i).replace('\\', '/');
      cmd.add(s);
    }

    String commandStr = StringUtils.join(cmd, " ");
    log.debug("Attempting to run: " + commandStr);

    return cmd;
  }
  @VisibleForTesting
  static StripCapabilitiesResult stripCapabilities(
      XmlElement configElement, Set<String> allCapabilitiesFromHello) {
    // collect all namespaces
    Set<String> foundNamespacesInXML = getNamespaces(configElement);
    LOG.trace(
        "All capabilities {}\nFound namespaces in XML {}",
        allCapabilitiesFromHello,
        foundNamespacesInXML);
    // required are referenced both in xml and hello
    SortedSet<String> requiredCapabilities = new TreeSet<>();
    // can be removed
    SortedSet<String> obsoleteCapabilities = new TreeSet<>();
    for (String capability : allCapabilitiesFromHello) {
      String namespace = capability.replaceAll("\\?.*", "");
      if (foundNamespacesInXML.contains(namespace)) {
        requiredCapabilities.add(capability);
      } else {
        obsoleteCapabilities.add(capability);
      }
    }

    LOG.trace(
        "Required capabilities {}, \nObsolete capabilities {}",
        requiredCapabilities,
        obsoleteCapabilities);

    return new StripCapabilitiesResult(requiredCapabilities, obsoleteCapabilities);
  }
  /**
   * Method description
   *
   * @param manager
   * @return
   * @throws IOException
   * @throws RepositoryException
   */
  @Override
  public List<String> importRepositories(RepositoryManager manager)
      throws IOException, RepositoryException {
    List<String> imported = new ArrayList<String>();

    if (logger.isTraceEnabled()) {
      logger.trace("search for repositories to import");
    }

    List<String> repositoryNames =
        RepositoryUtil.getRepositoryNames(getRepositoryHandler(), getDirectoryNames());

    for (String repositoryName : repositoryNames) {
      if (logger.isTraceEnabled()) {
        logger.trace("check repository {} for import", repositoryName);
      }

      Repository repository = manager.get(getTypeName(), repositoryName);

      if (repository == null) {
        importRepository(manager, repositoryName);
        imported.add(repositoryName);
      } else if (logger.isDebugEnabled()) {
        logger.debug("repository {} is allready managed", repositoryName);
      }
    }

    return imported;
  }
  public <RESPONSE extends ReaderResponse<?>> RESPONSE transmit(ReaderCommand<?, ?> readerCommand)
      throws Exception {

    Log.trace("Sending command: " + readerCommand.toString());

    // ACR122
    byte[] header = {(byte) 0xff, (byte) 0x00, (byte) 0x00, (byte) 0x00};
    out.put(header);
    out.put((byte) readerCommand.getLength());
    readerCommand.transfer(out);

    try {
      out.flip();
      CommandAPDU apdu = new CommandAPDU(out);
      ResponseAPDU resp = channel.transmit(apdu);
      out.clear();
      ByteBuffer in = ByteBuffer.wrap(resp.getBytes());
      // check response !!!

      RESPONSE response = (RESPONSE) readerCommand.receive(in);
      Log.trace("Receiving command: " + response.toString());
      return response;
    } catch (CardException e) {
      e.printStackTrace();
      throw new Exception(e.getMessage());
    }
  }
Example #30
0
  @Override
  public void removeSubscription(UpnpIOParticipant participant, String serviceID) {
    if (participant != null && serviceID != null) {
      Device device = participants.get(participant);

      if (device != null) {
        Service subService = searchSubService(serviceID, device);
        if (subService != null) {
          logger.trace(
              "Removing an UPNP service subscription '{}' for particpant '{}'",
              serviceID,
              participant.getUDN());

          UpnpSubscriptionCallback callback = subscriptionCallbacks.get(subService);
          if (callback != null) {
            callback.end();
          }
          subscriptionCallbacks.remove(subService);
        } else {
          logger.trace(
              "Could not find service '{}' for device '{}'",
              serviceID,
              device.getIdentity().getUdn());
        }
      } else {
        logger.trace("Could not find an upnp device for participant '{}'", participant.getUDN());
      }
    }
  }