Beispiel #1
0
  @POST
  @Path("/upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail) {

    // Path format //10.217.14.97/Installables/uploaded/
    System.out.println("path::" + System.getProperty("com.sun.aas.instanceRoot"));
    String uploadedFileLocation =
        System.getProperty("com.sun.aas.instanceRoot")
            + "/eclipseApps/SeriesWeb/images/upload/"
            + fileDetail.getFileName();

    try {
      OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
      int read = 0;
      byte[] bytes = new byte[1024];

      out = new FileOutputStream(new File(uploadedFileLocation));
      while ((read = uploadedInputStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
      }
      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    String output = "File uploaded to : " + uploadedFileLocation;

    return Response.status(200).entity(output).build();
  }
  @POST
  @Path("/upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail,
      @FormDataParam("login") String login) {

    String uploadedFileLocation = "d://" + fileDetail.getFileName();

    // save it
    writeToFile(uploadedInputStream, uploadedFileLocation);
    Integer index = null;
    for (int i = 0; i < HelloWorldService.list.size(); i++) {
      if (HelloWorldService.list.get(i).getLogin().equals(login)) {
        index = i;
        break;
      }
    }
    HelloWorldService.list.get(index.intValue()).setFileName(uploadedFileLocation);

    String output = "File uploaded to : " + uploadedFileLocation;

    return Response.status(200).entity(output).build();
  }
Beispiel #3
0
  // <editor-fold defaultstate="collapsed" desc="import">
  @POST
  @Path("/import/zip")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response importZip(
      @FormDataParam("file") FormDataContentDisposition fileDisposition,
      @FormDataParam("file") InputStream file) {
    String storeDirPath = Init.getStoredQueriesPath();
    File storeDir = storeDirPath == null ? null : new File(storeDirPath);
    if (storeDir == null) return Response.status(Response.Status.NOT_FOUND).build();

    final StringBuilder res = new StringBuilder();
    if (fileDisposition != null) {
      logInfo("import {0}", fileDisposition.getFileName());
      try {
        unzip(
            storeDir,
            file,
            new Reciver<String>() {
              @Override
              public void recive(String logtext) {
                res.append(logtext.trim());
                res.append("\n");
              }
            });
      } catch (IOException ex) {
        Logger.getLogger(SqlQueriesRest.class.getName()).log(Level.SEVERE, null, ex);
        return Response.serverError().build();
      }
    }
    return Response.ok("succ\n" + res.toString()).build();
  }
 /**
  * Sets the connection params.
  *
  * @param key the key
  * @param value the value
  * @return the API result
  */
 public APIResult setConnectionParams(String key, String value) {
   WebTarget target = getSessionWebTarget();
   FormDataMultiPart mp = new FormDataMultiPart();
   mp.bodyPart(
       new FormDataBodyPart(
           FormDataContentDisposition.name("sessionid").build(),
           this.sessionHandle,
           MediaType.APPLICATION_XML_TYPE));
   mp.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("key").build(), key));
   mp.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("value").build(), value));
   LOG.debug("Setting connection params " + key + "=" + value);
   APIResult result =
       target
           .path("params")
           .request()
           .put(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE), APIResult.class);
   return result;
 }
 /**
  * Removes the resource from connection.
  *
  * @param type the type
  * @param resourcePath the resource path
  * @return the API result
  */
 public APIResult removeResourceFromConnection(String type, String resourcePath) {
   WebTarget target = getSessionWebTarget();
   FormDataMultiPart mp = new FormDataMultiPart();
   mp.bodyPart(
       new FormDataBodyPart(
           FormDataContentDisposition.name("sessionid").build(),
           this.sessionHandle,
           MediaType.APPLICATION_XML_TYPE));
   mp.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("type").build(), type));
   mp.bodyPart(
       new FormDataBodyPart(FormDataContentDisposition.name("path").build(), resourcePath));
   APIResult result =
       target
           .path("resources/delete")
           .request()
           .put(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE), APIResult.class);
   return result;
 }
  /**
   * Open.
   *
   * @param password the password
   * @return the lens session handle
   */
  public LensSessionHandle open(String password) {

    WebTarget target = getSessionWebTarget();
    FormDataMultiPart mp = new FormDataMultiPart();
    mp.bodyPart(
        new FormDataBodyPart(
            FormDataContentDisposition.name("username").build(), params.getUser()));
    mp.bodyPart(
        new FormDataBodyPart(FormDataContentDisposition.name("password").build(), password));

    String database = params.getDbName();
    mp.bodyPart(
        new FormDataBodyPart(FormDataContentDisposition.name("database").build(), database));

    mp.bodyPart(
        new FormDataBodyPart(
            FormDataContentDisposition.name("sessionconf").fileName("sessionconf").build(),
            params.getSessionConf(),
            MediaType.APPLICATION_XML_TYPE));
    try {
      Response response =
          target.request().post(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE));
      if (response.getStatus() != 200) {
        throw new LensClientServerConnectionException(response.getStatus());
      }
      final LensSessionHandle handle = response.readEntity(LensSessionHandle.class);
      if (handle != null) {
        sessionHandle = handle;
        LOG.debug("Created a new session " + sessionHandle.getPublicId());
      } else {
        throw new IllegalStateException(
            "Unable to connect to lens " + "server with following paramters" + params);
      }
    } catch (ProcessingException e) {
      if (e.getCause() != null && e.getCause() instanceof ConnectException) {
        throw new LensClientServerConnectionException(e.getCause().getMessage(), e);
      }
    }

    LOG.debug("Successfully switched to database " + params.getDbName());
    open.set(true);

    return sessionHandle;
  }
  @Test
  public void testUploadStreamMissing() {
    FormDataContentDispositionBuilder builder =
        FormDataContentDisposition.name("multipart;form-data");
    builder.fileName("adele1.png");
    FormDataContentDisposition formDataContentDisposition = builder.build();

    response =
        recordEndpoint.uploadFile(
            AUTH_TOKEN, AUTH_TOKEN, "image", "image:123456789", null, formDataContentDisposition);

    assertResponseStatusIs(Response.Status.BAD_REQUEST);
  }
  @Test
  public void testUpload() throws ParseException {
    InputStream stream = new ByteArrayInputStream("a string".getBytes(StandardCharsets.UTF_8));

    FormDataContentDispositionBuilder builder =
        FormDataContentDisposition.name("multipart;form-data");
    builder.fileName("adele1.png");
    FormDataContentDisposition formDataContentDisposition = builder.build();

    response =
        recordEndpoint.uploadFile(
            AUTH_TOKEN, AUTH_TOKEN, "image", "image:123456789", stream, formDataContentDisposition);

    String entity = (String) response.getEntity();

    assertEquals(
        entity,
        "{\"record\":{\"data\":{\"children\":[{\"children\":["
            + "{\"name\":\"id\",\"value\":\"image:123456789\"},"
            + "{\"name\":\"type\",\"value\":\"image\"},"
            + "{\"name\":\"createdBy\",\"value\":\"12345\"},"
            + "{\"children\":["
            + "{\"name\":\"linkedRecordType\",\"value\":\"system\"},"
            + "{\"name\":\"linkedRecordId\",\"value\":\"cora\"}],\"actionLinks\":"
            + "{\"read\":{\"requestMethod\":\"GET\",\"rel\":\"read\","
            + "\"url\":\"http://localhost:8080/therest/rest/record/system/cora\","
            + "\"accept\":\"application/uub+record+json\"}},\"name\":\"dataDivider\"}],"
            + "\"name\":\"recordInfo\"},{\"children\":[{\"children\":[{\"name\":\"streamId\","
            + "\"value\":\"1\"},{\"name\":\"filename\",\"value\":\"adele1.png\"}"
            + ",{\"name\":\"filesize\",\"value\":\"8\"}"
            + ",{\"name\":\"mimeType\",\"value\":\"application/octet-stream\"}]"
            + ",\"actionLinks\":{\"read\":{\"requestMethod\":\"GET\",\"rel\":\"read\","
            + "\"url\":\"http://localhost:8080/therest/rest/record/image/image:123456789/master\","
            + "\"accept\":\"application/octet-stream\"}},\"name\":\"master\"}],"
            + "\"name\":\"resourceInfo\"}],\"name\":\"binary\"},\"actionLinks\":{\"read\":"
            + "{\"requestMethod\":\"GET\",\"rel\":\"read\","
            + "\"url\":\"http://localhost:8080/therest/rest/record/image/image:123456789\","
            + "\"accept\":\"application/uub+record+json\"},"
            + "\"upload\":{\"requestMethod\":\"POST\",\"rel\":\"upload\","
            + "\"contentType\":\"multipart/form-data\",\"url\":"
            + "\"http://localhost:8080/therest/rest/record/image/image:123456789/master\"},"
            + "\"update\":{\"requestMethod\":\"POST\","
            + "\"rel\":\"update\",\"contentType\":\"application/uub+record+json\","
            + "\"url\":\"http://localhost:8080/therest/rest/record/image/image:123456789\","
            + "\"accept\":\"application/uub+record+json\"},\"delete\":"
            + "{\"requestMethod\":\"DELETE\",\"rel\":\"delete\","
            + "\"url\":\"http://localhost:8080/therest/rest/record/image/image:123456789\"}}}}");

    assertResponseStatusIs(Response.Status.OK);
  }
  @Test
  public void testUploadNotAChildOfBinary() {
    InputStream stream = new ByteArrayInputStream("a string".getBytes(StandardCharsets.UTF_8));

    FormDataContentDispositionBuilder builder =
        FormDataContentDisposition.name("multipart;form-data");
    builder.fileName("adele1.png");
    FormDataContentDisposition formDataContentDisposition = builder.build();

    response =
        recordEndpoint.uploadFile(
            AUTH_TOKEN, AUTH_TOKEN, PLACE, "image:123456789", stream, formDataContentDisposition);

    assertResponseStatusIs(Response.Status.METHOD_NOT_ALLOWED);
  }
