@Override
  public void upgrade(
      ServerHttpRequest request,
      ServerHttpResponse response,
      String protocol,
      WebSocketHandler wsHandler,
      Map<String, Object> attrs)
      throws IOException {

    Assert.isInstanceOf(ServletServerHttpRequest.class, request);
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

    Assert.isInstanceOf(ServletServerHttpResponse.class, response);
    HttpServletResponse servletResponse =
        ((ServletServerHttpResponse) response).getServletResponse();

    if (!this.factory.isUpgradeRequest(servletRequest, servletResponse)) {
      // should never happen
      throw new HandshakeFailureException("Not a WebSocket request");
    }

    JettyWebSocketSession wsSession = new JettyWebSocketSession(request.getPrincipal(), attrs);
    JettyWebSocketHandlerAdapter wsListener =
        new JettyWebSocketHandlerAdapter(wsHandler, wsSession);

    servletRequest.setAttribute(WEBSOCKET_LISTENER_ATTR_NAME, wsListener);

    if (!this.factory.acceptWebSocket(servletRequest, servletResponse)) {
      // should not happen
      throw new HandshakeFailureException("WebSocket request not accepted by Jetty");
    }
  }
 @Override
 protected void doInit() {
   Assert.state(
       exchangeNameExpression == null || exchangeName == null,
       "Either an exchangeName or an exchangeNameExpression can be provided, but not both");
   BeanFactory beanFactory = this.getBeanFactory();
   if (this.exchangeNameExpression != null) {
     this.exchangeNameGenerator =
         new ExpressionEvaluatingMessageProcessor<String>(
             this.exchangeNameExpression, String.class);
     if (beanFactory != null) {
       this.exchangeNameGenerator.setBeanFactory(beanFactory);
     }
   }
   Assert.state(
       routingKeyExpression == null || routingKey == null,
       "Either a routingKey or a routingKeyExpression can be provided, but not both");
   if (this.routingKeyExpression != null) {
     this.routingKeyGenerator =
         new ExpressionEvaluatingMessageProcessor<String>(this.routingKeyExpression, String.class);
     if (beanFactory != null) {
       this.routingKeyGenerator.setBeanFactory(beanFactory);
     }
   }
   if (this.confirmCorrelationExpression != null) {
     this.correlationDataGenerator =
         new ExpressionEvaluatingMessageProcessor<Object>(
             this.confirmCorrelationExpression, Object.class);
     Assert.isInstanceOf(
         RabbitTemplate.class,
         this.amqpTemplate,
         "RabbitTemplate implementation is required for publisher confirms");
     ((RabbitTemplate) this.amqpTemplate).setConfirmCallback(this);
     if (beanFactory != null) {
       this.correlationDataGenerator.setBeanFactory(beanFactory);
     }
   } else {
     NullChannel nullChannel = extractTypeIfPossible(this.confirmAckChannel, NullChannel.class);
     Assert.state(
         this.confirmAckChannel == null || nullChannel != null,
         "A 'confirmCorrelationExpression' is required when specifying a 'confirmAckChannel'");
     nullChannel = extractTypeIfPossible(this.confirmNackChannel, NullChannel.class);
     Assert.state(
         this.confirmNackChannel == null || nullChannel != null,
         "A 'confirmCorrelationExpression' is required when specifying a 'confirmNackChannel'");
   }
   if (this.returnChannel != null) {
     Assert.isInstanceOf(
         RabbitTemplate.class,
         this.amqpTemplate,
         "RabbitTemplate implementation is required for publisher confirms");
     ((RabbitTemplate) this.amqpTemplate).setReturnCallback(this);
   }
 }
  @Override
  public void bindRequestor(
      String name, MessageChannel requests, MessageChannel replies, Properties properties) {
    if (logger.isInfoEnabled()) {
      logger.info("binding requestor: " + name);
    }
    validateProducerProperties(name, properties, SUPPORTED_REQUESTING_PRODUCER_PROPERTIES);
    Assert.isInstanceOf(SubscribableChannel.class, requests);
    RabbitPropertiesAccessor accessor = new RabbitPropertiesAccessor(properties);
    String queueName = applyRequests(name);
    AmqpOutboundEndpoint queue =
        this.buildOutboundEndpoint(queueName, accessor, this.rabbitTemplate);
    queue.setBeanFactory(this.getBeanFactory());

    String replyQueueName =
        accessor.getPrefix(this.defaultPrefix)
            + name
            + ".replies."
            + this.getIdGenerator().generateId();
    this.doRegisterProducer(name, requests, queue, replyQueueName, accessor);
    Queue replyQueue = new Queue(replyQueueName, false, false, true); // auto-delete
    declareQueueIfNotPresent(replyQueue);
    // register with context so it will be redeclared after a connection failure
    if (!this.autoDeclareContext.containsBean(replyQueueName)) {
      this.autoDeclareContext.getBeanFactory().registerSingleton(replyQueueName, replyQueue);
    }
    this.doRegisterConsumer(name, replies, replyQueue, accessor, false);
  }
