org.springframework.web.bind.annotation.PathVariable Java Examples

The following examples show how to use org.springframework.web.bind.annotation.PathVariable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestUsers.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@ApiOperation(
    value = "Changing a User's password",
    notes = "If you want to change another User's password, you have to be an admin")
@RequestMapping(
    value = "changepwd/{username}",
    method = RequestMethod.PUT,
    consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.ACCEPTED)
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public void changePasswordOf(
    @PathVariable("username") String username, @RequestBody /*@Valid*/ JsonObject newPwd)
    throws UnauthorizedUserException, PasswordWeakException, NotFoundException,
        NotAllowedException {
  log.debug("Changing password of user " + username);
  if (isAdmin()) {
    JsonObject jsonObject = gson.fromJson(newPwd, JsonObject.class);
    userManagement.changePasswordOf(username, jsonObject.get("new_pwd").getAsString());
  } else {
    throw new NotAllowedException(
        "Forbidden to change password of other users. Only admins can do this.");
  }
}
 
Example #2
Source File: InstancesProxyController.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD,
		RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Flux<InstanceWebProxy.InstanceResponse> endpointProxy(
		@PathVariable("applicationName") String applicationName, HttpServletRequest servletRequest) {
	ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
	String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + APPLICATION_MAPPED_PATH,
			servletRequest);
	URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true)
			.toUri();

	Flux<DataBuffer> cachedBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096)
			.cache();

	return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), uri, request.getMethod(),
			this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(cachedBody));
}
 
