Java 类javax.ws.rs.core.Response.ResponseBuilder 实例源码

项目:Celebino    文件:LitersMinuteController.java   
/**
 * Cadastra litersminute
 * 
 * @param User
 * @return Response
 */
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(LitersMinute litersminute) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    Timestamp date = new Timestamp(System.currentTimeMillis());
    litersminute.setDate(date);

    try {
        AirConditioning air = AirConditioningDao.getInstance().getById(litersminute.getAirconditioning().getId());

        if (air.getId().equals(null)) {
            AirConditioningDao.getInstance().insertU(litersminute.getAirconditioning());
        } else {
            litersminute.setAirconditioning(air);
        }

        Long id = LitersMinuteDao.getInstance().insertU(litersminute);
        litersminute.setId(id);

        System.out.println(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date.getTime()));
        System.out.println(date.getTime());
        builder.status(Response.Status.OK).entity(litersminute);

    } catch (SQLException e) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:Celebino    文件:LitersMinuteController.java   
/**
 * Return all lmin by air
 * 
 * @return Response
 */
@PermitAll
@GET
@Path("/byair/{id}")
@Produces("application/json")
public Response getAirConditioningById(@PathParam("id") Long idAir) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    try {
        List<LitersMinute> lmin = LitersMinuteDao.getInstance().getByAirId(idAir);

        if (lmin != null) {
            builder.status(Response.Status.OK);
            builder.entity(lmin);

        } else {
            builder.status(Response.Status.NOT_FOUND);
        }

    } catch (SQLException exception) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:InComb    文件:TranslationService.java   
/**
 * Returns Translations of a given {@link Locale}
 * @param locale to get the Translation of
 * @param request The HTTP-Request - is injected automatically
 * @return the translation
 */
@GET
public Response getTranslations(@PathParam("locale") final String locale,
        @Context final Request request) {

    final Translator translator = TranslatorManager.getTranslator(LocaleUtil.toLocale(locale));
    if(translator == null) {
        throw new NotFoundException();
    }

    final File file = translator.getFile();
    final Date lastModified = new Date(file.lastModified());

    ResponseBuilder respBuilder = request.evaluatePreconditions(lastModified);
    if(respBuilder == null) {
        respBuilder = Response.ok();
    }

    return respBuilder.lastModified(lastModified).entity(new StreamingOutput() {
        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {
            IOUtils.copy(new FileInputStream(file), output);
        }
    }).build();
}
项目:personium-core    文件:AbstractODataResource.java   
/**
 * POST用のレスポンスビルダーを作成する.
 * @param ent OEntity
 * @param outputFormat Content-Type
 * @param responseStr レスポンスボディ
 * @param resUriInfo レスポンスのUriInfo
 * @param key レスポンスのエンティティキー
 * @return レスポンスビルダー
 */
protected ResponseBuilder getPostResponseBuilder(
        OEntity ent,
        MediaType outputFormat,
        String responseStr,
        UriInfo resUriInfo,
        String key) {
    ResponseBuilder rb = Response.status(HttpStatus.SC_CREATED).entity(responseStr).type(outputFormat)
            .header(HttpHeaders.LOCATION, resUriInfo.getBaseUri().toASCIIString()
                    + getEntitySetName() + key)
            .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataVersion.V2.asString);

    // 応答にETAGを付与
    if (ent instanceof OEntityWrapper) {
        OEntityWrapper oew2 = (OEntityWrapper) ent;
        String etag = oew2.getEtag();
        if (etag != null) {
            rb = rb.header(HttpHeaders.ETAG, "W/\"" + etag + "\"");
        }
    }
    return rb;
}
项目:ditb    文件:StorageClusterVersionResource.java   
@GET
@Produces({MIMETYPE_TEXT, MIMETYPE_XML, MIMETYPE_JSON})
public Response get(final @Context UriInfo uriInfo) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("GET " + uriInfo.getAbsolutePath());
  }
  servlet.getMetrics().incrementRequests(1);
  try {
    StorageClusterVersionModel model = new StorageClusterVersionModel();
    model.setVersion(servlet.getAdmin().getClusterStatus().getHBaseVersion());
    ResponseBuilder response = Response.ok(model);
    response.cacheControl(cacheControl);
    servlet.getMetrics().incrementSucessfulGetRequests(1);
    return response.build();
  } catch (IOException e) {
    servlet.getMetrics().incrementFailedGetRequests(1);
    return Response.status(Response.Status.SERVICE_UNAVAILABLE)
      .type(MIMETYPE_TEXT).entity("Unavailable" + CRLF)
      .build();
  }
}
项目:Celebino    文件:AirConditioningController.java   
/**
 * Cadastrar air
 * 
 * @param AirConditioning
 * @return Response
 */
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(AirConditioning air) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    try {
        Long idAir = (long) AirConditioningDao.getInstance().insertU(air);
        air.setId(idAir);
        builder.status(Response.Status.OK).entity(air);

    } catch (SQLException e) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:Celebino    文件:AirConditioningController.java   