示例#4
0
  @Test
  public void test_ml_always_return_true() {

    Assert.isInstanceOf(BeanJarImpl.class, beanJar);
    String resp = beanJar.saludaJar("eduardo");
    Assert.isTrue("Hola eduardo Saludando desde jar".equals(resp));
  }
 public WebLogicClassLoaderAdapter(ClassLoader classLoader) {
   Class wlGenericClassLoaderClass = null;
   try {
     wlGenericClassLoaderClass = classLoader.loadClass(GENERIC_CLASS_LOADER_NAME);
     this.wlPreProcessorClass = classLoader.loadClass(CLASS_PRE_PROCESSOR_NAME);
     this.addPreProcessorMethod =
         classLoader
             .getClass()
             .getMethod("addInstanceClassPreProcessor", this.wlPreProcessorClass);
     this.getClassFinderMethod = classLoader.getClass().getMethod("getClassFinder");
     this.getParentMethod = classLoader.getClass().getMethod("getParent");
     this.wlGenericClassLoaderConstructor =
         wlGenericClassLoaderClass.getConstructor(
             this.getClassFinderMethod.getReturnType(), ClassLoader.class);
   } catch (Exception ex) {
     throw new IllegalStateException(
         "Could not initialize WebLogic LoadTimeWeaver because WebLogic 10 API classes are not available",
         ex);
   }
   Assert.isInstanceOf(
       wlGenericClassLoaderClass,
       classLoader,
       "ClassLoader must be instance of [" + wlGenericClassLoaderClass.getName() + "]");
   this.classLoader = classLoader;
 }
 private boolean assertHttpClientInstance(HttpClient httpClient) {
   Assert.isInstanceOf(
       AbstractHttpClient.class,
       httpClient,
       "HttpClient has to be derivate of AbstractHttpClient in order to allow authentication.");
   return true;
 }
  @Override
  public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException {
    Assert.notNull(objectIdentity, "Object Identity required");

    if (LOG.isDebugEnabled()) {
      LOG.debug("BEGIN createAcl: objectIdentity: " + objectIdentity);
    }

    // Need to retrieve the current principal, in order to know who "owns"
    // this ACL (can be changed later on)
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    PrincipalSid sid = new PrincipalSid(auth);

    AclObjectIdentity newAoi = new AclObjectIdentity(objectIdentity);
    newAoi.setOwnerId(sid.getPrincipal());
    newAoi.setOwnerPrincipal(true);
    newAoi.setEntriesInheriting(false);

    try {
      aclRepository.saveAcl(newAoi);
    } catch (AclAlreadyExistsException e) {
      throw new AlreadyExistsException(e.getMessage(), e);
    }

    // Retrieve the ACL via superclass (ensures cache registration, proper retrieval etc)
    Acl acl = readAclById(objectIdentity);
    Assert.isInstanceOf(MutableAcl.class, acl, "MutableAcl should be been returned");

    if (LOG.isDebugEnabled()) {
      LOG.debug("END createAcl: acl: " + acl);
    }
    return (MutableAcl) acl;
  }
  @SuppressWarnings("unchecked")
  @HideFromClient
  private <T extends Resource> T getResource(String name, Class<T> resourceType) {
    Assert.notNull(name, "Name must not be null");
    Assert.notNull(resourceType, "ResourceType must not be null");

    Folder root;
    String resourceName;
    if (name.equals("/common")) {
      root = this.fileSystem.getCommonFolder();
      resourceName = "";
    } else if (name.startsWith("/common/")) {
      root = this.fileSystem.getCommonFolder();
      resourceName = name.substring("/common/".length());
    } else {
      root = this.projectManager.getCurrentProject().getRootFolder();
      resourceName = name;
    }

    if (resourceName.length() == 0) {
      Assert.isInstanceOf(resourceType, root);
      return (T) root;
    }

    return root.jail().get(resourceName, resourceType);
  }
  private Map<String, Object> discoverAndSetParameters(
      IReportRunnable report, HttpServletRequest request) throws Throwable {

    Map<String, Object> parms = new HashMap<String, Object>();
    IGetParameterDefinitionTask task = birtEngine.createGetParameterDefinitionTask(report);
    @SuppressWarnings("unchecked")
    Collection<IParameterDefnBase> params = task.getParameterDefns(true);
    for (IParameterDefnBase param : params) {
      Assert.isInstanceOf(
          IScalarParameterDefn.class,
          param,
          "the parameter must be assignable to " + IScalarParameterDefn.class.getName());
      IScalarParameterDefn scalar = (IScalarParameterDefn) param;
      if (this.reportParameters != null && this.reportParameters.get(param.getName()) != null) {
        String format = scalar.getDisplayFormat();
        // todo will this step on the Spring MVC converters?
        ReportParameterConverter converter =
            new ReportParameterConverter(format, request.getLocale());

        Object value = this.reportParameters.get(param.getName());
        parms.put(param.getName(), value);

        //                       /* converter.parse(*/  this.reportParameters.get(param.getName()),
        // scalar.getDataType()/*)*/);
      } else if (StringUtils.hasText(getParameter(request, param.getName()))) {
        parms.put(param.getName(), getParamValueObject(request, scalar));
      }
    }
    task.close();
    return parms;
  }
  /**
   * Calculates the hash of password (and salt bytes, if supplied) and returns a base64 encoded
   * concatenation of the hash and salt, prefixed with {SHA} (or {SSHA} if salt was used).
   *
   * @param rawPass the password to be encoded.
   * @param salt the salt. Must be a byte array or null.
   * @return the encoded password in the specified format
   */
  public String encodePassword(String rawPass, Object salt) {
    MessageDigest sha;

    try {
      sha = MessageDigest.getInstance("SHA");
      sha.update(rawPass.getBytes("UTF-8"));
    } catch (java.security.NoSuchAlgorithmException e) {
      throw new IllegalStateException("No SHA implementation available!");
    } catch (UnsupportedEncodingException ue) {
      throw new IllegalStateException("UTF-8 not supported!");
    }

    if (salt != null) {
      Assert.isInstanceOf(byte[].class, salt, "Salt value must be a byte array");
      sha.update((byte[]) salt);
    }

    byte[] hash = combineHashAndSalt(sha.digest(), (byte[]) salt);

    String prefix;

    if (salt == null) {
      prefix = forceLowerCasePrefix ? SHA_PREFIX_LC : SHA_PREFIX;
    } else {
      prefix = forceLowerCasePrefix ? SSHA_PREFIX_LC : SSHA_PREFIX;
    }

    return prefix + new String(Base64.encode(hash));
  }
 public void setClassLoader(ClassLoader classLoader) {
   Assert.isInstanceOf(
       GroovyClassLoader.class,
       classLoader,
       "Property [classLoader] must be an instance of GroovyClassLoader");
   this.classLoader = (GroovyClassLoader) classLoader;
 }
  private Message<?> sendAndReceive(
      String exchangeName,
      String routingKey,
      Message<?> requestMessage,
      CorrelationData correlationData) {
    Assert.isInstanceOf(
        RabbitTemplate.class,
        this.amqpTemplate,
        "RabbitTemplate implementation is required for publisher confirms");
    MessageConverter converter = ((RabbitTemplate) this.amqpTemplate).getMessageConverter();
    MessageProperties amqpMessageProperties = new MessageProperties();
    org.springframework.amqp.core.Message amqpMessage =
        converter.toMessage(requestMessage.getPayload(), amqpMessageProperties);
    this.headerMapper.fromHeadersToRequest(requestMessage.getHeaders(), amqpMessageProperties);
    checkDeliveryMode(requestMessage, amqpMessageProperties);
    org.springframework.amqp.core.Message amqpReplyMessage =
        ((RabbitTemplate) this.amqpTemplate)
            .sendAndReceive(exchangeName, routingKey, amqpMessage, correlationData);

    if (amqpReplyMessage == null) {
      return null;
    }
    Object replyObject = converter.fromMessage(amqpReplyMessage);
    AbstractIntegrationMessageBuilder<?> builder =
        (replyObject instanceof Message)
            ? this.getMessageBuilderFactory().fromMessage((Message<?>) replyObject)
            : this.getMessageBuilderFactory().withPayload(replyObject);
    Map<String, ?> headers =
        this.headerMapper.toHeadersFromReply(amqpReplyMessage.getMessageProperties());
    builder.copyHeadersIfAbsent(headers);
    return builder.build();
  }
  /**
   * {@inheritDoc}
   *
   * @see es.ieci.tecdoc.isicres.legacy.ws.manager.impl.mapper.Mapper#map(java.lang.Object)
   */
  public Object map(Object obj) {
    Assert.isInstanceOf(InteresadoVO.class, obj);
    InteresadoVO interesado = (InteresadoVO) obj;
    WSStakeholder wsStakeholder = new WSStakeholder();
    wsStakeholder.setBookId(Long.valueOf(interesado.getIdLibro()));
    wsStakeholder.setFolderId(Long.valueOf(interesado.getIdRegistro()));
    wsStakeholder.setId(Long.valueOf(interesado.getId()));
    // Puede ocurrir que un interesado no tenga dirección de notificación
    if (interesado.getDireccionNotificacion() != null) {
      wsStakeholder.setIdAddress(Long.valueOf(interesado.getDireccionNotificacion().getId()));
    }
    wsStakeholder.setIdThirdParty(Long.valueOf(interesado.getTercero().getId()));
    wsStakeholder.setName(interesado.getNombre());
    wsStakeholder.setOrd(interesado.getOrden());
    wsStakeholder.setPreferred(interesado.isPrincipal());

    // El tipo indica si es físico o jurídico
    BaseTerceroVO tercero = interesado.getTercero();
    if (tercero != null) {
      if (tercero instanceof TerceroValidadoFisicoVO) {
        wsStakeholder.setTypeStakeholder(TerceroType.FISICO_VALUE);
      } else if (tercero instanceof TerceroValidadoJuridicoVO) {
        wsStakeholder.setTypeStakeholder(TerceroType.JURIDICO_VALUE);
      }
    }
    return wsStakeholder;
  }