Example #3
Source File: UserController.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
/**
 * Fetch users with the given id. <code>http://.../v1/users/{id}</code> will return user with
 * given id.
 *
 * @param id
 * @return A non-null, non-empty collection of users.
 */
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Entity> findById(@PathVariable("id") String id) throws Exception {
  logger.info(String
      .format("user-service findById() invoked:{} for {} ", userService.getClass().getName(),
          id));
  id = id.trim();
  Entity user;
  try {
    user = userService.findById(id);
  } catch (Exception ex) {
    logger.log(Level.WARNING, "Exception raised findById REST Call {0}", ex);
    throw ex;
  }
  return user != null ? new ResponseEntity<>(user, HttpStatus.OK)
      : new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
Example #4
Source File: KaptchaController.java    From WebStack-Guns with MIT License 6 votes vote down vote up
/**
 * 返回图片
 *
 * @author stylefeng
 * @Date 2017/5/24 23:00
 */
@RequestMapping("/{pictureId}")
public void renderPicture(@PathVariable("pictureId") String pictureId, HttpServletResponse response) {
    String path = gunsProperties.getFileUploadPath() + pictureId;
    try {
        byte[] bytes = FileUtil.toByteArray(path);
        response.getOutputStream().write(bytes);
    } catch (Exception e) {
        //如果找不到图片就返回一个默认图片
        try {
            response.sendRedirect("/static/img/github.png");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
 
Example #5
Source File: PaymentController.java    From micro-ecommerce with Apache License 2.0 6 votes vote down vote up
/**
 * Shows the {@link Receipt} for the given order.
 * 
 * @param order
 * @return
 */
@RequestMapping(value = PaymentLinks.RECEIPT, method = GET)
HttpEntity<Resource<Receipt>> showReceipt(@PathVariable("id") Order order) {

	if (order == null || !order.isPaid() || order.isTaken()) {
		return new ResponseEntity<Resource<Receipt>>(HttpStatus.NOT_FOUND);
	}

	Payment payment = paymentService.getPaymentFor(order);

	if (payment == null) {
		return new ResponseEntity<Resource<Receipt>>(HttpStatus.NOT_FOUND);
	}

	return createReceiptResponse(payment.getReceipt());
}
 
Example #6
Source File: TaskController.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
/**
 * 添加候选人
 */
@RequestMapping("task/candidate/add/{taskId}")
@ResponseBody
public String addCandidates(@PathVariable("taskId") String taskId, @RequestParam("userOrGroupIds[]") String[] userOrGroupIds,
                            @RequestParam("type[]") String[] types, HttpServletRequest request) {
    // 设置当前操作人,对于调用活动可以获取到当前操作人
    String currentUserId = UserUtil.getUserFromSession(request.getSession()).getId();
    identityService.setAuthenticatedUserId(currentUserId);

    for (int i = 0; i < userOrGroupIds.length; i++) {
        String type = types[i];
        if (StringUtils.equals("user", type)) {
            taskService.addCandidateUser(taskId, userOrGroupIds[i]);
        } else if (StringUtils.equals("group", type)) {
            taskService.addCandidateGroup(taskId, userOrGroupIds[i]);
        }
    }
    return "success";
}
 
Example #7
Source File: ManageController.java    From PhrackCTF-Platform-Team with Apache License 2.0 6 votes vote down vote up
/**
 * 后台查看用户IP界面
 * 
 * @param id
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/admin/userips/{id}",method={RequestMethod.GET})
public ModelAndView UserIps(@PathVariable long id) throws Exception {
	ModelAndView mv = new ModelAndView("admin/userips");
	Subject currentUser = SecurityUtils.getSubject();
	CommonUtils.setControllerName(request, mv);
	CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv);
	if (CommonUtils.CheckIpBanned(request, bannedIpServices)) {
		currentUser.logout();
		return new ModelAndView("redirect:/showinfo?err=-99");
	}
	
	
	Users userobj = userServices.getUserById(id);
	if (userobj == null) {
		return new ModelAndView("redirect:/showinfo?err=404");
	}
	mv.addObject("currentuser", userobj);
	List<IpLogs> ips = ipLogServices.getAllIpLogsByUserId(userobj.getId());
	
	mv.addObject("ipused", ips);
	mv.setViewName("admin/userips");
	return mv;
}
 
Example #8
Source File: ClusterAssignController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@PostMapping("/all_server/{app}")
public Result<ClusterAppAssignResultVO> apiAssignAllClusterServersOfApp(@PathVariable String app,
                                                                        @RequestBody
                                                                            ClusterAppFullAssignRequest assignRequest) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    if (assignRequest == null || assignRequest.getClusterMap() == null
        || assignRequest.getRemainingList() == null) {
        return Result.ofFail(-1, "bad request body");
    }
    try {
        return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, assignRequest.getClusterMap(),
            assignRequest.getRemainingList()));
    } catch (Throwable throwable) {
        logger.error("Error when assigning full cluster servers for app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example #9
Source File: CubeController.java    From kylin with Apache License 2.0 6 votes vote down vote up
/**
 * Get SQL of a Cube segment
 *
 * @param cubeName    Cube Name
 * @param segmentName Segment Name
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/{cubeName}/segs/{segmentName}/sql", method = { RequestMethod.GET }, produces = {
        "application/json" })
@ResponseBody
public GeneralResponse getSql(@PathVariable String cubeName, @PathVariable String segmentName) {

    checkCubeExists(cubeName);
    CubeInstance cube = cubeService.getCubeManager().getCube(cubeName);

    CubeSegment segment = cube.getSegment(segmentName, null);
    if (segment == null) {
        throw new NotFoundException("Cannot find segment " + segmentName);
    }

    IJoinedFlatTableDesc flatTableDesc = new CubeJoinedFlatTableDesc(segment, true);
    String sql = JoinedFlatTable.generateSelectDataStatement(flatTableDesc);

    GeneralResponse response = new GeneralResponse();
    response.setProperty("sql", sql);

    return response;
}
 
Example #10
Source File: StudentGroupingController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "{grouping}/studentGroupsEnrolledByStudent")
    public @ResponseBody ResponseEntity<String> getStudentGroupsEnrolledByStudent(@PathVariable Grouping grouping) {
        if (!groupingIsOpenForEnrollment(grouping)) {
//            throw new DomainException("error.grouping.notOpenToEnrollment");
            return new ResponseEntity<>(
                    createErrorJson((new DomainException("error.grouping.notOpenToEnrollment")).getLocalizedMessage()),
                    HttpStatus.FORBIDDEN);
        }
        if (!personInGroupingAttends(grouping, AccessControl.getPerson())) {
//            throw new DomainException("error.grouping.notEnroled");
            return new ResponseEntity<>(
                    createErrorJson((new DomainException("error.grouping.notEnroled")).getLocalizedMessage()),
                    HttpStatus.FORBIDDEN);
        }
        return new ResponseEntity<>(view(grouping
                .getStudentGroupsSet()
                .stream()
                .filter(studentGroup -> studentGroup.getAttendsSet().stream()
                        .anyMatch(attends -> attends.getRegistration().getPerson() == AccessControl.getPerson()))).toString(), HttpStatus.OK);
    }
 
Example #11
Source File: ProductController.java    From product-recommendation-system with MIT License 6 votes vote down vote up
/**
 * 处理查询商品的请求
 * @param product 封装了要查询的商品需要满足的条件
 * @param pageNum 第几页
 * @param pageSize 每页多少条
 * @return 封装有商品列表以及分页信息的map集合
 */
@RequestMapping(value="/listProduct/{pageNum}/{pageSize}")
public @ResponseBody Map<String, Object> listProduct(@RequestBody Product product,
	@PathVariable(value="pageNum") Integer pageNum, @PathVariable(value="pageSize") Integer pageSize) {
	Map<String, Object> map = new HashMap<String, Object>();
	
	PageParam pageParam = new PageParam(pageNum, pageSize);
	if (pageNum == null || pageSize == null) {
		pageParam = null;
	}
	
	PageInfo<ProductDTO> productInfo = this.productService.listProductPage(product, pageParam);
	// 1.获取商品列表
	List<ProductDTO> productList = productInfo.getList();
	// 2.获取分页条
	String pageBar = PageUtils.pageStr(productInfo, PRODUCT_QUERY_METHOD_PAGE);
	// 3.统计公有多少条记录
	Long listSize = productInfo.getTotal();
	
	map.put(FRONT_PRODUCTLIST_ATTR, productList);
	map.put(FRONT_LISTSIZE_ATTR, listSize);
	map.put(FRONT_PAGEBAR_ATTR, pageBar);
	
	return map;
}
 
Example #12
Source File: GreetingController.java    From spring-security-fundamentals with Apache License 2.0 6 votes vote down vote up
/**
 * Web service endpoint to fetch a single Greeting entity by primary key
 * identifier.
 * 
 * If found, the Greeting is returned as JSON with HTTP status 200.
 * 
 * If not found, the service returns an empty response body with HTTP status
 * 404.
 * 
 * @param id A Long URL path variable containing the Greeting primary key
 *        identifier.
 * @return A ResponseEntity containing a single Greeting object, if found,
 *         and a HTTP status code as described in the method comment.
 */
@RequestMapping(
        value = "/api/greetings/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Greeting> getGreeting(@PathVariable("id") Long id) {
    logger.info("> getGreeting id:{}", id);

    Greeting greeting = greetingService.findOne(id);
    if (greeting == null) {
        return new ResponseEntity<Greeting>(HttpStatus.NOT_FOUND);
    }

    logger.info("< getGreeting id:{}", id);
    return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
 
Example #13
Source File: Web3ApiController.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "getTransactionByHash",
        notes = "Get transaction information based on transaction hash")
@ApiImplicitParam(name = "transHash", value = "transHash", required = true, dataType = "String",
        paramType = "path")
@GetMapping("/transaction/{transHash}")
public Transaction getTransactionByHash(@PathVariable int groupId,
        @PathVariable String transHash) {
    return web3ApiService.getTransactionByHash(groupId, transHash);
}
 
Example #14
Source File: DemoController.java    From spring-boot-starter-samples with Apache License 2.0 5 votes vote down vote up
@BusinessLog(module = LogConstant.Module.N01, business = LogConstant.BUSINESS.N010001, opt = BusinessType.SELECT)
@RequestMapping(value = "to/detail/{id}", produces = "text/html; charset=UTF-8")
public String detail(@PathVariable(value = "id") String id, HttpServletRequest request, Model model) throws Exception {

	DemoModel rtModel = getDemoService().getModel(id);
	if (rtModel != null) {
		model.addAttribute("rtModel", rtModel);
		//model.addAttribute("xxxList", getDemoService().getxxxList());
	}
	return "html/demo/detail-demo";
}
 
Example #15
Source File: UserController.java    From txle with Apache License 2.0 5 votes vote down vote up
@GetMapping("/deductMoneyFromUser/{userid}/{balance}")
String deductMoneyFromUser(@PathVariable("userid") long userid, @PathVariable("balance") double balance) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    System.err.println("[" + sdf.format(new Date()) + "] Executing method '" + this.getClass() + ".testGlobalTransaction'. \t\tParameters[userid = " + userid + ", balance = " + balance + "]");

    System.err.println(request.getHeader(GLOBAL_TX_ID_KEY));

    return userService.updateBalanceByUserId(userid, balance);
}
 
Example #16
Source File: AppDeploymentClientResource.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/rest/activiti/apps/redeploy/{deploymentId}/{replaceAppId}",method=RequestMethod.GET, produces = "application/json")
public JsonNode redeployApp(HttpServletRequest request, HttpServletResponse httpResponse, @PathVariable String deploymentId, @PathVariable String replaceAppId){
    ServerConfig serverConfig = retrieveServerConfig();
    ServerConfig targetServerConfig = retrieveServerConfig();
    try {
        return clientService.redeployReplaceApp(httpResponse, serverConfig, targetServerConfig, deploymentId, replaceAppId);
    } catch (IOException e) {
        throw new InternalServerErrorException("Could not redeploy app: " + e.getMessage());
    }
}
 
Example #17
Source File: UserApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * DELETE /user/{username} : Delete user
 * This can only be done by the logged in user.
 *
 * @param username The name that needs to be deleted (required)
 * @return Invalid username supplied (status code 400)
 *         or User not found (status code 404)
 */
@ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", })
@ApiResponses(value = { 
    @ApiResponse(code = 400, message = "Invalid username supplied"),
    @ApiResponse(code = 404, message = "User not found") })
@RequestMapping(value = "/user/{username}",
    method = RequestMethod.DELETE)
default Mono<ResponseEntity<Void>> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username, ServerWebExchange exchange) {
    return getDelegate().deleteUser(username, exchange);
}
 
Example #18
Source File: AbstractCrudController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = "/{uid}/{property}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE )
public void replaceCollectionItemsJson(
    @PathVariable( "uid" ) String pvUid,
    @PathVariable( "property" ) String pvProperty,
    HttpServletRequest request ) throws Exception
{
    List<T> objects = getEntity( pvUid );
    IdentifiableObjects identifiableObjects = renderService.fromJson( request.getInputStream(), IdentifiableObjects.class );

    collectionService.clearCollectionItems( objects.get( 0 ), pvProperty );
    collectionService.addCollectionItems( objects.get( 0 ), pvProperty, Lists.newArrayList( identifiableObjects.getIdentifiableObjects() ) );
}
 
Example #19
Source File: StreamDeploymentController.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
/**
 * Request un-deployment of an existing stream.
 *
 * @param name the name of an existing stream (required)
 * @return response without a body
 */
@RequestMapping(value = "/{name}", method = RequestMethod.DELETE)
public ResponseEntity<Void> undeploy(@PathVariable("name") String name) {
	this.repository.findById(name)
			.orElseThrow(() -> new NoSuchStreamDefinitionException(name));
	this.streamService.undeployStream(name);
	return new ResponseEntity<>(HttpStatus.OK);
}
 
Example #20
Source File: ConnectionResource.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
/**
 * GET  /connections/:id : get the "id" connection.
 *
 * @param id the id of the connectionDTO to retrieve
 * @return the ResponseEntity with status 200 (OK) and with body the connectionDTO, or with status 404 (Not Found)
 */
@GetMapping("/connections/{id}")
@Timed
public ResponseEntity<ConnectionDTO> getConnection(@PathVariable Long id) {
    log.debug("REST request to get Connection : {}", id);
    ConnectionDTO connectionDTO = connectionService.findOne(id);
    return ResponseUtil.wrapOrNotFound(Optional.ofNullable(connectionDTO));
}
 
Example #21
Source File: MerchantController.java    From txle with Apache License 2.0 5 votes vote down vote up
@GetMapping("/payMoneyToMerchant/{merchantid}/{balance}")
public String payMoneyToMerchant(@PathVariable("merchantid") long merchantid, @PathVariable("balance") double balance) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    System.err.println("[" + sdf.format(new Date()) + "] Executing method '" + this.getClass() + ".payMoneyToMerchant'. \t\tParameters[merchantid = " + merchantid + ", balance = " + balance + "]");
    merchantService.updateBalanceByMerchantId(merchantid, balance);
    return TxleConstants.OK;
}
 
Example #22
Source File: WorkbasketController.java    From taskana with Apache License 2.0 5 votes vote down vote up
@PutMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION)
@Transactional(rollbackFor = Exception.class)
public ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>>
    setDistributionTargetsForWorkbasketId(
        @PathVariable(value = "workbasketId") String sourceWorkbasketId,
        @RequestBody List<String> targetWorkbasketIds)
        throws WorkbasketNotFoundException, NotAuthorizedException {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug(
        "Entry to getTasksStatusReport(workbasketId= {}, targetWorkbasketIds´= {})",
        sourceWorkbasketId,
        targetWorkbasketIds);
  }

  workbasketService.setDistributionTargets(sourceWorkbasketId, targetWorkbasketIds);

  List<WorkbasketSummary> distributionTargets =
      workbasketService.getDistributionTargets(sourceWorkbasketId);
  ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>> response =
      ResponseEntity.ok(
          workbasketSummaryRepresentationModelAssembler.toDistributionTargetPageModel(
              distributionTargets, null));
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Exit from getTasksStatusReport(), returning {}", response);
  }

  return response;
}
 
