Ejemplo n.º 1
0
  /**
   * Invoke API by sending HTTP request with the given options.
   *
   * @param path The sub-path of the HTTP URL
   * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
   * @param queryParams The query parameters
   * @param body The request body object - if it is not binary, otherwise null
   * @param binaryBody The request body object - if it is binary, otherwise null
   * @param headerParams The header parameters
   * @param formParams The form parameters
   * @param accept The request's Accept header
   * @param contentType The request's Content-Type header
   * @param authNames The authentications to apply
   * @return The response body in type of string
   */
  public <T> T invokeAPI(
      String path,
      String method,
      List<Pair> queryParams,
      Object body,
      byte[] binaryBody,
      Map<String, String> headerParams,
      Map<String, Object> formParams,
      String accept,
      String contentType,
      String[] authNames,
      TypeRef returnType)
      throws ApiException {

    Response response =
        getAPIResponse(
            path,
            method,
            queryParams,
            body,
            binaryBody,
            headerParams,
            formParams,
            accept,
            contentType,
            authNames);

    statusCode = response.getStatusInfo().getStatusCode();
    responseHeaders = response.getHeaders();

    if (statusCode == 401) {
      throw new ApiException(
          response.getStatusInfo().getStatusCode(),
          "HTTP Error 401 - Unauthorized: Access is denied due to invalid credentials.",
          response.getHeaders(),
          null);
    } else if (response.getStatusInfo() == Response.Status.NO_CONTENT) {
      return null;
    } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      if (returnType == null) return null;
      else return deserialize(response, returnType);
    } else {
      String message = "error";
      String respBody = null;
      if (response.hasEntity()) {
        try {
          respBody = response.readEntity(String.class);
          message = respBody;
        } catch (RuntimeException e) {
          // e.printStackTrace();
        }
      }
      throw new ApiException(
          response.getStatusInfo().getStatusCode(), message, response.getHeaders(), respBody);
    }
  }
Ejemplo n.º 2
0
  /**
   * Test checks that a GET on the resource "/form/colours" with mime-type "text/html" shows the
   * appropriate colours based on the query param "match".
   */
  @Test
  public void testGetColoursAsPlainText() {
    // without the query param "match"
    Response response = target().path("form").path("colours").request(MediaType.TEXT_PLAIN).get();
    assertEquals(
        "GET on path '/form/colours' with mime type 'text/html' doesn't give expected response",
        Response.Status.OK,
        response.getStatusInfo());

    String responseMsg =
        target().path("form").path("colours").request(MediaType.TEXT_PLAIN).get(String.class);
    assertEquals(
        "Response content doesn't match the expected value",
        "red\norange\nyellow\ngreen\nblue\nindigo\nviolet\n",
        responseMsg);

    // with the query param "match" value "re"
    responseMsg =
        target("form/colours")
            .queryParam("match", "re")
            .request(MediaType.TEXT_PLAIN)
            .get(String.class);
    assertEquals(
        "Response content doesn't match the expected value with the query param 'match=re'",
        "red\ngreen\n",
        responseMsg);
  }
Ejemplo n.º 3
0
    private ToStateTransitions load(
        LoginData loginData, ProjectGroupConfig boardConfig, Issue issue, String toState)
        throws IOException {
      final UriBuilder builder =
          UriBuilder.fromUri(boardConfig.getJiraUrl())
              .path("rest")
              .path("api")
              .path("2")
              .path("issue")
              .path(issue.getKey())
              .path("transitions")
              .queryParam("issueIdOrKey", issue.getKey());
      final WebTarget target = loginData.getClient().target(builder);
      final Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get();

      if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
        throw new IOException(
            "Error looking up the transitions for issue "
                + issue.getKey()
                + ": "
                + response.readEntity(String.class));
      }
      Map<String, Transition> states = new HashMap<>();
      ModelNode modelNode = ModelNode.fromJSONString(response.readEntity(String.class));
      for (ModelNode transitionNode : modelNode.get("transitions").asList()) {
        Transition transition =
            new Transition(transitionNode.get("id").asInt(), transitionNode.get("name").asString());
        states.put(transition.toState, transition);
      }
      ToStateTransitions toStateTransitions = new ToStateTransitions(issue.getState(), states);
      return toStateTransitions;
    }