示例#14
0
  /**
   * Converts a given {@link Document} to an AXIOM {@link org.apache.axiom.soap.SOAPEnvelope}.
   *
   * @param document the document to be converted
   * @return the converted envelope
   * @throws IllegalArgumentException in case of errors
   * @see org.apache.rampart.util.Axis2Util.getSOAPEnvelopeFromDOMDocument(Document, boolean)
   */
  public static SOAPEnvelope toEnvelope(Document document) {
    try {
      DOMImplementation implementation = document.getImplementation();
      Assert.isInstanceOf(DOMImplementationLS.class, implementation);

      DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation;
      LSOutput output = loadSaveImplementation.createLSOutput();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      output.setByteStream(bos);

      LSSerializer serializer = loadSaveImplementation.createLSSerializer();
      serializer.write(document, output);

      ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

      XMLInputFactory inputFactory = StAXUtils.getXMLInputFactory();

      StAXSOAPModelBuilder stAXSOAPModelBuilder =
          new StAXSOAPModelBuilder(inputFactory.createXMLStreamReader(bis), null);
      SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();

      // Necessary to build a correct Axiom tree, see SWS-483
      envelope.serialize(new NullOutputStream());

      return envelope;
    } catch (Exception ex) {
      IllegalArgumentException iaex =
          new IllegalArgumentException("Error in converting Document to SOAP Envelope");
      iaex.initCause(ex);
      throw iaex;
    }
  }
