@Test
  public void testCreateQueueEndpoint() throws Exception {
    JmsEndpointComponent component = new JmsEndpointComponent();

    reset(applicationContext);
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(connectionFactory)
        .once();
    replay(applicationContext);

    Endpoint endpoint = component.createEndpoint("jms:queuename", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);

    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(), "queuename");
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().isPubSubDomain(), false);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getConnectionFactory(),
        connectionFactory);
    Assert.assertNull(((JmsEndpoint) endpoint).getEndpointConfiguration().getDestination());
    Assert.assertEquals(((JmsEndpoint) endpoint).getEndpointConfiguration().getTimeout(), 5000L);

    verify(applicationContext);
  }
  /**
   * Notifies this instance that there was a change in the value of a property of an
   * <tt>Endpoint</tt> participating in this multipoint conference.
   *
   * @param endpoint the <tt>Endpoint</tt> which is the source of the event/notification and is
   *     participating in this multipoint conference
   * @param ev a <tt>PropertyChangeEvent</tt> which specifies the source of the event/notification,
   *     the name of the property and the old and new values of that property
   */
  private void endpointPropertyChange(Endpoint endpoint, PropertyChangeEvent ev) {
    String propertyName = ev.getPropertyName();
    boolean maybeRemoveEndpoint;

    if (Endpoint.SCTP_CONNECTION_PROPERTY_NAME.equals(propertyName)) {
      // The SctpConnection of/associated with an Endpoint has changed. We
      // may want to fire initial events over that SctpConnection (as soon
      // as it is ready).
      SctpConnection oldValue = (SctpConnection) ev.getOldValue();
      SctpConnection newValue = (SctpConnection) ev.getNewValue();

      endpointSctpConnectionChanged(endpoint, oldValue, newValue);

      // The SctpConnection may have expired.
      maybeRemoveEndpoint = (newValue == null);
    } else if (Endpoint.CHANNELS_PROPERTY_NAME.equals(propertyName)) {
      // An RtpChannel may have expired.
      maybeRemoveEndpoint = true;
    } else {
      maybeRemoveEndpoint = false;
    }
    if (maybeRemoveEndpoint) {
      // It looks like there is a chance that the Endpoint may have
      // expired. Endpoints are held by this Conference via WeakReferences
      // but WeakReferences are unpredictable. We have functionality
      // though which could benefit from discovering that an Endpoint has
      // expired as quickly as possible (e.g. ConferenceSpeechActivity).
      // Consequently, try to expedite the removal of expired Endpoints.
      if (endpoint.getSctpConnection() == null && endpoint.getChannelCount(null) == 0) {
        removeEndpoint(endpoint);
      }
    }
  }