Ejemplo n.º 4
0
  public void rollbackTransaction() {
    try {
      if (transactionPath == null) {
        logger.warn("No fedora transaction active, can't rollback.");
        return; // Better not to throw exception here, the transaction probably was rolled back in
                // other way or never started, so the purpose of voiding the transaction is reached
                // anyway
      }
      toUpdate.clear();
      toDelete.clear();

      Response response =
          ClientBuilder.newClient()
              .target(transactionPath + "/fcr:tx/fcr:rollback")
              .request()
              .post(null);
      if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
        throw new RuntimeException(
            "Fedora responded with error when trying to rollback transaction. "
                + response.readEntity(String.class));
      }
    } finally {
      transactionPath = null;
    }
  }
  public void sendMessages(
      String source, long sourceDeviceId, String destination, IncomingMessageList messages)
      throws IOException {
    Response response = null;

    try {
      response =
          client
              .target(peer.getUrl())
              .path(String.format(RELAY_MESSAGE_PATH, source, sourceDeviceId, destination))
              .request()
              .put(Entity.json(messages));

      if (response.getStatus() != 200 && response.getStatus() != 204) {
        if (response.getStatus() == 411)
          throw new WebApplicationException(Response.status(413).build());
        else throw new WebApplicationException(Response.status(response.getStatusInfo()).build());
      }

    } catch (ProcessingException e) {
      logger.warn("sendMessage", e);
      throw new IOException(e);
    } finally {
      if (response != null) response.close();
    }
  }
  @Test
  public void canAddRecipeAndIngredients() throws Exception {
    UUID uuid = UUIDGen.getTimeUUID();

    String json =
        "{\"recipe\":{\"name\":\"Spaghetti Bolognaise\",\"id\":\""
            + uuid
            + "\"},\"ingredients\":["
            + "{\"recipeId\":\""
            + uuid
            + "\",\"name\":\"tomatoes\",\"quantity\":10,\"unit\":\"items\"},"
            + "{\"recipeId\":\""
            + uuid
            + "\",\"name\":\"mince meat\",\"quantity\":500,\"unit\":\"grams\"}]}";

    Response result =
        target("recipe/" + uuid)
            .request()
            .accept(APPLICATION_JSON_TYPE)
            .put(Entity.entity(json, MediaType.APPLICATION_JSON_TYPE));

    assertThat(result.getStatusInfo().getFamily(), equalTo(SUCCESSFUL));
    verify(mockRecipeDao).persist(new Recipe(uuid, "Spaghetti Bolognaise"));
    verify(mockIngredientDao).persist(new Ingredient(uuid, "tomatoes", 10, "items"));
    verify(mockIngredientDao).persist(new Ingredient(uuid, "mince meat", 500, "grams"));
  }
Ejemplo n.º 7
0
  /**
   * Creates a request to the server (with the whole process time set to the maximum of 5 seconds)
   * for the given {@code path} and {@code mediaType} that should result in the {@code
   * expectedResponse}.
   */
  private void _testExceptionInWriteResponseMethod(
      final String path, final String mediaType, final Response.Status expectedResponse)
      throws Exception {
    // Executor.
    final ExecutorService executor = Executors.newSingleThreadExecutor();

    final Future<Response> responseFuture =
        executor.submit(
            new Callable<Response>() {

              @Override
              public Response call() throws Exception {
                return target().path(path).request(mediaType).get();
              }
            });

    executor.shutdown();
    final boolean inTime = executor.awaitTermination(5000, TimeUnit.MILLISECONDS);

    // Asserts.
    assertTrue(inTime);

    // Response.
    final Response response = responseFuture.get();
    assertEquals(expectedResponse, response.getStatusInfo());
  }