@PermitAll
@PUT
@Path("/")
@Produces("application/json")
@Consumes("application/json")
public Response update(AirConditioning air) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    try {
        AirConditioningDao.getInstance().update(air);
        builder.status(Response.Status.OK).entity(air);

    } catch (SQLException exception) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }
    return builder.build();

}
项目:ditb    文件:RootResource.java   
@GET
@Produces({MIMETYPE_TEXT, MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF,
  MIMETYPE_PROTOBUF_IETF})
public Response get(final @Context UriInfo uriInfo) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("GET " + uriInfo.getAbsolutePath());
  }
  servlet.getMetrics().incrementRequests(1);
  try {
    ResponseBuilder response = Response.ok(getTableList());
    response.cacheControl(cacheControl);
    servlet.getMetrics().incrementSucessfulGetRequests(1);
    return response.build();
  } catch (Exception e) {
    servlet.getMetrics().incrementFailedGetRequests(1);
    return processException(e);
  }
}
项目:personium-core    文件:DavCmpFsImpl.java   
@Override
public final ResponseBuilder putForCreate(final String contentType, final InputStream inputStream) {
    // Locking
    Lock lock = this.lock();
    try {
        // 新規作成時には、作成対象のDavNodeは存在しないため、親DavNodeをリロードして存在確認する。
        // 親DavNodeが存在しない場合:他のリクエストによって削除されたたため、404を返却
        // 親DavNodeが存在するが、作成対象のDavNodeが存在する場合:他のリクエストによって作成されたたtめ、更新処理を実行
        this.parent.load();
        if (!this.parent.exists()) {
            throw PersoniumCoreException.Dav.HAS_NOT_PARENT.params(this.parent.getUrl());
        }

        // 作成対象のDavNodeが存在する場合は更新処理
        if (this.exists()) {
            return this.doPutForUpdate(contentType, inputStream, null);
        }
        // 作成対象のDavNodeが存在しない場合は新規作成処理
        return this.doPutForCreate(contentType, inputStream);
    } finally {
        // UNLOCK
        lock.release();
        log.debug("unlock1");
    }
}
项目:personium-core    文件:AuthzTest.java   
/**
 * LocationヘッダのURLのフラグメントにerror_descriptionが存在しない場合チェックがtrueを返すこと.
 * @throws UnsupportedEncodingException URLのエラー
 */
@Test
public void LocationヘッダのURLのフラグメントにerror_descriptionが存在しない場合チェックがtrueを返すこと() throws UnsupportedEncodingException {
    ResponseBuilder rb = Response.status(Status.FOUND).type(MediaType.APPLICATION_JSON_TYPE);
    StringBuilder sbuf = new StringBuilder(UrlUtils.cellRoot("authz") + "#" + OAuth2Helper.Key.ERROR + "=");
    sbuf.append(URLEncoder.encode("Server Connection Error.", "utf-8"));
    sbuf.append("&" + OAuth2Helper.Key.STATE + "=");
    sbuf.append(URLEncoder.encode("0000000111", "utf-8"));
    sbuf.append("&" + OAuth2Helper.Key.CODE + "=");
    sbuf.append(URLEncoder.encode("PR503-SV-0002", "utf-8"));
    rb.header(HttpHeaders.LOCATION, sbuf.toString());

    Response res = rb.entity("").build();
    AuthzEndPointResourceMock authz = new AuthzEndPointResourceMock(null, null);
    assertTrue(authz.isSuccessAuthorization(res));
}
项目:Equella    文件:FileResourceImpl.java   
/**
 * @param stagingUuid
 * @param parentFolder May or may not be present. This folder must already
 *            exist.
 * @param folder Mandatory
 * @return
 */