Example #23
Source File: _Recorder.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/batch/{record}", method = RequestMethod.DELETE)
public void deleteBatch(HttpServletRequest request, HttpServletResponse response, @PathVariable("record") Object record, String ids) {

	Long recordId = recordService.getRecordID(record, false);
	Map<String, String> requestMap = prepareParams(request, recordId);

	String[] idArray = ids.split(",");
	for (String id : idArray) {
		exeDelete(recordId, EasyUtils.obj2Long(id), requestMap);
	}
	printSuccessMessage();
}
 
Example #24
Source File: ConsumerController.java    From Kafdrop with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "getConsumer", notes = "Get topic and partition details for a consumer group")
@ApiResponses(value = {
      @ApiResponse(code = 200, message = "Success", response = ConsumerVO.class),
      @ApiResponse(code = 404, message = "Invalid consumer group")
})
@RequestMapping(path = "{groupId:.+}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public @ResponseBody ConsumerVO getConsumer(@PathVariable("groupId") String groupId) throws Exception
{
   final ConsumerVO consumer = kafkaMonitor.getConsumer(groupId)
         .orElseThrow(() -> new ConsumerNotFoundException(groupId));

   return consumer;
}
 
Example #25
Source File: SundialController.java    From Milkomeda with MIT License 5 votes vote down vote up
@RequestMapping("add/{orderNo}")
public Object add(@PathVariable("orderNo") Long orderNo) {
    TOrder tOrder = new TOrder();
    tOrder.setOrderNo(orderNo);
    tOrder.setCreateTime(new Date());
    tOrder.setProductId(1L);
    tOrder.setProductName("测试");
    tOrder.setUserId(122L);
    dataSourceService.insert(tOrder);
    return tOrder;
}
 
Example #26
Source File: AvatarApiController.java    From lemon with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "{username}", produces = MediaType.IMAGE_PNG_VALUE)
public void avatar(
        @PathVariable("username") String username,
        @RequestParam(value = "width", required = false, defaultValue = "16") int width,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String tenantId = tenantHolder.getTenantId();

    InputStream is = userAvatarService.viewAvatarByUsername(username,
            width, tenantId).getInputStream();

    response.setContentType("image/png");
    IOUtils.copy(is, response.getOutputStream());
}
 