Ejemplo n.º 8
0
  protected ThingStatusDetail authenticate(String username, String password) {

    TokenRequest token = new TokenRequest(username, password);
    String payLoad = gson.toJson(token);

    Response response =
        tokenTarget.request().post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));

    logger.trace("Authenticating : Response : {}", response.getStatusInfo());

    if (response != null) {
      if (response.getStatus() == 200 && response.hasEntity()) {

        String responsePayLoad = response.readEntity(String.class);
        JsonObject readObject = parser.parse(responsePayLoad).getAsJsonObject();

        for (Entry<String, JsonElement> entry : readObject.entrySet()) {
          switch (entry.getKey()) {
            case "access_token":
              {
                accessToken = entry.getValue().getAsString();
                logger.trace("Authenticating : Setting access code to : {}", accessToken);
                return ThingStatusDetail.NONE;
              }
          }
        }
      } else if (response.getStatus() == 401) {
        return ThingStatusDetail.CONFIGURATION_ERROR;
      } else if (response.getStatus() == 503) {
        return ThingStatusDetail.COMMUNICATION_ERROR;
      }
    }
    return ThingStatusDetail.CONFIGURATION_ERROR;
  }
Ejemplo n.º 9
0
  protected Vehicle queryVehicle() {

    // get a list of vehicles
    Response response =
        vehiclesTarget
            .request(MediaType.APPLICATION_JSON_TYPE)
            .header("Authorization", "Bearer " + accessToken)
            .get();

    logger.trace("Querying the vehicle : Response : {}", response.getStatusInfo());

    JsonParser parser = new JsonParser();

    JsonObject jsonObject = parser.parse(response.readEntity(String.class)).getAsJsonObject();
    Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);

    for (int i = 0; i < vehicleArray.length; i++) {
      logger.trace("Querying the vehicle : VIN : {}", vehicleArray[i].vin);
      if (vehicleArray[i].vin.equals(getConfig().get(VIN))) {
        vehicleJSON = gson.toJson(vehicleArray[i]);
        parseAndUpdate("queryVehicle", null, vehicleJSON);
        return vehicleArray[i];
      }
    }

    return null;
  }
Ejemplo n.º 10
0
  /**
   * Test checks that a GET on the resource "/form/colours" with mime-type "application/json" shows
   * the appropriate colours based on the query param "match".
   */
  @Test
  public void testGetColoursAsJson() {
    Response response =
        target().path("form").path("colours").request(MediaType.APPLICATION_JSON).get();
    assertEquals(
        "GET on path '/form/colours' with mime type 'application/json' doesn't give expected response",
        Response.Status.OK,
        response.getStatusInfo());

    JSONArray jsonArray =
        target()
            .path("form")
            .path("colours")
            .request(MediaType.APPLICATION_JSON)
            .get(JSONArray.class);
    assertEquals(
        "Returned JSONArray doesn't have expected number of entries", 7, jsonArray.length());

    // with the query param "match" value "re"
    jsonArray =
        target("form/colours")
            .queryParam("match", "re")
            .request(MediaType.APPLICATION_JSON)
            .get(JSONArray.class);
    assertEquals(
        "Returned JSONArray doesn't have expected number of entries with the query param 'match=re'",
        2,
        jsonArray.length());
  }
  public void sendDeliveryReceipt(
      String source, long sourceDeviceId, String destination, long messageId) throws IOException {
    Response response = null;

    try {
      response =
          client
              .target(peer.getUrl())
              .path(String.format(RECEIPT_PATH, source, sourceDeviceId, destination, messageId))
              .request()
              .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
              .put(Entity.entity("", MediaType.APPLICATION_JSON_TYPE));

      if (response.getStatus() != 200 && response.getStatus() != 204) {
        if (response.getStatus() == 411)
          throw new WebApplicationException(Response.status(413).build());
        else throw new WebApplicationException(Response.status(response.getStatusInfo()).build());
      }
    } catch (ProcessingException e) {
      logger.warn("sendMessage", e);
      throw new IOException(e);
    } finally {
      if (response != null) response.close();
    }
  }