Beispiel #10
0
  @PUT
  @Path(
      "/{"
          + RodaConstants.API_PATH_PARAM_REPRESENTATION_UUID
          + "}/"
          + RodaConstants.API_PRESERVATION_METADATA
          + "/")
  @ApiOperation(
      value = "Update representation preservation file",
      notes = "Update a preservation file to a representation",
      response = PreservationMetadata.class)
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "OK", response = PreservationMetadata.class),
        @ApiResponse(code = 404, message = "Not found", response = ApiResponseMessage.class)
      })
  public Response updatePreservationMetadataOnFile(
      @ApiParam(value = "The ID of the existing representation", required = true)
          @PathParam(RodaConstants.API_PATH_PARAM_REPRESENTATION_UUID)
          String representationId,
      @ApiParam(value = "The ID of the preservation metadata file", required = false)
          @QueryParam(RodaConstants.API_PATH_PARAM_FILE_ID)
          String fileId,
      @FormDataParam(RodaConstants.API_PARAM_FILE) InputStream inputStream,
      @FormDataParam(RodaConstants.API_PARAM_FILE) FormDataContentDisposition fileDetail,
      @ApiParam(
              value = "Choose format in which to get the response",
              allowableValues = RodaConstants.API_POST_PUT_MEDIA_TYPES)
          @QueryParam(RodaConstants.API_QUERY_KEY_ACCEPT_FORMAT)
          String acceptFormat)
      throws RODAException {
    String mediaType = ApiUtils.getMediaType(acceptFormat, request);

    // get user
    User user = UserUtility.getApiUser(request);

    // delegate action to controller
    Browser.createOrUpdatePreservationMetadataWithRepresentation(
        user, representationId, fileId, inputStream, fileDetail.getFileName(), false);
    return Response.ok(
            new ApiResponseMessage(ApiResponseMessage.OK, "Preservation file updated"), mediaType)
        .build();
  }