@Override
public Response createFolderPost(String stagingUuid, String parentFolder, GenericFileBean folder)
{
    final StagingFile stagingFile = getStagingFile(stagingUuid);
    ensureFileExists(stagingFile, parentFolder);

    final String filename = folder.getFilename();
    final String newPath = PathUtils.filePath(parentFolder, filename);

    boolean exists = fileSystemService.fileExists(stagingFile, newPath);
    fileSystemService.mkdir(stagingFile, newPath);

    // was: .entity(convertFile(stagingFile, newPath, false))
    ResponseBuilder resp = Response.status(exists ? Status.OK : Status.CREATED);
    if( !exists )
    {
        resp = resp.location(itemLinkService.getFileDirURI(stagingFile, URLUtils.urlEncode(newPath, false)));
    }
    return resp.build();
}
项目:Equella    文件:ItemResourceImpl.java   
@Override
public Response headFile(HttpHeaders headers, String uuid, int version, String path)
{
    ItemId itemId = new ItemId(uuid, version);
    checkViewItem(itemId);

    ItemFile itemFile = itemFileService.getItemFile(itemId, null);
    ResponseBuilder builder = makeBlobHeaders(itemFile, path);

    String contentType = mimeService.getMimeTypeForFilename(path);
    builder.type(contentType);

    if( !fileSystemService.fileExists(itemFile, path) )
    {
        return Response.status(Status.NOT_FOUND).build();
    }
    return builder.build();
}
项目:Equella    文件:DefaultOptionsExceptionMapper.java   
@Override
public Response toResponse(DefaultOptionsMethodException arg0)
{
    final ResponseBuilder response = Response.ok();
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Methods", ALL_METHODS);
    response.header("Allow", ALL_METHODS);
    response.header("Access-Control-Allow-Headers", "X-Authorization, Content-Type");
    response.header("Access-Control-Max-Age", TimeUnit.DAYS.toSeconds(1));
    response.header("Access-Control-Expose-Headers", "Location");
    return response.build();
}
项目:plugin-redirect    文件:RedirectResource.java   
/**
 * Redirect to main home page.
 */
protected ResponseBuilder redirectToHome() throws URISyntaxException {
    final String user = securityHelper.getLogin();
    if (isAnonymous(user)) {
        // We know nothing about the user
        return redirectToUrl(configuration.get("redirect.external.home"));
    }

    // Guess the company of this user
    if (companyResource.isUserInternalCommpany()) {
        // Internal user, redirect to the default URL of corporate user
        return redirectToUrl(configuration.get("redirect.internal.home"));
    }

    // Not internal user, redirect to the other home page
    return redirectToUrl(configuration.get("redirect.external.home"));

}
项目:personium-core    文件:AuthzTest.java   
/**
 * LocationヘッダのURLのフラグメントにerrorが存在しない場合チェックがtrueを返すこと.
 * @throws UnsupportedEncodingException URLのエラー
 */
@Test
public void LocationヘッダのURLのフラグメントにerrorが存在しない場合チェックがtrueを返すこと() throws UnsupportedEncodingException {
    ResponseBuilder rb = Response.status(Status.FOUND).type(MediaType.APPLICATION_JSON_TYPE);
    StringBuilder sbuf = new StringBuilder(UrlUtils.cellRoot("authz") + "#");
    sbuf.append("&" + OAuth2Helper.Key.ERROR_DESCRIPTION + "=");
    sbuf.append(URLEncoder.encode("Server Connection Error.", "utf-8"));
    sbuf.append("&" + OAuth2Helper.Key.STATE + "=");
    sbuf.append(URLEncoder.encode("0000000111", "utf-8"));
    sbuf.append("&" + OAuth2Helper.Key.CODE + "=");
    sbuf.append(URLEncoder.encode("PR503-SV-0002", "utf-8"));
    rb.header(HttpHeaders.LOCATION, sbuf.toString());

    Response res = rb.entity("").build();
    AuthzEndPointResourceMock authz = new AuthzEndPointResourceMock(null, null);
    assertTrue(authz.isSuccessAuthorization(res));
}
项目:personium-core    文件:AuthzTest.java   
/**
 * LocationヘッダのURLのフラグメントにエラー情報が全て存在する場合チェックがfalseを返すこと.
 * @throws UnsupportedEncodingException URLのエラー
 */