示例#3
0
  public void init(SynapseEnvironment synapseEnvironment) {
    ConfigurationContext cc =
        ((Axis2SynapseEnvironment) synapseEnvironment).getAxis2ConfigurationContext();
    if (!initialized) {
      // The check for clustering environment
      ClusteringAgent clusteringAgent = cc.getAxisConfiguration().getClusteringAgent();
      if (clusteringAgent != null && clusteringAgent.getStateManager() != null) {
        isClusteringEnabled = Boolean.TRUE;
      } else {
        isClusteringEnabled = Boolean.FALSE;
      }

      context =
          new EndpointContext(getName(), getDefinition(), isClusteringEnabled, cc, metricsMBean);
    }
    initialized = true;

    if (children != null) {
      for (Endpoint e : children) {
        e.init(synapseEnvironment);
      }
    }

    contentAware =
        definition != null
            && ((definition.getFormat() != null
                    && !definition.getFormat().equals(SynapseConstants.FORMAT_REST))
                || definition.isSecurityOn()
                || definition.isReliableMessagingOn()
                || definition.isAddressingOn()
                || definition.isUseMTOM()
                || definition.isUseSwa());
  }
  @Override
  public Endpoint createEndpoint(String endpointUri, TestContext context) {
    try {
      URI uri = new URI(endpointUri);
      String path = uri.getSchemeSpecificPart();

      if (path.startsWith("//")) {
        path = path.substring(2);
      }

      if (path.contains("?")) {
        path = path.substring(0, path.indexOf('?'));
      }

      Map<String, String> parameters = getParameters(endpointUri);
      String endpointName = null;
      if (parameters.containsKey(ENDPOINT_NAME)) {
        endpointName = parameters.remove(ENDPOINT_NAME);
      }

      Endpoint endpoint = createEndpoint(path, parameters, context);

      if (StringUtils.hasText(endpointName)) {
        endpoint.setName(endpointName);
      }

      return endpoint;
    } catch (URISyntaxException e) {
      throw new CitrusRuntimeException(
          String.format("Unable to parse endpoint uri '%s'", endpointUri), e);
    }
  }
  /**
   * Checks whether RTP packets from {@code sourceChannel} should be forwarded to {@link #channel}.
   *
   * @param sourceChannel the channel.
   * @return {@code true} iff RTP packets from {@code sourceChannel} should be forwarded to {@link
   *     #channel}.
   */
  public boolean isForwarded(Channel sourceChannel) {
    if (lastN < 0 && currentLastN < 0) {
      // If Last-N is disabled, we forward everything.
      return true;
    }

    if (sourceChannel == null) {
      logger.warn("Invalid sourceChannel: null.");
      return false;
    }

    Endpoint channelEndpoint = sourceChannel.getEndpoint();
    if (channelEndpoint == null) {
      logger.warn("sourceChannel has no endpoint.");
      return false;
    }

    if (forwardedEndpoints == INITIAL_EMPTY_LIST) {
      // LastN is enabled, but we haven't yet initialized the list of
      // endpoints in the conference.
      initializeConferenceEndpoints();
    }

    // This may look like a place to optimize, because we query an unordered
    // list (in O(n)) and it executes on each video packet if lastN is
    // enabled. However, the size of  forwardedEndpoints is restricted to
    // lastN and so small enough that it is not worth optimizing.
    return forwardedEndpoints.contains(channelEndpoint.getID());
  }
  /**
   * Gets an <tt>Endpoint</tt> participating in this <tt>Conference</tt> which has a specific
   * identifier/ID. If an <tt>Endpoint</tt> participating in this <tt>Conference</tt> with the
   * specified <tt>id</tt> does not exist at the time the method is invoked, the method optionally
   * initializes a new <tt>Endpoint</tt> instance with the specified <tt>id</tt> and adds it to the
   * list of <tt>Endpoint</tt>s participating in this <tt>Conference</tt>.
   *
   * @param id the identifier/ID of the <tt>Endpoint</tt> which is to be returned
   * @return an <tt>Endpoint</tt> participating in this <tt>Conference</tt> which has the specified
   *     <tt>id</tt> or <tt>null</tt> if there is no such <tt>Endpoint</tt> and <tt>create</tt>
   *     equals <tt>false</tt>
   */
  private Endpoint getEndpoint(String id, boolean create) {
    Endpoint endpoint = null;
    boolean changed = false;

    synchronized (endpoints) {
      for (Iterator<WeakReference<Endpoint>> i = endpoints.iterator(); i.hasNext(); ) {
        Endpoint e = i.next().get();

        if (e == null) {
          i.remove();
          changed = true;
        } else if (e.getID().equals(id)) {
          endpoint = e;
        }
      }

      if (create && endpoint == null) {
        endpoint = new Endpoint(id, this);
        // The propertyChangeListener will weakly reference this
        // Conference and will unregister itself from the endpoint
        // sooner or later.
        endpoint.addPropertyChangeListener(propertyChangeListener);
        endpoints.add(new WeakReference<>(endpoint));
        changed = true;

        EventAdmin eventAdmin = videobridge.getEventAdmin();
        if (eventAdmin != null) eventAdmin.sendEvent(EventFactory.endpointCreated(endpoint));
      }
    }

    if (changed) firePropertyChange(ENDPOINTS_PROPERTY_NAME, null, null);

    return endpoint;
  }
  public Endpoint unmarshall(StaxUnmarshallerContext context) throws Exception {
    Endpoint endpoint = new Endpoint();
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) targetDepth += 2;

    while (true) {
      XMLEvent xmlEvent = context.nextEvent();
      if (xmlEvent.isEndDocument()) return endpoint;

      if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
        if (context.testExpression("Address", targetDepth)) {
          endpoint.setAddress(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }
        if (context.testExpression("Port", targetDepth)) {
          endpoint.setPort(IntegerStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }
      } else if (xmlEvent.isEndElement()) {
        if (context.getCurrentDepth() < originalDepth) {
          return endpoint;
        }
      }
    }
  }
  @Test
  public void testResolveJmsEndpoint() throws Exception {
    reset(applicationContext);

    expect(applicationContext.getBeansOfType(EndpointComponent.class))
        .andReturn(Collections.<String, EndpointComponent>emptyMap())
        .once();
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(EasyMock.createMock(ConnectionFactory.class))
        .once();

    replay(applicationContext);

    TestContext context = new TestContext();
    context.setApplicationContext(applicationContext);

    DefaultEndpointFactory factory = new DefaultEndpointFactory();
    Endpoint endpoint = factory.create("jms:Sample.Queue.Name", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(),
        "Sample.Queue.Name");

    verify(applicationContext);
  }