Beispiel #11
0
  /**
   * Upload an app file.
   *
   * <p>URL (PST): {scheme}://{host}:{port}/{contextRoot}/appstore/apps/{appid}/content (FormData:
   * InputStream and FormDataContentDisposition)
   *
   * @param appId
   * @param file
   * @return
   * @throws ClientException
   * @throws IOException
   */
  public StatusDTO uploadApp(String appId, File file) throws ClientException {
    if (file == null || !file.exists()) {
      throw new ClientException(401, "File doesn't exist.");
    }
    if (!file.isFile()) {
      throw new ClientException(401, "File is not a file.");
    }

    try {
      MultiPart multipart = new FormDataMultiPart();
      {
        FileDataBodyPart filePart =
            new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE);
        {
          FormDataContentDisposition.FormDataContentDispositionBuilder formBuilder =
              FormDataContentDisposition.name("file");
          formBuilder.fileName(URLEncoder.encode(file.getName(), "UTF-8"));
          formBuilder.size(file.length());
          formBuilder.modificationDate(new Date(file.lastModified()));
          filePart.setFormDataContentDisposition(formBuilder.build());
        }
        multipart.bodyPart(filePart);
      }

      WebTarget target = getRootPath().path("appstore/apps").path(appId).path("content");
      Builder builder = target.request(MediaType.APPLICATION_JSON);
      Response response =
          updateHeaders(builder).post(Entity.entity(multipart, multipart.getMediaType()));
      checkResponse(response);

      StatusDTO status = response.readEntity(StatusDTO.class);
      return status;

    } catch (ClientException | UnsupportedEncodingException e) {
      handleException(e);
    }

    return null;
  }
  private void expectTokenForUploadToPrefereblyBeHeaderThanQuery(
      String headerAuthToken, String queryAuthToken, String authTokenExpected) {
    SpiderInstanceFactorySpy factorySpy = setupInstanceProviderWithFactorySpy();

    FormDataContentDispositionBuilder builder =
        FormDataContentDisposition.name("multipart;form-data");
    builder.fileName("adele1.png");
    FormDataContentDisposition formDataContentDisposition = builder.build();
    InputStream stream = new ByteArrayInputStream("a string".getBytes(StandardCharsets.UTF_8));

    response =
        recordEndpoint.uploadFile(
            headerAuthToken,
            queryAuthToken,
            "image",
            "image:123456789",
            stream,
            formDataContentDisposition);

    SpiderUploaderSpy spiderUploaderSpy = factorySpy.spiderUploaderSpy;
    assertEquals(spiderUploaderSpy.authToken, authTokenExpected);
  }
  @POST
  @Path("/upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail) {
    String fileId = UUID.randomUUID().toString();
    String newFileName = fileId + "." + FilenameUtils.getExtension(fileDetail.getFileName());
    ;
    System.out.println(newFileName);
    String uploadedFileLocation = Constants.fileLocation + newFileName;
    try {
      // save it
      writeToFile(uploadedInputStream, uploadedFileLocation);

      FileVO responseFileVO = new FileVO();
      responseFileVO.setFileUrl(Constants.fileUrl + newFileName);
      return Response.status(200).entity(responseFileVO).type(MediaType.APPLICATION_JSON).build();
    } catch (Exception e) {
      return Response.status(400).build();
    }
  }
  /**
   * Test result formatter.
   *
   * @param conf the conf
   * @param status the status
   * @param isDir the is dir
   * @param reDirectUrl the re direct url
   * @throws InterruptedException the interrupted exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  private void testResultFormatter(LensConf conf, Status status, boolean isDir, String reDirectUrl)
      throws InterruptedException, IOException {
    // test post execute op
    final WebTarget target = target().path("queryapi/queries");

    final FormDataMultiPart mp = new FormDataMultiPart();
    conf.addProperty(LensConfConstants.QUERY_PERSISTENT_RESULT_SET, "true");
    mp.bodyPart(
        new FormDataBodyPart(
            FormDataContentDisposition.name("sessionid").build(),
            lensSessionId,
            MediaType.APPLICATION_XML_TYPE));
    mp.bodyPart(
        new FormDataBodyPart(
            FormDataContentDisposition.name("query").build(),
            "select ID, IDSTR, IDARR, IDSTRARR from " + testTable));
    mp.bodyPart(
        new FormDataBodyPart(FormDataContentDisposition.name("operation").build(), "execute"));
    mp.bodyPart(
        new FormDataBodyPart(
            FormDataContentDisposition.name("conf").fileName("conf").build(),
            conf,
            MediaType.APPLICATION_XML_TYPE));
    QueryHandle handle =
        target
            .request()
            .post(
                Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE),
                new GenericType<LensAPIResult<QueryHandle>>() {})
            .getData();

    Assert.assertNotNull(handle);

    // Get query
    LensQuery ctx =
        target
            .path(handle.toString())
            .queryParam("sessionid", lensSessionId)
            .request()
            .get(LensQuery.class);
    // wait till the query finishes
    QueryStatus stat = ctx.getStatus();
    while (!stat.finished()) {
      ctx =
          target
              .path(handle.toString())
              .queryParam("sessionid", lensSessionId)
              .request()
              .get(LensQuery.class);
      stat = ctx.getStatus();
      Thread.sleep(1000);
    }

    Assert.assertEquals(ctx.getStatus().getStatus(), status);

    if (status.equals(QueryStatus.Status.SUCCESSFUL)) {
      QueryContext qctx = queryService.getQueryContext(handle);
      if (qctx == null) {
        // This shouldn't occur. It is appearing when query gets purged. So adding extra logs
        // for debugging in the future.
        log.info("successful query's QueryContext is null");
        log.info("query handle: {}", handle);
        log.info("allQueries: {}", queryService.allQueries);
        // not doing formatter validation if qctx is null
      } else if (!isDir) {
        // isDir is true if the formatter is skipped due to result being the max size allowed
        if (qctx.isDriverPersistent()) {
          Assert.assertTrue(qctx.getQueryOutputFormatter() instanceof PersistedOutputFormatter);
        } else {
          Assert.assertTrue(qctx.getQueryOutputFormatter() instanceof InMemoryOutputFormatter);
        }
      } else {
        Assert.assertNull(qctx.getQueryOutputFormatter());
      }
      // fetch results
      TestQueryService.validatePersistedResult(
          handle,
          target(),
          lensSessionId,
          new String[][] {
            {"ID", "INT"}, {"IDSTR", "STRING"}, {"IDARR", "ARRAY"}, {"IDSTRARR", "ARRAY"},
          },
          isDir);
      if (!isDir) {
        TestQueryService.validateHttpEndPoint(target(), lensSessionId, handle, reDirectUrl);
      }
    } else {
      assertTrue(ctx.getSubmissionTime() > 0);
      assertTrue(ctx.getLaunchTime() > 0);
      assertTrue(ctx.getDriverStartTime() > 0);
      assertTrue(ctx.getDriverFinishTime() > 0);
      assertTrue(ctx.getFinishTime() > 0);
      Assert.assertEquals(ctx.getStatus().getStatus(), QueryStatus.Status.FAILED);
    }
  }