@Test
public void LocationヘッダのURLのフラグメントにエラー情報が全て存在する場合チェックがfalseを返すこと() throws UnsupportedEncodingException {
    ResponseBuilder rb = Response.status(Status.FOUND).type(MediaType.APPLICATION_JSON_TYPE);
    StringBuilder sbuf = new StringBuilder(UrlUtils.cellRoot("authz") + "#" + OAuth2Helper.Key.ERROR + "=");
    sbuf.append(URLEncoder.encode("Server Connection Error.", "utf-8"));
    sbuf.append("&" + OAuth2Helper.Key.ERROR_DESCRIPTION + "=");
    sbuf.append(URLEncoder.encode("Server Connection Error.", "utf-8"));
    sbuf.append("&" + OAuth2Helper.Key.STATE + "=");
    sbuf.append(URLEncoder.encode("0000000111", "utf-8"));
    sbuf.append("&" + OAuth2Helper.Key.CODE + "=");
    sbuf.append(URLEncoder.encode("PR503-SV-0002", "utf-8"));
    rb.header(HttpHeaders.LOCATION, sbuf.toString());

    Response res = rb.entity("").build();
    AuthzEndPointResourceMock authz = new AuthzEndPointResourceMock(null, null);
    assertFalse(authz.isSuccessAuthorization(res));
}
项目:personium-core    文件:MessageODataResource.java   
/**
 * 受信/送信メッセージEntityを作成する.
 * @param uriInfo URL情報
 * @param reader リクエストボディ
 * @return response情報
 */
protected Response createMessage(UriInfo uriInfo,
        Reader reader) {

    // response用URLに__ctlを追加する
    UriInfo resUriInfo = PersoniumCoreUtils.createUriInfo(uriInfo, 2, "__ctl");

    // Entityの作成を Producerに依頼
    OEntityWrapper oew = getOEntityWrapper(reader, odataResource, CtlSchema.getEdmDataServicesForMessage().build());
    EntityResponse res = getOdataProducer().createEntity(getEntitySetName(), oew);

    // レスポンスボディを生成する
    OEntity ent = res.getEntity();
    MediaType outputFormat = MediaType.APPLICATION_JSON_TYPE;
    List<MediaType> contentTypes = new ArrayList<MediaType>();
    contentTypes.add(MediaType.APPLICATION_JSON_TYPE);
    String key = AbstractODataResource.replaceDummyKeyToNull(ent.getEntityKey().toKeyString());
    String responseStr = renderEntityResponse(resUriInfo, res, "json", contentTypes);

    // 制御コードのエスケープ処理
    responseStr = escapeResponsebody(responseStr);

    ResponseBuilder rb = getPostResponseBuilder(ent, outputFormat, responseStr, resUriInfo, key);
    return rb.build();
}
项目:personium-core    文件:DavCmpFsImpl.java   
@Override
public ResponseBuilder putForUpdate(final String contentType, final InputStream inputStream, String etag) {
    // ロック
    Lock lock = this.lock();
    try {
        // 更新には、更新対象のDavNodeが存在するため、更新対象のDavNodeをリロードして存在確認する。
        // 更新対象のDavNodeが存在しない場合:
        // ・更新対象の親DavNodeが存在しない場合:親ごと消えているため404を返却
        // ・更新対象の親DavNodeが存在する場合:他のリクエストによって削除されたたため、作成処理を実行
        // 更新対象のDavNodeが存在する場合:更新処理を実行
        this.load();
        if (this.metaFile == null) {
            this.parent.load();
            if (this.parent.metaFile == null) {
                throw getNotFoundException().params(this.parent.getUrl());
            }
            return this.doPutForCreate(contentType, inputStream);
        }
        return this.doPutForUpdate(contentType, inputStream, etag);
    } finally {
        // ロックを開放する
        lock.release();
        log.debug("unlock2");
    }
}
项目:personium-core    文件:DavMoveResource.java   
/**
 * MOVEメソッドの処理.
 * @return JAX-RS応答オブジェクト
 */