Ejemplo n.º 12
0
 @Test
 public void testCustomBadRequest() {
   // with InMemory container and connector status info should be transferred as it is produced.
   final Response response = target().path("resource/custom-bad-request").request().get();
   Assert.assertEquals(400, response.getStatus());
   Assert.assertNull(response.getStatusInfo().getReasonPhrase());
 }
Ejemplo n.º 13
0
 /*
  * Notify node that we (think we) are its predecessor.
  */
 public TableRep notify(NodeInfo node, TableRep predDb) throws DHTBase.Failed {
   /*
    * The protocol here is more complex than for other operations. We
    * notify a new successor that we are its predecessor, and expect its
    * bindings as a result. But if it fails to accept us as its predecessor
    * (someone else has become intermediate predecessor since we found out
    * this node is our successor i.e. race condition that we don't try to
    * avoid because to do so is infeasible), it notifies us by returning
    * null. This is represented in HTTP by RC=304 (Not Modified).
    */
   NodeInfo thisNode = predDb.getInfo();
   UriBuilder ub = UriBuilder.fromUri(node.addr).path("notify");
   URI notifyPath = ub.queryParam("id", thisNode.id).build();
   info("client notify(" + notifyPath + ")");
   Response response = putRequest(notifyPath, Entity.xml(predDb));
   if (response != null && response.getStatusInfo() == Response.Status.NOT_MODIFIED) {
     /*
      * Do nothing, the successor did not accept us as its predecessor.
      */
     return null;
   } else if (response == null || response.getStatus() >= 300) {
     throw new DHTBase.Failed("PUT /notify?id=ID");
   } else {
     TableRep bindings = response.readEntity(TableRep.class);
     return bindings;
   }
 }