示例#15
0
  public void handleReturnValue(
      Object returnValue,
      MethodParameter returnType,
      ModelAndViewContainer mavContainer,
      NativeWebRequest webRequest)
      throws Exception {

    mavContainer.setRequestHandled(true);

    if (returnValue == null) {
      return;
    }

    ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
    ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

    Assert.isInstanceOf(HttpEntity.class, returnValue);
    HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;
    if (responseEntity instanceof ResponseEntity) {
      outputMessage.setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
    }

    HttpHeaders entityHeaders = responseEntity.getHeaders();
    if (!entityHeaders.isEmpty()) {
      outputMessage.getHeaders().putAll(entityHeaders);
    }

    Object body = responseEntity.getBody();
    if (body != null) {
      writeWithMessageConverters(body, returnType, inputMessage, outputMessage);
    } else {
      // flush headers to the HttpServletResponse
      outputMessage.getBody();
    }
  }
  /** La interfaz de Spring que se implementa, define este thrown de un Runtime Exception. */
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(
        UsernamePasswordAuthenticationToken.class,
        authentication,
        "Only UsernamePasswordAuthenticationToken is supported");

    final UsernamePasswordAuthenticationToken userToken =
        (UsernamePasswordAuthenticationToken) authentication;
    String mail = userToken.getName();
    String password = (String) authentication.getCredentials();

    LOGGER.debug("Authenticating user: "******"ROLE_USER"};
      return createSuccessfulAuthentication(mail, password, null, roles);
    } else {
      if (UserStateEnum.SUSPENDED_BY_ADMIN.equals(checkCredentials.getUserStateEnum())) {
        throw new UserSuspendedException(checkCredentials.getMessage());
      } else {
        throw new BadCredentialsException(checkCredentials.getMessage());
      }
    }
  }
 private AbstractEndpoint createEndpoint(MessageHandler handler, T annotation) {
   AbstractEndpoint endpoint = null;
   String inputChannelName =
       (String) AnnotationUtils.getValue(annotation, INPUT_CHANNEL_ATTRIBUTE);
   if (StringUtils.hasText(inputChannelName)) {
     MessageChannel inputChannel;
     try {
       inputChannel = this.channelResolver.resolveDestination(inputChannelName);
     } catch (DestinationResolutionException e) {
       inputChannel = new DirectChannel();
       if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
         ConfigurableListableBeanFactory listableBeanFactory =
             (ConfigurableListableBeanFactory) this.beanFactory;
         listableBeanFactory.registerSingleton(inputChannelName, inputChannel);
         inputChannel =
             (MessageChannel) listableBeanFactory.initializeBean(inputChannel, inputChannelName);
       }
     }
     Assert.notNull(inputChannel, "failed to resolve inputChannel '" + inputChannelName + "'");
     Assert.isInstanceOf(
         SubscribableChannel.class,
         inputChannel,
         "The input channel for an Annotation-based endpoint must be a SubscribableChannel.");
     endpoint = new EventDrivenConsumer((SubscribableChannel) inputChannel, handler);
   }
   return endpoint;
 }
  private SimpleMessageGroup buildMessageGroup(Object groupId, boolean raw) {
    Assert.notNull(groupId, "'groupId' must not be null");
    Object mgm = this.doRetrieve(MESSAGE_GROUP_KEY_PREFIX + groupId);
    if (mgm != null) {
      Assert.isInstanceOf(MessageGroupMetadata.class, mgm);
      MessageGroupMetadata messageGroupMetadata = (MessageGroupMetadata) mgm;
      ArrayList<Message<?>> messages = new ArrayList<Message<?>>();

      Iterator<UUID> messageIds = messageGroupMetadata.messageIdIterator();
      while (messageIds.hasNext()) {
        if (raw) {
          messages.add(this.getRawMessage(messageIds.next()));
        } else {
          messages.add(this.getMessage(messageIds.next()));
        }
      }

      SimpleMessageGroup messageGroup =
          new SimpleMessageGroup(
              messages,
              groupId,
              messageGroupMetadata.getTimestamp(),
              messageGroupMetadata.isComplete());
      messageGroup.setLastReleasedMessageSequenceNumber(
          messageGroupMetadata.getLastReleasedMessageSequenceNumber());
      return messageGroup;
    } else {
      return new SimpleMessageGroup(groupId);
    }
  }
 private MediaType getRequestedMediaType() {
   RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
   Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
   HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();
   MediaType requestedMediaType = getMediaTypes(request);
   return requestedMediaType;
 }
 @Override
 protected void endpointInit() {
   if (getConfirmCorrelationExpression() != null) {
     Assert.isInstanceOf(
         RabbitTemplate.class,
         this.amqpTemplate,
         "RabbitTemplate implementation is required for publisher confirms");
     ((RabbitTemplate) this.amqpTemplate).setConfirmCallback(this);
   }
   if (getReturnChannel() != null) {
     Assert.isInstanceOf(
         RabbitTemplate.class,
         this.amqpTemplate,
         "RabbitTemplate implementation is required for publisher confirms");
     ((RabbitTemplate) this.amqpTemplate).setReturnCallback(this);
   }
 }
 @Override
 public void setEnvironment(Environment environment) {
   Assert.isInstanceOf(
       ConfigurableEnvironment.class,
       environment,
       "unsupported environment type. " + environment.getClass());
   this.environment = (ConfigurableEnvironment) environment;
 }