public Response doMove() {

    // リクエストヘッダのバリデート
    validateHeaders();

    // 移動先のBox情報を取得する
    BoxRsCmp boxRsCmp = getBoxRsCmp();

    // 移動先の情報を生成
    DavDestination davDestination;
    try {
        davDestination = new DavDestination(destination, this.getAccessContext().getBaseUri(), boxRsCmp);
    } catch (URISyntaxException e) {
        // URI 形式でない
        throw PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params(org.apache.http.HttpHeaders.DESTINATION,
                destination);
    }

    // データの更新・削除
    ResponseBuilder response = this.davCmp.move(this.ifMatch, this.overwrite, davDestination);

    return response.build();
}
项目:dremio-oss    文件:TableauResource.java   
/**
 * returns a Tableau export for the dataset
 * @return
 * @throws DatasetNotFoundException
 * @throws NamespaceException
 */
@GET
@Produces({APPLICATION_TDS, APPLICATION_TDS_DRILL})
public Response get(@HeaderParam(HttpHeaders.HOST) String host) throws DatasetNotFoundException, NamespaceException {
  // make sure path exists
  DatasetConfig datasetConfig = namespace.getDataset(datasetPath.toNamespaceKey());

  ResponseBuilder builder =  Response.ok().entity(datasetConfig);
  if (host == null) {
    return builder.build();
  }

  final String hostOnly;
  int portIndex = host.indexOf(":");
  if (portIndex == -1) {
    hostOnly = host;
  } else {
    hostOnly = host.substring(0, portIndex);
  }

  builder.header(WebServer.X_DREMIO_HOSTNAME, hostOnly);

  return builder.build();
}
项目:personium-core    文件:CellSnapshotDavFileResource.java   
/**
 * process DELETE Method and delete this resource.
 * @param ifMatch If-Match header
 * @return JAX-RS response object
 */
@WriteAPI
@DELETE
public Response delete(@HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch) {
    // Check exist
    checkFileExists();
    // Access Control
    davRsCmp.getParent().checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.ROOT);
    ResponseBuilder rb = davRsCmp.getDavCmp().delete(ifMatch, false);
    return rb.build();
}
项目:personium-core    文件:CellSnapshotDavCmpFsImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public ResponseBuilder putForUpdate(String contentType, InputStream inputStream, String etag) {
    Lock lock = this.lock();
    try {
        if (DavCmp.TYPE_NULL.equals(getType())) {
            return this.doPutForCreate(contentType, inputStream);
        } else {
            return this.doPutForUpdate(contentType, inputStream, etag);
        }
    } finally {
        lock.release();
    }
}
项目:ditb    文件:ScannerInstanceResource.java   
@GET
@Produces(MIMETYPE_BINARY)
public Response getBinary(final @Context UriInfo uriInfo) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("GET " + uriInfo.getAbsolutePath() + " as " +
      MIMETYPE_BINARY);
  }
  servlet.getMetrics().incrementRequests(1);
  try {
    Cell value = generator.next();
    if (value == null) {
      LOG.info("generator exhausted");
      return Response.noContent().build();
    }
    ResponseBuilder response = Response.ok(CellUtil.cloneValue(value));
    response.cacheControl(cacheControl);
    response.header("X-Row", Base64.encodeBytes(CellUtil.cloneRow(value)));      
    response.header("X-Column", 
      Base64.encodeBytes(
        KeyValue.makeColumn(CellUtil.cloneFamily(value), CellUtil.cloneQualifier(value))));
    response.header("X-Timestamp", value.getTimestamp());
    servlet.getMetrics().incrementSucessfulGetRequests(1);
    return response.build();
  } catch (IllegalStateException e) {
    if (ScannerResource.delete(id)) {
      servlet.getMetrics().incrementSucessfulDeleteRequests(1);
    } else {
      servlet.getMetrics().incrementFailedDeleteRequests(1);
    }
    servlet.getMetrics().incrementFailedGetRequests(1);
    return Response.status(Response.Status.GONE)
      .type(MIMETYPE_TEXT).entity("Gone" + CRLF)
      .build();
  }
}
项目:ctsms    文件:InventoryResource.java   
@GET
@Path("{id}/files/pdf")
public Response aggregatePDFFiles(@PathParam("id") Long id, @Context UriInfo uriInfo) throws AuthenticationException, AuthorisationException, ServiceException {
    FilePDFVO vo = WebUtil.getServiceLocator().getFileService().aggregatePDFFiles(auth, fileModule, id, null, null, new PSFUriPart(uriInfo));
    // http://stackoverflow.com/questions/9204287/how-to-return-a-png-image-from-jersey-rest-service-method-to-the-browser
    // non-streamed
    ResponseBuilder response = Response.ok(vo.getDocumentDatas(), vo.getContentType().getMimeType());
    response.header(HttpHeaders.CONTENT_LENGTH, vo.getSize());
    return response.build();
}
项目:Celebino    文件:GardenController.java   
/**
 * Get garden by username's user
 * 
 * @param username
 * @return Response
 */