示例#9
0
  private void init(Interface intf) throws IOException {
    if (intf == null || intf.getNumEndpoints() != 2) throw new IllegalArgumentException();

    // XXX presumably this handles the "multiple devfs claims" case; check.

    intf.claim();
    this.intf = intf;

    try {
      for (int i = 0; i < intf.getNumEndpoints(); i++) {
        Endpoint ep = intf.getEndpoint(i);

        if (!"bulk".equals(ep.getType())) throw new IllegalArgumentException();
        if (ep.isInput()) in = ep.getInputStream();
        else out = ep.getOutputStream();
      }
      if (in == null || out == null) throw new IllegalArgumentException();
    } catch (IOException e) {
      try {
        close();
      } catch (Exception x) {
        intf = null;
      }
      throw e;
    } catch (RuntimeException e) {
      try {
        close();
      } catch (Exception x) {
        intf = null;
      }
      throw e;
    }
  }
示例#10
0
 public synchronized void unbind(EndOid oid, Ticket ticket) {
   List<Subscriber> subscribers = routes.get(oid);
   if (subscribers == null) {
     System.err.println("NULL Subscribers for: " + oid.toString());
     return;
   }
   for (Subscriber sub : subscribers) {
     if (sub.ticket.equals(ticket)) {
       if (sub.continuation != null) {
         sub.continuation.resume();
         sub.continuation = null;
       }
       subscribers.remove(sub);
       break;
     }
   }
   routes.put(oid, subscribers);
   if (subscribers.size() == 0) {
     Endpoint ep = registry.get(oid);
     if (ep == null) {
       System.err.println("Cannot find endpont: " + oid.toString());
       return;
     }
     ep.idle = true;
     ep.idleTime = System.currentTimeMillis();
   }
 }
示例#11
0
 private String getAnnotatedEndpoint(Object object) {
   if (object.getClass().isAnnotationPresent(Endpoint.class)) {
     Annotation annotation = object.getClass().getAnnotation(Endpoint.class);
     Endpoint endpoint = (Endpoint) annotation;
     return endpoint.target();
   }
   return null;
 }
示例#12
0
  private void sendNewEndpointNotification(Endpoint endpoint, String name) {
    Intent intent = new Intent(NEW_ENDPOINT);

    intent.putExtra(ENDPOINT_ADDRESS, endpoint.toString());
    intent.putExtra(ENDPOINT_HARDWARE, endpoint.getHardwareAsString());
    intent.putExtra(ENDPOINT_NAME, name == null ? "" : name);

    mContext.sendBroadcast(intent);
  }
 /** @return the ID of the endpoint of our channel. */
 private String getEndpointId() {
   if (endpointId == null) {
     Endpoint endpoint = channel.getEndpoint();
     if (endpoint != null) {
       endpointId = endpoint.getID();
     }
   }
   return endpointId;
 }
 /**
  * Used to send a message to a subset of endpoints in the call, primary use case being a message
  * that has originated from an endpoint (as opposed to a message originating from the bridge and
  * being sent to all endpoints in the call, for that see broadcastMessageOnDataChannels below
  *
  * @param msg
  * @param endpoints
  */
 public void sendMessageOnDataChannels(String msg, List<Endpoint> endpoints) {
   for (Endpoint endpoint : endpoints) {
     try {
       endpoint.sendMessageOnDataChannel(msg);
     } catch (IOException e) {
       logger.error("Failed to send message on data channel.", e);
     }
   }
 }
 private Endpoint getEndpoint(String name, String component) {
   Endpoint endpoint = endpointRepository.findOneByComponent(component);
   if (endpoint == null) {
     endpoint = new Endpoint();
     endpoint.setComponent(component);
     endpoint.setName(name);
     return endpointRepository.save(endpoint);
   }
   return endpoint;
 }