示例#22
0
 /**
  * Gets the http servlet response from the context.
  *
  * @param context the context
  * @return the http servlet response
  */
 public static HttpServletResponse getHttpServletResponse(final RequestContext context) {
   Assert.isInstanceOf(
       ServletExternalContext.class,
       context.getExternalContext(),
       "Cannot obtain HttpServletResponse from event of type: "
           + context.getExternalContext().getClass().getName());
   return (HttpServletResponse) context.getExternalContext().getNativeResponse();
 }
示例#23
0
 protected void configureSslStoreProvider(
     AbstractHttp11JsseProtocol<?> protocol, SslStoreProvider sslStoreProvider) {
   Assert.isInstanceOf(
       Http11NioProtocol.class,
       protocol,
       "SslStoreProvider can only be used with Http11NioProtocol");
   ((Http11NioProtocol) protocol).getEndpoint().setAttribute("sslStoreProvider", sslStoreProvider);
   protocol.setSslImplementationName(TomcatEmbeddedJSSEImplementation.class.getName());
 }
 /**
  * Opens and returns a connection to the given URL.
  *
  * <p>The default implementation uses the given {@linkplain #setProxy(java.net.Proxy) proxy} - if
  * any - to open a connection.
  *
  * @param url the URL to open a connection to
  * @param proxy the proxy to use, may be {@code null}
  * @return the opened connection
  * @throws IOException in case of I/O errors
  */
 protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
   // Bugs with reusing connections in Android 2.2 (Froyo) and older
   if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
     System.setProperty("http.keepAlive", "false");
   }
   URLConnection urlConnection =
       (proxy != null ? url.openConnection(proxy) : url.openConnection());
   Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
   return (HttpURLConnection) urlConnection;
 }
 private void udpateRequest(
     ServerHttpRequest request, ServerHttpResponse response, FrameFormat frameFormat) {
   Assert.notNull(request, "expected request");
   Assert.notNull(response, "expected response");
   Assert.notNull(frameFormat, "expected frameFormat");
   Assert.isInstanceOf(AsyncServerHttpRequest.class, request, "Expected AsyncServerHttpRequest");
   this.asyncRequest = (AsyncServerHttpRequest) request;
   this.response = response;
   this.frameFormat = frameFormat;
 }