@PermitAll
@GET
@Path("/username/{username}")
@Produces("application/json")
public Response getGardensByUsername(@PathParam("username") String username) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    try {
        List<Garden> gardens = GardenDao.getInstance().getByUsername(username);

        if (gardens != null) {
            builder.status(Response.Status.OK);
            builder.entity(gardens);

        } else {
            builder.status(Response.Status.NOT_FOUND);
        }

    } catch (SQLException exception) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:Celebino    文件:GardenController.java   
/**
 * Get gardens by user id
 * 
 * @param userId
 * @return
 */
@PermitAll
@GET
@Path("/user/{id}")
@Produces("application/json")
public Response getGardensByUserId(@PathParam("id") Long userId) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    try {
        List<Garden> gardens = GardenDao.getInstance().getByUserId(userId);

        if (gardens != null) {
            builder.status(Response.Status.OK);
            builder.entity(gardens);
        } else {
            builder.status(Response.Status.NOT_FOUND);
        }

    } catch (SQLException exception) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:Celebino    文件:GardenController.java   
@PermitAll
@PUT
@Path("/")
@Produces("application/json")
@Consumes("application/json")
public Response update(Garden graden) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    try {
        GardenDao.getInstance().update(graden);
        builder.status(Response.Status.OK).entity(graden);

    } catch (SQLException exception) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }
    return builder.build();

}
项目:personium-core    文件:LogResource.java   
private Response createResponse(final InputStream isInvariable) {
    // ステータスコードを追加
    ResponseBuilder res = Response.status(HttpStatus.SC_OK);
    res.header(HttpHeaders.CONTENT_TYPE, EventUtils.TEXT_CSV);
    res.entity(isInvariable);
    return res.build();
}
项目:Celebino    文件:UserController.java   
/**
 * Get user by username
 * 
 * @param username
 * @return
 */