Example #27
Source File: MessageConversationController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = "/{mcUid}/{msgUid}/attachments/{fileUid}", method = RequestMethod.GET )
public void getAttachment(
    @PathVariable( value = "mcUid" ) String mcUid,
    @PathVariable( value = "msgUid" ) String msgUid,
    @PathVariable( value = "fileUid" ) String fileUid,
    HttpServletResponse response )
    throws WebMessageException
{
    User user = currentUserService.getCurrentUser();

    Message message = getMessage( mcUid, msgUid, user );

    FileResource fr = fileResourceService.getFileResource( fileUid );

    if ( message == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "No message found with id '" + msgUid + "' for message conversation with id '" + mcUid + "'" ) );
    }

    boolean attachmentExists = message.getAttachments().stream().filter( att -> att.getUid().equals( fileUid ) ).count() == 1;

    if ( fr == null || !attachmentExists )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "No messageattachment found with id '" + fileUid + "'" ) );
    }

    if ( !fr.getDomain().equals( FileResourceDomain.MESSAGE_ATTACHMENT ))
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Invalid messageattachment." ) );
    }

    fileResourceUtils.configureFileResourceResponse( response, fr );
}
 
Example #28
Source File: Export.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/report/{reportId}")
public void exportReport(HttpServletResponse response, 
           @PathVariable("reportId") Long reportId) {
	
	Report report = reportService.getReport(reportId);
	List<Report> list = reportService.getReportsByGroup(reportId, Environment.getUserId());
	String json = EasyUtils.obj2Json(list);
	
	String fileName = report.getName() + ".json";
       String exportPath = DataExport.getExportPath() + "/" + fileName;

	// 先输出内容到服务端的导出文件中
       FileHelper.writeFile(exportPath, json, false);
       DataExport.downloadFileByHttp(response, exportPath);
}
 