示例#16
0
  private void update(Presence p) {
    if (!p.type.equals("show")) return;

    Endpoint ep = registry.get(p.fromOid);
    if (ep != null) {
      if (!ep.show.equals(p.show)) ep.show = p.show;
      if (!ep.status.equals(p.status)) ep.status = p.status;
    } else {
      System.err.println("NULL Endpoint when update presence: " + p.fromOid.toString());
    }
  }
  /**
   * Generates assembler classes if the API returns more than one object.
   *
   * @param resources
   * @param templateGroup
   */
  private void generateModelClassesForInput(
      List<Resource> resources, StringTemplateGroup templateGroup) {
    List<String> generatedClasses = new ArrayList<String>();
    for (Resource resource : resources) {
      if (resource.getEndPoints() != null) {
        for (Endpoint endpoint : resource.getEndPoints()) {
          if (endpoint.getOperations() != null) {
            for (EndpointOperation operation : endpoint.getOperations()) {
              ResourceMethod method =
                  operation.generateMethod(
                      endpoint, resource, dataTypeMappingProvider, nameGenerator);
              if (method.getInputModel() != null) {
                Model model = method.getInputModel();
                if (model != null) {
                  if (!generatedClasses.contains(model.getName())) {
                    List<String> imports = new ArrayList<String>();
                    imports.addAll(this.config.getDefaultModelImports());
                    for (ModelField param : model.getFields()) {
                      param.setName(reservedWordMapper.translate(param.getName()));
                      for (String importDef :
                          param
                              .getFieldDefinition(
                                  this.getDataTypeMappingProvider(), config, nameGenerator)
                              .getImportDefinitions()) {
                        if (!imports.contains(importDef)) {
                          imports.add(importDef);
                        }
                      }
                    }
                    StringTemplate template = templateGroup.getInstanceOf(MODEL_OBJECT_TEMPLATE);

                    template.setAttribute("fields", model.getFields());
                    template.setAttribute("imports", imports);
                    template.setAttribute("extends", config.getDefaultModelBaseClass());
                    template.setAttribute(
                        "annotationPackageName", languageConfig.getAnnotationPackageName());
                    template.setAttribute("className", model.getGenratedClassName());
                    template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
                    File aFile =
                        new File(
                            languageConfig.getModelClassLocation()
                                + model.getGenratedClassName()
                                + languageConfig.getClassFileExtension());
                    writeFile(aFile, template.toString(), "Input model class");
                    generatedClasses.add(model.getName());
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  /**
   * Extracts a list of endpoint IDs from a list of {@link Endpoint}s.
   *
   * @param endpoints the list of {@link Endpoint}s.
   * @return the list of IDs of endpoints in {@code endpoints}.
   */
  private List<String> getIDs(List<Endpoint> endpoints) {
    if (endpoints != null && !endpoints.isEmpty()) {
      List<String> endpointIds = new LinkedList<>();
      for (Endpoint endpoint : endpoints) {
        endpointIds.add(endpoint.getID());
      }
      return endpointIds;
    }

    return null;
  }
 private URI toIpUri(Endpoint endpoint, URI uri) throws URISyntaxException {
   final URI endpointUri = endpoint.getUri();
   final String fullpath = endpointUri.getPath() + uri.getPath();
   return new URI(
       endpointUri.getScheme(),
       endpointUri.getUserInfo(),
       endpoint.getIp().getHostAddress(),
       endpointUri.getPort(),
       fullpath,
       uri.getQuery(),
       null);
 }
 public Endpoint modifyResourceEndpoint(Resource resource, EntityTag entityTag, Date lastModified)
     throws EndpointNotFoundException {
   checkNotNull(resource, "ResourceSnapshot cannot be null");
   checkNotNull(entityTag, "Entity tag cannot be null");
   checkNotNull(lastModified, "Last modified cannot be null");
   Endpoint endpoint = endpointRepository.endpointOfResource(resource.id());
   if (endpoint == null) {
     throw new EndpointNotFoundException(resource.id());
   }
   endpoint.modify(entityTag, lastModified);
   return endpoint;
 }
示例#21
0
  @Override
  public void run() {
    Endpoint endpoint = (Endpoint) this.parameters;

    this.log("Starting...");
    this.running = true;

    while (this.running) {
      try {
        if (this.connection == null) {
          this.parameters.setStatus(Endpoint.Status.CONNECTING);

          this.log("Attempting connection to " + endpoint.toConnectionString() + "...");
          Socket socket = new EndpointSocketFactory().createSocket(endpoint);

          if (socket != null) {
            this.log("Socket connected.");

            this.log("Attempting to start Mercury thread...");
            this.createConnection(new SocketTransport(socket));
          }
        } else {
          synchronized (this.connection) {
            try {
              this.connection.wait();
            } catch (InterruptedException e) {
            } catch (IllegalMonitorStateException e) {
            }
          }

          if (this.connection.started && !this.connection.running) {
            this.log("Connection was reset.");

            this.resetConnection();
          }
        }
      } catch (UnknownHostException e) {
        this.log(LogMessage.ERROR, "Unknown Host: " + endpoint.getHost());

        this.stopConnector();
      } catch (IOException e) {
        this.log(LogMessage.ERROR, "IO Error. Resetting connection.");

        this.resetConnection();
      } catch (KeyManagementException e) {
        this.log(LogMessage.ERROR, "Error loading key material for SSL.");

        this.stopConnector();
      }
    }

    this.log("Stopped.");
  }
  /*
   * Creates an endpoint with the wildcard adress (::0) and an ephemeral port.
   * The new endpoint gets a client message deliverer and is started.
   * To listen on specific interfaces or ports, set the default endpoint manually.
   * To distinguish different interfaces, one endpoint per interface must be added.
   */
  private synchronized void createDefaultEndpoint() {
    if (default_endpoint != null) return;

    default_endpoint = new CoAPEndpoint();

    try {
      default_endpoint.start();
      LOGGER.log(Level.INFO, "Created implicit default endpoint " + default_endpoint.getAddress());
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Could not create default endpoint", e);
    }
  }
示例#23
0
  @Test
  @RunAsClient
  public void testDate() throws Exception {
    URL wsdlURL = new URL(baseURL + "/MyService?wsdl");
    QName qname = new QName("http://date.jaxws.ws.test.jboss.org/", "MyService");
    Service service = Service.create(wsdlURL, qname);
    Endpoint port = service.getPort(Endpoint.class);

    Date date = new Date();

    Date response = port.echoDate(date);
    assertEquals(date.toString(), response.toString());
  }
示例#24
0
  /**
   *
   *
   * <pre>
   *  Alice        Proxy         Bob
   * 1  | INVITE     |            |
   *    |----------->|            |
   * 2  |            | INVITE     |
   *    |            |----------->|
   * 3  |            |        180 |
   *    |            |<-----------|
   * 4  |        180 |            |
   *    |<-----------|            |
   * 5  |            | CANCEL     |
   *    |            |----------->|
   * 6  |        408 |            |
   *    |<-----------|            |
   * 7  |            | 200/CANCEL |
   *    |            |<-----------|
   * 8  |            | 487/INVITE |
   *    |            |<-----------|
   * 9  |            | ACK        |
   *    |            |----------->|
   * 10 | ACK        |            |
   *    |----------->|            |
   * </pre>
   */
  @Test
  public void testVirtualBranch() throws Exception {
    Endpoint bob = createEndpoint("bob");
    UaRunnable callB = new UasScript.RingingCanceled(bob.getUserAgent());

    callB.start();

    SipServletRequest request = _ua.createRequest(SipMethods.INVITE, bob.getUri());
    request.setRequestURI(bob.getContact().getURI());
    Call callA = _ua.createCall(request);

    assertThat(callA.waitForResponse(), hasStatus(SipServletResponse.SC_REQUEST_TIMEOUT));
    checkForFailure();
  }
 private String generatePathForAttachment(Resource child, Resource parent)
     throws EndpointNotFoundException {
   Attachment attachment = parent.findAttachment(child.id());
   if (attachment == null) {
     return null;
   }
   Endpoint endpoint = getResourceEndpoint(parent.id());
   ResourceTemplate parentTemplate =
       this.templateManagementService.findTemplateById(parent.id().templateId());
   AttachedTemplate attachedTemplate = parentTemplate.attachedTemplate(attachment.id());
   StringBuilder builder = new StringBuilder();
   addSegment(builder, endpoint.path());
   addSegment(builder, attachedTemplate.path());
   return builder.toString();
 }
示例#26
0
  /** {@inheritDoc} */
  public void mapLocalToNtp(long ssrc, long localTime, double ntpTime) {
    SSRCDesc ssrcDesc = getSSRCDesc(ssrc);

    if (localTime != -1 && ntpTime != -1.0 && ssrcDesc.endpointId != null) {
      Endpoint endpoint = getEndpoint(ssrcDesc.endpointId);
      if (endpoint.localTime == -1 || endpoint.ntpTime == -1.0) {
        synchronized (endpoint) {
          if (endpoint.localTime == -1 || endpoint.ntpTime == -1.0) {
            endpoint.localTime = localTime;
            endpoint.ntpTime = ntpTime;
          }
        }
      }
    }
  }
示例#27
0
  /**
   * Sends a POST request with a file and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param file The file to upload
   * @param responseClass The class to deserialise the Json response to. Can be null if no response
   *     message is expected.
   * @param fields Any name-value pairs to serialise
   * @param <T> The type to deserialise the response to.
   * @return A {@link Response} containing the deserialised body, if any.
   * @throws IOException If an error occurs.
   * @see MultipartEntityBuilder
   */
  public <T> Response<T> post(
      Endpoint endpoint, File file, Class<T> responseClass, NameValuePair... fields)
      throws IOException {
    if (file == null) {
      return post(endpoint, responseClass, fields);
    } // deal with null case

    // Create the request
    HttpPost post = new HttpPost(endpoint.url());
    post.setHeaders(combineHeaders());

    // Add fields as text pairs
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    for (NameValuePair field : fields) {
      multipartEntityBuilder.addTextBody(field.getName(), field.getValue());
    }
    // Add file as binary
    FileBody bin = new FileBody(file);
    multipartEntityBuilder.addPart("file", bin);

    // Set the body
    post.setEntity(multipartEntityBuilder.build());

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(post)) {
      T body = deserialiseResponseMessage(response, responseClass);
      return new Response<>(response.getStatusLine(), body);
    }
  }
示例#28
0
  /**
   * Sends a POST request with a file and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param file The file to upload
   * @param responseClass The class to deserialise the Json response to. Can be null if no response
   *     message is expected.
   * @param <T> The type to deserialise the response to.
   * @return A {@link Response} containing the deserialised body, if any.
   * @throws IOException If an error occurs.
   * @see MultipartEntityBuilder
   */
  private <T> Response<T> post(Endpoint endpoint, File file, Class<T> responseClass)
      throws IOException {
    if (file == null) {
      return post(endpoint, responseClass);
    } // deal with null case

    // Create the request
    HttpPost post = new HttpPost(endpoint.url());
    post.setHeaders(combineHeaders());

    // Add fields as text pairs
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    // Add file as binary
    FileBody fileBody = new FileBody(file);
    multipartEntityBuilder.addPart("file", fileBody);

    // Set the body
    post.setEntity(multipartEntityBuilder.build());

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(post)) {
      if (String.class.isAssignableFrom(responseClass)) {
        String body = getResponseString(response);
        return new Response(response.getStatusLine(), body);
      } else {
        T body = deserialiseResponseMessage(response, responseClass);
        return new Response<>(response.getStatusLine(), body);
      }
    }
  }
示例#29
0
  /**
   * Sends a GET request and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param headers Any additional headers to send with this request. You can use {@link
   *     org.apache.http.HttpHeaders} constants for header names.
   * @return A {@link Path} to the downloaded content, if any.
   * @throws IOException If an error occurs.
   * @see java.nio.file.Files#probeContentType(Path)
   */
  public Response<Path> get(Endpoint endpoint, NameValuePair... headers) throws IOException {

    // Create the request
    HttpGet get = new HttpGet(endpoint.url());
    get.setHeaders(combineHeaders(headers));
    Path tempFile = null;

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(get)) {

      if (response.getStatusLine().getStatusCode() != HttpStatus.OK_200) {
        return null;
      } // If bad response return null

      // Request the content
      HttpEntity entity = response.getEntity();

      // Download the content to a temporary file
      if (entity != null) {
        tempFile = Files.createTempFile("download", "file");
        try (InputStream input = entity.getContent();
            OutputStream output = Files.newOutputStream(tempFile)) {
          IOUtils.copy(input, output);
        }
      }

      return new Response<>(response.getStatusLine(), tempFile);
    }
  }
示例#30
0
 public void testEntity() throws Exception {
   int port = PortAllocator.getFreePort();
   String address = "http://localhost:" + port + "/entity";
   Endpoint endpoint = Endpoint.create(new MyEndpoint());
   endpoint.publish(address);
   try {
     HTTPResponseInfo rInfo = sendEntity(address);
     String resp = rInfo.getResponseBody();
     if (resp.contains("x1y1")) {
       fail("Entity is getting resolved");
     }
     int code = rInfo.getResponseCode();
     assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, code);
   } finally {
     endpoint.stop();
   }
 }