Ejemplo n.º 14
0
  /** Test checks that POST on the '/form' resource gives a response page with the entered data. */
  @Test
  public void testPostOnForm() {
    MultivaluedMap<String, String> formData = new MultivaluedStringMap();
    formData.add("name", "testName");
    formData.add("colour", "red");
    formData.add("hint", "re");

    Response response =
        target()
            .path("form")
            .request()
            .post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
    assertEquals(Response.Status.OK, response.getStatusInfo());

    // check that the generated response is the expected one
    InputStream responseInputStream = response.readEntity(InputStream.class);
    try {
      byte[] responseData = new byte[responseInputStream.available()];
      final int read = responseInputStream.read(responseData);

      assertTrue(read > 0);
      assertTrue(new String(responseData).contains("Hello, you entered"));
    } catch (IOException ex) {
      Logger.getLogger(MainTest.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 15
0
  @Test
  public void testWrongId() throws Exception {

    URI uri = getBaseUri().queryParam("id", -1).build();
    Response response = client.target(uri).request("application/xml").get();

    assertEquals(Response.Status.Family.CLIENT_ERROR, response.getStatusInfo().getFamily());
  }
Ejemplo n.º 16
0
 /** Test if GET on the resource "/form" gives response with status code 200. */
 @Test
 public void testGetOnForm() {
   Response response = target().path("form").request(MediaType.TEXT_HTML).get();
   assertEquals(
       "GET on the 'form' resource doesn't give expected response",
       Response.Status.OK,
       response.getStatusInfo());
 }
Ejemplo n.º 17
0
  public void addCatalog() {
    Response response = services.getCatalogService().request().post(Entity.xml(catalogItem));

    Response.StatusType statusInfo = response.getStatusInfo();

    if (statusInfo.getStatusCode() == Response.Status.CREATED.getStatusCode())
      status = "User added successfully";
    else status = statusInfo.getReasonPhrase();
  }
  public void handleFileUpload(FileUploadEvent fue) {
    String docId = UUID.randomUUID().toString();
    getDocIds().add(docId);
    try {
      IclubDocumentModel model = new IclubDocumentModel();
      model.setIclubPerson(getSessionUserId());
      model.setDCrtdDt(new Date(System.currentTimeMillis()));
      model.setDId(docId);
      model.setDName(fue.getFile().getFileName());
      model.setDContent(fue.getFile().getContentType());
      model.setDSize(fue.getFile().getSize());

      WebClient client = IclubWebHelper.createCustomClient(D_BASE_URL + "add");
      ResponseModel response =
          client.accept(MediaType.APPLICATION_JSON).post(model, ResponseModel.class);
      client.close();

      if (response.getStatusCode() == 0) {
        ContentDisposition cd =
            new ContentDisposition(
                "attachment;filename="
                    + fue.getFile().getFileName()
                    + ";filetype="
                    + fue.getFile().getContentType());
        List<Attachment> attachments = new ArrayList<Attachment>();
        Attachment attachment = new Attachment(docId, fue.getFile().getInputstream(), cd);
        attachments.add(attachment);

        WebClient uploadClient = WebClient.create(D_BASE_URL + "upload");
        Response res =
            uploadClient.type("multipart/form-data").post(new MultipartBody(attachments));
        uploadClient.close();

        if (res.getStatus() == 200) {
          IclubWebHelper.addMessage(
              getLabelBundle().getString("doucmentuploadedsuccessfully"),
              FacesMessage.SEVERITY_INFO);
        } else {
          IclubWebHelper.addMessage(
              getLabelBundle().getString("doucmentuploadingfailed")
                  + " :: "
                  + (res.getHeaderString("status") != null
                      ? res.getHeaderString("status")
                      : res.getStatusInfo()),
              FacesMessage.SEVERITY_ERROR);
        }
      }
    } catch (Exception e) {
      LOGGER.error(e, e);
      IclubWebHelper.addMessage(
          getLabelBundle().getString("doucmentuploadingerror") + " :: " + e.getMessage(),
          FacesMessage.SEVERITY_ERROR);
    }
  }
 @Test(expected = ClientErrorException.class)
 public void testGetReturns403() throws Exception {
   // Arrange
   Mockito.when(response.getStatus()).thenReturn(403);
   Mockito.when(response.getStatusInfo().getFamily())
       .thenReturn(Response.Status.Family.CLIENT_ERROR);
   Mockito.when(builder.get()).thenReturn(response);
   // Act
   classUnderTest.getOne(builder);
   // Assert
   fail("Should have thrown an Exception");
 }
Ejemplo n.º 20
0
  public void patchMetadata(ZdoModel model) {
    // Warning: this does not go to triplestore
    // Warning: this will work only for this use case but fail miserably if used for something else
    /*  We tried to update fedora with the updateMetadata() method, but it fails with 400.
    This happens only when using transaction and trying to update metadata node that was just inserted.
    Theory is, that fedora does not realize this operation should be on temporary transaction node
    and tries to perform update on non-transaction node (which does not exist until transaction is committed.
    Hence, we use this sparql workaround that does not have this error.
    */
    String updateString = "INSERT {   \n";
    StmtIterator iter = model.listStatements();
    if (!iter.hasNext()) {
      return; // If there is nothing to update, return
    }
    while (iter.hasNext()) {
      Statement statement = iter.next();
      String subject = statement.getSubject().getURI();
      String predicate = statement.getPredicate().getURI();
      if (!predicate.startsWith("http://inqool.cz/zdo/") && !predicate.startsWith(DCTerms.NS)) {
        continue;
      }
      String value = statement.getObject().asLiteral().getString();

      String updateLine =
          " <" + fitTransactionToUrl(subject) + "> <" + predicate + "> \"" + value + "\".\n";
      updateString += updateLine;
    }
    updateString += "}\nWHERE { }";

    Response response =
        ClientBuilder.newClient()
            .target(fitTransactionToUrl(model.getUrl()))
            .request()
            .method("PATCH", Entity.entity(updateString, "application/sparql-update"));

    if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
      logError(model.getUrl(), response.getStatusInfo());
      throw new RuntimeException("Failed to update resource " + model.getUrl());
    }
  }
Ejemplo n.º 21
0
  /**
   * Create new Jersey client response context initialized from a JAX-RS {@link Response response}.
   *
   * @param requestContext associated request context.
   * @param response JAX-RS response to be used to initialize the response context.
   */
  public ClientResponse(final ClientRequest requestContext, final Response response) {
    this(response.getStatusInfo(), requestContext);
    this.headers(OutboundJaxrsResponse.from(response).getContext().getStringHeaders());

    final Object entity = response.getEntity();
    if (entity != null) {
      InputStream entityStream =
          new InputStream() {

            private ByteArrayInputStream byteArrayInputStream = null;

            @Override
            public int read() throws IOException {
              if (byteArrayInputStream == null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                OutputStream stream = null;
                try {
                  try {
                    stream =
                        requestContext
                            .getWorkers()
                            .writeTo(
                                entity,
                                entity.getClass(),
                                null,
                                null,
                                response.getMediaType(),
                                response.getMetadata(),
                                requestContext.getPropertiesDelegate(),
                                baos,
                                null,
                                false);
                  } finally {
                    if (stream != null) {
                      stream.close();
                    }
                  }
                } catch (IOException e) {
                  // ignore
                }

                byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray());
              }

              return byteArrayInputStream.read();
            }
          };
      setEntityStream(entityStream);
    }
  }
 @Test
 @SuppressWarnings("unchecked")
 public void testDeleteReturns200() throws Exception {
   // Arrange
   Mockito.when(response.getStatus()).thenReturn(200);
   Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(null);
   Mockito.when(response.getStatusInfo().getFamily())
       .thenReturn(Response.Status.Family.SUCCESSFUL);
   Mockito.when(builder.delete(Response.class)).thenReturn(response);
   // Act
   Issue deleteOne = classUnderTest.deleteOne(builder);
   // Assert
   assertEquals(null, deleteOne);
 }
 @Test
 @SuppressWarnings("unchecked")
 public void testPutReturns204() throws Exception {
   // Arrange
   Mockito.when(response.getStatus()).thenReturn(204);
   Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(entity);
   Mockito.when(response.getStatusInfo().getFamily())
       .thenReturn(Response.Status.Family.SUCCESSFUL);
   Mockito.when(builder.put(entity, Response.class)).thenReturn(response);
   // Act
   Issue putOne = classUnderTest.putOne(builder, entity);
   // Assert
   assertEquals(null, putOne);
 }
  @Test
  @SuppressWarnings("unchecked")
  public void testPostReturns200() throws Exception {

    Mockito.when(response.getStatus()).thenReturn(200);
    Mockito.when(response.getStatusInfo().getFamily())
        .thenReturn(Response.Status.Family.SUCCESSFUL);
    Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(jsonstring);
    Mockito.when(builder.post(entity, Response.class)).thenReturn(response);
    // Act
    Issue actual = classUnderTest.postOne(builder, expected);
    // Assert
    assertEquals(expected, actual);
  }
Ejemplo n.º 25
0
  /**
   * Create a GitLabApiException instance based on the ClientResponse.
   *
   * @param response
   */
  public GitLabApiException(Response response) {

    super();
    statusInfo = response.getStatusInfo();
    httpStatus = response.getStatus();

    if (response.hasEntity()) {
      try {

        ErrorMessage errorMessage = response.readEntity(ErrorMessage.class);
        message = errorMessage.getMessage();

      } catch (Exception ignore) {
      }
    }
  }
Ejemplo n.º 26
0
  private Object callGitHub(String organization, String repository, String command, String param) {
    try {
      String url =
          String.format(
              "%s/repos/%s/%s/%s%s",
              Config.getInstance().getGitAPIUrl(),
              organization,
              repository,
              command,
              param != null ? param : "");
      Client client = ClientBuilder.newBuilder().build();

      WebTarget target =
          client
              .register(
                  new Authenticator(
                      Config.getInstance().getUserName(), Config.getInstance().getPassword()))
              .target(url);
      Response response = target.request().get();
      String value = response.readEntity(String.class);

      if (response.getStatus() != 200) {
        logger.warn(
            "Response status is NOT OK ("
                + response.getStatus()
                + ", "
                + response.getStatusInfo()
                + ") for URL: "
                + url
                + "\nFull message: "
                + value);
        return null;
      } else {
        logger.info("Response OK");
      }

      response.close(); // You should close connections!

      return value;
    } catch (Throwable e) {
      logger.warn("Error while validating user input:", e);
      return null;
    }
  }
Ejemplo n.º 27
0
  private String sparqlQuery(String query) {
    Client client = ClientBuilder.newClient();

    Response response =
        client
            .target(SPARQL_ENDPOINT)
            .request()
            .post(Entity.entity(query, "application/sparql-query"));

    if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
      String result = response.readEntity(String.class);
      logger.debug("Sparql Query result: ", result);
      return result;
    } else {
      logger.error("Sparql Query: ", query);
      logger.error("Result: ", response.getStatus());
      throw new SparqlException("Error executing SPARQL Query.");
    }
  }