Example #29
Source File: AdminConfigurationController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/admin/configuration/payment/{provider}/connect/{orgId}")
public String oAuthRedirectToAuthorizationURL(Principal principal,
                                              @PathVariable("orgId") Integer orgId,
                                              @PathVariable("provider") String provider,
                                              HttpSession session) {
    if(CONNECT_PROVIDERS.contains(provider) && userManager.isOwnerOfOrganization(userManager.findUserByUsername(principal.getName()), orgId)) {
        var connectURL = getConnector(provider).getConnectURL(orgId);
        session.setAttribute(provider+CONNECT_STATE_PREFIX +orgId, connectURL.getState());
        session.setAttribute(provider+CONNECT_ORG, orgId);
        return "redirect:" + connectURL.getAuthorizationUrl();
    }
    return REDIRECT_ADMIN;
}
 
Example #30
Source File: AnkushHadoopClusterCreation.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Home error.
 *
 * @param model the model
 * @param clusterId the cluster id
 * @return the string
 */
@RequestMapping(value = "/home/{clusterId}", method = RequestMethod.GET)
public String homeError(ModelMap model,@PathVariable("clusterId") String clusterId) {
	logger.info("Inside Error Hadoop Cluster  view");
	model.addAttribute("title", "dashboard");
	model.addAttribute("cssFiles", cssFiles);
	model.addAttribute("jsFiles", jsFiles);
	model.addAttribute("clusterId", clusterId);
	return "hadoop/hadoop-home";
}