@PermitAll
@GET
@Path("/username/{username}")
@Produces("application/json")
public Response getUserByUsername(@PathParam("username") String username) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    try {

        User user = UserDao.getInstance().getByUsername(username);

        if (user != null) {

            builder.status(Response.Status.OK);
            builder.entity(user);

        } else {

            builder.status(Response.Status.NOT_FOUND);
        }

    } catch (SQLException exception) {

        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:Celebino    文件:WateringController.java   
/**
 * Cadastra watering
 * 
 * @param Watering
 * @return Response
 */
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(Watering watering) {

    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    Timestamp time = new Timestamp(System.currentTimeMillis());
    watering.setTime(time);
    try {

        Long idWatering = (long) WateringDao.getInstance().insert(watering);
        watering.setId(idWatering);
        builder.status(Response.Status.OK).entity(watering);

    } catch (SQLException e) {

        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:Celebino    文件:GardenStatusController.java   
/**
 * Cadastra GardenStatus
 * 
 * @param GardenStatus
 * @return Response
 */
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(GardenStatus gardenstatus) {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.expires(new Date());

    Timestamp time = new Timestamp(System.currentTimeMillis());
    gardenstatus.setTime(time);

    try {
        Garden garden = GardenDao.getInstance().getById(gardenstatus.getGarden().getId());

        if (garden.getId().equals(null)) {
            GardenDao.getInstance().insertU(gardenstatus.getGarden());
        } else {
            gardenstatus.setGarden(garden);
        }

        Long id = GardenStatusDao.getInstance().insertU(gardenstatus);
        gardenstatus.setId(id);

        System.out.println(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(time.getTime()));
        System.out.println(time.getTime());
        builder.status(Response.Status.OK).entity(gardenstatus);

    } catch (SQLException e) {
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return builder.build();
}
项目:ctsms    文件:ProbandResource.java   
@GET
@Path("{id}/inquiryvalues/{trialId}/pdf")
public Response renderInquiries(@PathParam("id") Long id, @PathParam("trialId") Long trialId, @QueryParam("active") Boolean active,
        @QueryParam("active_signup") Boolean activeSignup, @QueryParam("blank") boolean blank) throws AuthenticationException,
        AuthorisationException, ServiceException {
    InquiriesPDFVO vo = WebUtil.getServiceLocator().getProbandService().renderInquiries(auth, trialId, id, active, activeSignup, blank);
    // http://stackoverflow.com/questions/9204287/how-to-return-a-png-image-from-jersey-rest-service-method-to-the-browser
    // non-streamed
    ResponseBuilder response = Response.ok(vo.getDocumentDatas(), vo.getContentType().getMimeType());
    response.header(HttpHeaders.CONTENT_LENGTH, vo.getSize());
    return response.build();
}
项目:personium-core    文件:DavFileResource.java   
/**
 * process GET Method and retrieve the file content.
 * @param ifNoneMatch If-None-Match Header
 * @param rangeHeaderField Range header
 * @return JAX-RS response object
 */
@GET
public Response get(
        @HeaderParam(HttpHeaders.IF_NONE_MATCH) final String ifNoneMatch,
        @HeaderParam("Range") final String rangeHeaderField
        ) {

    // Access Control
    this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ);

    ResponseBuilder rb = this.davRsCmp.get(ifNoneMatch, rangeHeaderField);
    return rb.build();
}
项目:ctsms    文件:EcrfStatusEntryResource.java   
@GET
@Path("{listEntryId}/ecrfpdf")
public Response renderEcrfs(@PathParam("listEntryId") Long listEntryId,
        @QueryParam("blank") Boolean blank) throws AuthenticationException, AuthorisationException, ServiceException {
    ECRFPDFVO vo = WebUtil.getServiceLocator().getTrialService().renderEcrfs(auth, null, listEntryId, null, blank);
    // http://stackoverflow.com/questions/9204287/how-to-return-a-png-image-from-jersey-rest-service-method-to-the-browser
    // non-streamed
    ResponseBuilder response = Response.ok(vo.getDocumentDatas(), vo.getContentType().getMimeType());
    response.header(HttpHeaders.CONTENT_LENGTH, vo.getSize());
    return response.build();
}
项目:opencps-v2    文件:WorkingUnitManagementImpl.java   
@Override
public Response getLogo(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user,
        ServiceContext serviceContext, long id) {
    WorkingUnitInterface actions = new WorkingUnitActions();

    try {

        File file = actions.getLogo(id, serviceContext);

        FileEntry fileEntry = actions.getFileEntry(id, serviceContext);

        String fileName = Validator.isNotNull(fileEntry) ? fileEntry.getFileName() : StringPool.BLANK;

        ResponseBuilder responseBuilder = Response.ok((Object) file);

        responseBuilder.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                .header("Content-Type", fileEntry.getMimeType());

        return responseBuilder.build();

    } catch (Exception e) {

        ErrorMsg error = new ErrorMsg();
        error.setMessage("file not found!");
        error.setCode(404);
        error.setDescription("file not found!");
        return Response.status(404).entity(error).build();
    }
}
项目:ctsms    文件:TrialResource.java   
@GET
@Path("{id}/files/pdf")
public Response aggregatePDFFiles(@PathParam("id") Long id, @Context UriInfo uriInfo) throws AuthenticationException, AuthorisationException, ServiceException {
    FilePDFVO vo = WebUtil.getServiceLocator().getFileService().aggregatePDFFiles(auth, fileModule, id, null, null, new PSFUriPart(uriInfo));
    // http://stackoverflow.com/questions/9204287/how-to-return-a-png-image-from-jersey-rest-service-method-to-the-browser
    // non-streamed
    ResponseBuilder response = Response.ok(vo.getDocumentDatas(), vo.getContentType().getMimeType());
    response.header(HttpHeaders.CONTENT_LENGTH, vo.getSize());
    return response.build();
}
项目:Equella    文件:FileResourceImpl.java   
@Override
public Response uploadOrReplaceFile(String stagingUuid, String filepath, boolean append, String unzipTo, long size,
    String contentType, InputStream binaryData)
{
    final StagingFile stagingFile = getStagingFile(stagingUuid);

    boolean creating = !fileSystemService.fileExists(stagingFile, filepath);
    try( InputStream bd = binaryData )
    {
        final FileInfo fileInfo = fileSystemService.write(stagingFile, filepath, bd, append);
        final FileBean fileBean = new FileBean();
        fileBean.setFilename(fileInfo.getFilename());
        fileBean.setParent(getParent(stagingFile, filepath));
        fileBean.setSize(fileInfo.getLength());

        // unzip?
        if( !Strings.isNullOrEmpty(unzipTo) )
        {
            fileSystemService.mkdir(stagingFile, unzipTo);
            fileSystemService.unzipFile(stagingFile, filepath, unzipTo);
        }

        // Returns both the file dir entity and the location of the content
        // so that you can know both locations
        ResponseBuilder resp = Response.status(creating ? Status.CREATED : Status.OK)
            .entity(itemLinkService.addLinks(stagingFile, fileBean, filepath));
        if( creating )
        {
            resp.location(itemLinkService.getFileContentURI(stagingFile, URLUtils.urlEncode(filepath, false)));
        }
        return resp.build();
    }
    catch( IOException e )
    {
        throw Throwables.propagate(e);
    }
}
项目:Equella    文件:ItemResourceImpl.java   
private ResponseBuilder makeBlobHeaders(ItemFile itemFile, String filename)
{
    FileInfo fileInfo = fileSystemService.getFileInfo(itemFile, filename);
    ResponseBuilder builder = Response.ok();
    builder.lastModified(new Date(fileSystemService.lastModified(itemFile, filename)));
    builder.header(HttpHeaders.ETAG, fileInfo.getMd5CheckSum());
    builder.header(HttpHeaders.CONTENT_LENGTH, fileInfo.getLength());
    builder.header(HttpHeaders.CONTENT_TYPE, mimeService.getMimeTypeForFilename(fileInfo.getFilename()));
    return builder;
}
项目:Equella    文件:StagingResourceImpl.java   
@Override
public Response completeMultipart(String uuid, String filepath, String uploadId, MultipartCompleteBean completion)
    throws IOException
{
    StagingFile stagingFile = getStagingFile(uuid);
    List<PartBean> parts = completion.getParts();
    int[] partNumbers = new int[parts.size()];
    String[] etags = new String[parts.size()];
    int i = 0;
    for( PartBean partBean : parts )
    {
        partNumbers[i] = partBean.getPartNumber();
        etags[i++] = partBean.getEtag();
    }
    String folderPath = "multipart/" + uploadId;

    if( !fileSystemService.fileExists(stagingFile, folderPath) )
    {
        throw new BadRequestException("Multipart upload doesn't exist: " + uploadId);
    }

    File folder = fileSystemService.getExternalFile(stagingFile, folderPath);
    for( int partNumber : partNumbers )
    {
        fileSystemService.write(stagingFile, filepath,
            fileSystemService.read(stagingFile, folder + "/" + Integer.toString(partNumber)), true);
    }
    fileSystemService.removeFile(stagingFile, folderPath);
    ResponseBuilder resp = Response.ok();
    return resp.build();
}
项目:Equella    文件:StagingResourceImpl.java   
private ResponseBuilder makeResponseHeaders(String uuid, String filepath) throws IOException
{
    ResponseBuilder builder = Response.ok();
    StagingFile handle = new StagingFile(uuid);
    FileInfo fileInfo = fileSystemService.getFileInfo(handle, filepath);

    builder.lastModified(new Date(fileSystemService.lastModified(handle, filepath)));
    builder.header(HttpHeaders.CONTENT_LENGTH, fileInfo.getLength());
    builder.header(HttpHeaders.CONTENT_TYPE, mimeService.getMimeTypeForFilename(fileInfo.getFilename()));
    builder.header(HttpHeaders.ETAG, "\"" + fileSystemService.getMD5Checksum(handle, filepath) + "\"");
    return builder;
}