Ejemplo n.º 28
0
  public void startTransaction() {
    if (transactionPath != null) {
      throw new RuntimeException("Fedora transaction already active, can't start new one.");
    }

    Response response =
        ClientBuilder.newClient().target(FEDORA_ENDPOINT + "fcr:tx").request().post(null);
    if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
      throw new RuntimeException("Fedora responded with error when starting transaction.");
    }

    URI txLocation = response.getLocation();
    if (txLocation == null) {
      throw new RuntimeException("There was no transaction info in fedora's response.");
    }
    toUpdate.clear();
    toDelete.clear();
    transactionPath = txLocation.toString();
  }
  @Override
  public void delete(final String code) throws InterruptedException, CrudException {
    try {
      final Response response =
          restApplicationsService.path(toLowerCase.f(code)).request().delete();
      final Response.StatusType statusInfo = response.getStatusInfo();
      log.debug("Response in delete method {}", response);

      if (NO_CONTENT != statusInfo.getStatusCode()) {
        log.error("response status expected {} but got {}", NO_CONTENT, statusInfo.getStatusCode());
        throw new CrudException(format("Impossible de supprimer l'application [%s]", code));
      }
    } catch (Exception e) {
      log.error("error in delete", e);
      if (e instanceof CrudException) {
        throw e;
      }
      throw new InterruptedException(e.getMessage());
    }
  }
Ejemplo n.º 30
0
  public ZdoModel get(String url) {
    Response response =
        ClientBuilder.newClient()
            .target(fitTransactionToUrl(url))
            .request()
            .accept(RDF_SERIALIZATION)
            .get();

    if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
      logger.error(
          "Get on Fedora url "
              + url
              + " returned "
              + response.getStatus()
              + ": "
              + response.readEntity(String.class));
      return null;
    }

    if (response.getMediaType().toString().equals("text/rdf+n3")) {
      ZdoModel result = response.readEntity(ZdoModel.class);
      if (result == null) return null;
      result.setUrl(
          fitTransactionToUrl(
              url)); // sometimes fedora returns url without transaction in url, but subjects with
                     // it...then get property doesn't work of course
      result
          .stripPossibleBadUrlEnding(); // sometimes we get unwanted query parameters or such, but
                                        // we need url to exactly match the RDF subject
      return result;
    } else {
      logger.debug(
          "Tried to retrieve non RDF resource '{}', retreiving from /fcr:metadata node instead.",
          url);
      ZdoModel model = get(url + "/fcr:metadata");
      model.setUrl(fitTransactionToUrl(url));
      return model;
    }
  }