示例#26
0
 public void testRESTXMLWithWrongCodingSchemeParameter() throws Exception {
   try {
     callRestfulService(
         "GetXML?query=org.LexGrid.codingSchemes.CodingScheme&org.LexGrid.codingSchemes.CodingScheme&codingSchemeName=INVALID_CODING_SCHEME");
   } catch (Exception e) {
     Assert.isInstanceOf(FileNotFoundException.class, e);
     return;
   }
   fail();
 }
 @Override
 public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
     throws BeansException {
   Assert.isInstanceOf(
       ConfigurableListableBeanFactory.class,
       registry,
       "Test Database Auto-configuration can only be "
           + "used with a ConfigurableListableBeanFactory");
   process(registry, (ConfigurableListableBeanFactory) registry);
 }
  @Override
  public Binding<MessageChannel> bindProducer(
      final String name, MessageChannel moduleOutputChannel, Properties properties) {
    Assert.isInstanceOf(SubscribableChannel.class, moduleOutputChannel);
    KafkaPropertiesAccessor producerPropertiesAccessor = new KafkaPropertiesAccessor(properties);
    validateProducerProperties(name, properties, SUPPORTED_PRODUCER_PROPERTIES);
    if (logger.isInfoEnabled()) {
      logger.info("Using kafka topic for outbound: " + name);
    }

    final String topicName = escapeTopicName(name);

    int numPartitions = producerPropertiesAccessor.getNumberOfKafkaPartitionsForProducer();

    Collection<Partition> partitions =
        ensureTopicCreated(topicName, numPartitions, defaultReplicationFactor);

    ProducerMetadata<byte[], byte[]> producerMetadata =
        new ProducerMetadata<>(
            topicName, byte[].class, byte[].class, BYTE_ARRAY_SERIALIZER, BYTE_ARRAY_SERIALIZER);
    producerMetadata.setCompressionType(
        ProducerMetadata.CompressionType.valueOf(
            producerPropertiesAccessor.getCompressionCodec(this.defaultCompressionCodec)));
    producerMetadata.setBatchBytes(producerPropertiesAccessor.getBatchSize(this.defaultBatchSize));
    Properties additionalProps = new Properties();
    additionalProps.put(
        ProducerConfig.ACKS_CONFIG,
        String.valueOf(producerPropertiesAccessor.getRequiredAcks(this.defaultRequiredAcks)));
    additionalProps.put(
        ProducerConfig.LINGER_MS_CONFIG,
        String.valueOf(producerPropertiesAccessor.getBatchTimeout(this.defaultBatchTimeout)));
    ProducerFactoryBean<byte[], byte[]> producerFB =
        new ProducerFactoryBean<>(producerMetadata, brokers, additionalProps);

    try {
      final ProducerConfiguration<byte[], byte[]> producerConfiguration =
          new ProducerConfiguration<>(producerMetadata, producerFB.getObject());

      MessageHandler handler =
          new SendingHandler(
              topicName, producerPropertiesAccessor, partitions.size(), producerConfiguration);
      EventDrivenConsumer consumer =
          new EventDrivenConsumer((SubscribableChannel) moduleOutputChannel, handler);
      consumer.setBeanFactory(this.getBeanFactory());
      consumer.setBeanName("outbound." + name);
      consumer.afterPropertiesSet();
      Binding<MessageChannel> producerBinding =
          Binding.forProducer(name, moduleOutputChannel, consumer, producerPropertiesAccessor);
      addBinding(producerBinding);
      producerBinding.start();
      return producerBinding;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * This is the main method of this class, calling authentication, authorization and user details
   * mapping.
   *
   * @param authentication object to populate
   * @return Populated authentication object
   * @throws AuthenticationException
   */
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {
    Assert.isInstanceOf(
        UsernamePasswordAuthenticationToken.class,
        authentication,
        messages.getMessage(
            "AbstractUserDetailsAuthenticationProvider.onlySupports",
            "Only UsernamePasswordAuthenticationToken is supported"));

    logger.finest("CustomLdapAuthenticationProvider: authenticate");

    final UsernamePasswordAuthenticationToken userToken =
        (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    logger.fine("Processing authentication request for user: "******"LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
      DirContextOperations userData = getAuthenticator().authenticate(authentication);

      Collection<GrantedAuthority> extraAuthorities =
          loadUserAuthorities(userData, username, password);

      Collection<String> userAuthGroups = loadUserAuthGroups(userData, username, password);

      ExtendedLdapUserDetailsImpl extendedUserDetails =
          userDetailsContextMapper.mapUserFromContext(
              userData, username, extraAuthorities, userAuthGroups);

      return createSuccessfulAuthentication(userToken, extendedUserDetails);

    } catch (PasswordPolicyException ppe) {
      // The only reason a ppolicy exception can occur during a bind is that the account is locked.
      throw new LockedException(
          messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
      if (hideUserNotFoundExceptions) {
        throw new BadCredentialsException(
            messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
      } else {
        throw notFound;
      }
    } catch (NamingException ldapAccessFailure) {
      throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure);
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see es.ieci.tecdoc.isicres.legacy.ws.manager.impl.mapper.Mapper#map(java.lang.Object)
   */
  public Object map(Object obj) {
    Assert.isInstanceOf(CiudadVO.class, obj);
    CiudadVO ciudadVO = (CiudadVO) obj;
    WSCity wsCity = new WSCity();

    wsCity.setCode(ciudadVO.getCodigo());
    wsCity.setId(Long.valueOf(ciudadVO.getId()));
    wsCity.setName(ciudadVO.getNombre());

    return wsCity;
  }