repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
magicsky/sya
src/test/java/com/github/magicsky/sya/examples/ibinding/ICPPNamespaceAliasExample.java
956
package com.github.magicsky.sya.examples.ibinding; import com.github.magicsky.sya.ast.visitors.ASTNamesVisitor; import com.github.magicsky.sya.checkers.BaseTest; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceAlias; /** * @author */ public class ICPPNamespaceAliasExample extends BaseTest { // namespace A { int x; } // namespace B = A; // int f(){ B::x; } public void testExample() { IASTTranslationUnit translationUnit = parseCPP(getCommentAbove()); ASTNamesVisitor namesVisitor = new ASTNamesVisitor(); translationUnit.accept(namesVisitor); ICPPNamespace A = (ICPPNamespace) namesVisitor.getNames().get(0).resolveBinding(); ICPPNamespace B = (ICPPNamespace) namesVisitor.getNames().get(2).resolveBinding(); assertSame(((ICPPNamespaceAlias) B).getBinding(), A); } }
apache-2.0
Mykaelos/MykaelosUnityLibrary
Camera/CameraResolutionChange.cs
1002
using System; using UnityEngine; /** * Fires the ResolutionChanged if the screen width or height changes. * * Example on how to use: * GetComponent<CameraResolutionChange>().ResolutionChanged += OnResolutionChanged; * * private void OnResolutionChanged() { * // Do something with the new resolution, like update the camera position/distance. * } */ public class CameraResolutionChange : MonoBehaviour { private Vector2 Resolution; private void Awake() { Resolution = new Vector2(Screen.width, Screen.height); } private void Update() { if (Resolution.x != Screen.width || Resolution.y != Screen.height) { OnResolutionChanged(); Resolution.x = Screen.width; Resolution.y = Screen.height; } } #region ResolutionChanged Event public event Action ResolutionChanged; protected void OnResolutionChanged() { ResolutionChanged?.Invoke(); } #endregion ResolutionChanged Event }
apache-2.0
thiloplanz/jmockmongo
src/main/java/jmockmongo/DeleteHandler.java
929
/** * Copyright (c) 2012, Thilo Planz. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License, Version 2.0 * as published by the Apache Software Foundation (the "License"). * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * You should have received a copy of the License along with this program. * If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package jmockmongo; import org.bson.BSONObject; public interface DeleteHandler { public Result handleDelete(String database, String collection, boolean singleRemove, BSONObject selector); }
apache-2.0
JohnCny/TY_NEW
src/java/com/cardpay/pccredit/customer/web/MaintenanceController.java
27790
/** * */ package com.cardpay.pccredit.customer.web; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.cardpay.pccredit.customer.constant.CustomerInforConstant; import com.cardpay.pccredit.customer.constant.MaintenanceConstant; import com.cardpay.pccredit.customer.constant.MaintenanceEndResultEnum; import com.cardpay.pccredit.customer.constant.MarketingCreateWayEnum; import com.cardpay.pccredit.customer.filter.CustomerInforFilter; import com.cardpay.pccredit.customer.filter.MaintenanceFilter; import com.cardpay.pccredit.customer.model.CustomerInfor; import com.cardpay.pccredit.customer.model.Maintenance; import com.cardpay.pccredit.customer.model.MaintenanceAction; import com.cardpay.pccredit.customer.model.MaintenanceLog; import com.cardpay.pccredit.customer.service.CustomerInforService; import com.cardpay.pccredit.customer.service.MaintenanceService; import com.cardpay.pccredit.datapri.constant.DataPriConstants; import com.cardpay.pccredit.manager.service.ManagerBelongMapService; import com.cardpay.pccredit.manager.web.AccountManagerParameterForm; import com.cardpay.pccredit.manager.web.SysOrganizationForm; import com.cardpay.pccredit.riskControl.constant.RiskCustomerCollectionEnum; import com.wicresoft.jrad.base.auth.IUser; import com.wicresoft.jrad.base.auth.JRadModule; import com.wicresoft.jrad.base.auth.JRadOperation; import com.wicresoft.jrad.base.constant.JRadConstants; import com.wicresoft.jrad.base.database.model.QueryResult; import com.wicresoft.jrad.base.web.JRadModelAndView; import com.wicresoft.jrad.base.web.controller.BaseController; import com.wicresoft.jrad.base.web.result.JRadPagedQueryResult; import com.wicresoft.jrad.base.web.result.JRadReturnMap; import com.wicresoft.jrad.base.web.security.LoginManager; import com.wicresoft.jrad.base.web.utility.WebRequestHelper; import com.wicresoft.util.date.DateHelper; import com.wicresoft.util.spring.Beans; import com.wicresoft.util.spring.mvc.mv.AbstractModelAndView; import com.wicresoft.util.web.RequestHelper; /** * @author shaoming * * 2014年11月11日 下午2:27:27 */ @Controller @RequestMapping("/customer/maintenance/*") @JRadModule("customer.maintenance") public class MaintenanceController extends BaseController{ @Autowired private MaintenanceService maintenanceService; @Autowired private ManagerBelongMapService managerBelongMapService; @Autowired private CustomerInforService customerInforService; /** * 浏览维护计划信息页面 * * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "browse.page", method = { RequestMethod.GET }) @JRadOperation(JRadOperation.BROWSE) public AbstractModelAndView browse(@ModelAttribute MaintenanceFilter filter, HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_browse", request); filter.setRequest(request); IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); //查询客户经理 List<AccountManagerParameterForm> forms = maintenanceService.findSubListManagerByManagerId(user); String customerManagerId = filter.getCustomerManagerId(); QueryResult<MaintenanceForm> result = null; if(customerManagerId!=null && !customerManagerId.equals("")){ result = maintenanceService.findMaintenancePlansList(filter); }else{ if(forms.size()>0){ filter.setCustomerManagerIds(forms); result = maintenanceService.findMaintenancePlansList(filter); }else{ //直接返回页面 return mv; } } JRadPagedQueryResult<MaintenanceForm> pagedResult = new JRadPagedQueryResult<MaintenanceForm>(filter, result); mv.addObject(PAGED_RESULT, pagedResult); mv.addObject("forms", forms); return mv; } /** * 增加维护计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "create.page") @JRadOperation(JRadOperation.CREATE) public AbstractModelAndView create(HttpServletRequest request) { IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String userId = user.getId(); String str [] = RequestHelper.getStringValue(request, ID).split("/"); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_create", request); MaintenanceWeb m = new MaintenanceWeb(); m.setAppId(str[0]); MaintenanceForm maintenance = maintenanceService.findMaintenAndAppInfo(m); mv.addObject("maintenance",maintenance); mv.addObject("appId", str[0]); mv.addObject("userId",userId); mv.addObject("customerManagerId",str[1]); return mv; } /** * 修改维护计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "change.page") @JRadOperation(JRadOperation.CHANGE) public AbstractModelAndView change(HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_change", request); String str [] = RequestHelper.getStringValue(request, ID).split("/"); if (StringUtils.isNotEmpty(str[0])) { MaintenanceForm maintenance = maintenanceService.findMaintenanceById(str[0]); mv.addObject("maintenance", maintenance); mv.addObject("appId",str[1]); } return mv; } /** * 显示维护计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "display.page") @JRadOperation(JRadOperation.DISPLAY) public AbstractModelAndView display(HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_display", request); String [] str = RequestHelper.getStringValue(request, ID).split("/"); String maintenanceId = str[0]; String appId = str[1]; if (StringUtils.isNotEmpty(maintenanceId)) { MaintenanceWeb m = new MaintenanceWeb(); m.setId(maintenanceId); m.setAppId(appId); MaintenanceForm maintenance = maintenanceService.findMaintenance(m); List<MaintenanceWeb> maintenanceActions = maintenanceService.findMaintenanceActionByMaintenanceId(maintenanceId); mv.addObject("maintenanceWeb", m); mv.addObject("maintenance", maintenance); mv.addObject("maintenanceActions",maintenanceActions); mv.addObject("appId",appId); } return mv; } /** * 显示维护计划列表页面 * @param request * @return */ @ResponseBody @RequestMapping(value = "displayInfo.page", method = { RequestMethod.GET }) @JRadOperation(JRadOperation.BROWSE) public AbstractModelAndView displayInfo(@ModelAttribute MaintenanceFilter filter,HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_displayInfo", request); String [] str = RequestHelper.getStringValue(request, ID).split("/"); String appId = str[0]; filter.setAppId(appId); filter.setRequest(request); QueryResult<MaintenanceWeb> result = maintenanceService.findMaintenanceWebPlansByFilter(filter); for(int i=0;i<result.getItems().size();i++){ MaintenanceWeb web = (MaintenanceWeb)result.getItems().get(i); if(web!=null){ if("nextmaintain".equals(web.getEndResult())){ result.getItems().get(i).setEndResult("继续维护"); }else if("maintaining".equals(web.getEndResult())){ result.getItems().get(i).setEndResult("维护中"); }else if("complete".equals(web.getEndResult())){ result.getItems().get(i).setEndResult("维护完成"); }else{ result.getItems().get(i).setEndResult("维护中"); } } } JRadPagedQueryResult<MaintenanceWeb> pagedResult = new JRadPagedQueryResult<MaintenanceWeb>(filter, result); mv.addObject(PAGED_RESULT, pagedResult); mv.addObject("appId", appId); return mv; } /** * 添加催收计划 * @param form * @param request * @return */ @ResponseBody @RequestMapping(value = "insert.json") @JRadOperation(JRadOperation.CREATE) public JRadReturnMap insert(@ModelAttribute MaintenanceForm form, HttpServletRequest request) { //boolean flag = maintenanceService.checkRepeat(form.getCustomerId(),MaintenanceEndResultEnum.maintaining); JRadReturnMap returnMap = WebRequestHelper.requestValidation(getModuleName(), form); // if(!flag){ if (returnMap.isSuccess()) { try { Maintenance maintenance = form.createModel(Maintenance.class); IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String createdBy = user.getId(); maintenance.setCreatedBy(createdBy); String customerManagerId = maintenance.getCustomerManagerId(); if(customerManagerId!=null && customerManagerId.equals(createdBy)){ maintenance.setCreateWay(MarketingCreateWayEnum.myself.toString());; }else{ maintenance.setCreateWay(MarketingCreateWayEnum.manager.toString());; } String id = maintenanceService.insertMaintenance(maintenance); returnMap.put(RECORD_ID, id); returnMap.addGlobalMessage(CREATE_SUCCESS); }catch (Exception e) { returnMap.put(JRadConstants.MESSAGE, DataPriConstants.SYS_EXCEPTION_MSG); returnMap.put(JRadConstants.SUCCESS, false); return WebRequestHelper.processException(e); } } // }else{ // returnMap.setSuccess(false); // returnMap.addGlobalError(MaintenanceConstant.alreadyExists); // } return returnMap; } /** * 修改维护计划 * @param form * @param request * @return */ @ResponseBody @RequestMapping(value = "update.json") @JRadOperation(JRadOperation.CHANGE) public JRadReturnMap update(@ModelAttribute MaintenanceForm form, HttpServletRequest request) { JRadReturnMap returnMap = WebRequestHelper.requestValidation(getModuleName(), form); if (returnMap.isSuccess()) { try { String createWay = maintenanceService.findMaintenanceById(form.getId()).getCreateWay(); if(createWay!=null && createWay.equals(RiskCustomerCollectionEnum.system.toString())){ returnMap.setSuccess(false); returnMap.addGlobalError(CustomerInforConstant.UPDATEERROR); return returnMap; } IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String modifiedBy = user.getId(); Maintenance maintenance = form.createModel(Maintenance.class); maintenance.setModifiedBy(modifiedBy); boolean flag=maintenanceService.updateMaintenance(maintenance); if(flag){ returnMap.put(RECORD_ID, maintenance.getId()); returnMap.addGlobalMessage(CHANGE_SUCCESS); }else{ returnMap.setSuccess(false); returnMap.addGlobalError(CustomerInforConstant.UPDATEERROR); } }catch (Exception e) { returnMap.put(JRadConstants.MESSAGE, DataPriConstants.SYS_EXCEPTION_MSG); returnMap.put(JRadConstants.SUCCESS, false); return WebRequestHelper.processException(e); } } return returnMap; } /** * 增加催收实施计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "createAction.page") @JRadOperation(JRadOperation.CREATE) public AbstractModelAndView createAction(HttpServletRequest request) { String maintenanceId = RequestHelper.getStringValue(request, ID); String appId = RequestHelper.getStringValue(request, "appId"); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_action_create", request); mv.addObject("maintenanceId",maintenanceId); mv.addObject("appId",appId); return mv; } /** * 添加维护计划实施信息 * @param form * @param request * @return */ @ResponseBody @RequestMapping(value = "insertAction.json") @JRadOperation(JRadOperation.CREATE) public JRadReturnMap insertAction(@ModelAttribute MaintenanceForm form, HttpServletRequest request) { JRadReturnMap returnMap = WebRequestHelper.requestValidation(getModuleName(), form); if (returnMap.isSuccess()) { try { Maintenance maintenance = new Maintenance(); String endResult= form.getEndResult(); String maintenanceId = form.getMaintenancePlanId(); String appId = form.getAppId(); maintenance.setId(maintenanceId); maintenance.setEndResult(endResult); /*修改催收计划最终结果*/ boolean flag = maintenanceService.updateMaintenancePassive(maintenance); if(flag){ /*在当前计划下添加一条新的实施信息记录*/ MaintenanceAction maintenanceAction = new MaintenanceAction(); IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String createdBy = user.getId(); String maintenanceEndTime = form.getMaintenanceEndTime(); String maintenanceStartTime = form.getMaintenanceStartTime(); maintenanceAction.setCreatedBy(createdBy); if(maintenanceEndTime!=null && !maintenanceEndTime.equals("")){ maintenanceAction.setMaintenanceEndTime(DateHelper.getDateFormat(maintenanceEndTime, "yyyy-MM-dd HH:mm:ss")); } if(maintenanceStartTime!=null && !maintenanceStartTime.equals("")){ maintenanceAction.setMaintenanceStartTime(DateHelper.getDateFormat(maintenanceStartTime,"yyyy-MM-dd HH:mm:ss")); } maintenanceAction.setMaintenancePlanId(form.getMaintenancePlanId()); maintenanceAction.setMaintenanceResult(form.getMaintenanceResult()); maintenanceAction.setMaintenanceWay(form.getMaintenanceWay()); String id = maintenanceService.insertMaintenanceAction(maintenanceAction); /*若最终结果为继续维护*/ String maintenancePlanId = ""; if(endResult.equals(MaintenanceEndResultEnum.nextmaintain.toString())){ /*新增一条新的计划,计划内容与当前计划相同,最终结果为维护中*/ maintenancePlanId = maintenanceService.copyMaintenancePlan(maintenanceId, MaintenanceEndResultEnum.maintaining, createdBy); /*返回最初维护计划页面*/ returnMap.put(ID, maintenanceId+"/"+appId); returnMap.put(RECORD_ID,maintenancePlanId); }else{ /*返回维护计划详细信息页面*/ returnMap.put(ID, maintenanceId+"/"+appId); returnMap.put(RECORD_ID, id); } returnMap.put(JRadConstants.MESSAGE, endResult); returnMap.addGlobalMessage(CREATE_SUCCESS); }else{ returnMap.setSuccess(false); returnMap.addGlobalError(CustomerInforConstant.UPDATEERROR); } }catch (Exception e) { returnMap.put(JRadConstants.MESSAGE, DataPriConstants.SYS_EXCEPTION_MSG); returnMap.put(JRadConstants.SUCCESS, false); return WebRequestHelper.processException(e); } } return returnMap; } /** * 修改催收实施计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "changeAction.page") @JRadOperation(JRadOperation.CHANGE) public AbstractModelAndView changeAction(HttpServletRequest request) { String id = RequestHelper.getStringValue(request, ID); String appId = RequestHelper.getStringValue(request, "appId"); MaintenanceAction maintenanceAction = maintenanceService.findMaintenanceActionById(id); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_action_change", request); mv.addObject("maintenanceAction",maintenanceAction); mv.addObject("appId",appId); return mv; } /** * 修改催收实施计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "displayAction.page") @JRadOperation(JRadOperation.CHANGE) public AbstractModelAndView displayAction(HttpServletRequest request) { String id = RequestHelper.getStringValue(request, ID); String appId = RequestHelper.getStringValue(request, "appId"); MaintenanceAction maintenanceAction = maintenanceService.findMaintenanceActionById(id); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_action_browe", request); mv.addObject("maintenanceAction",maintenanceAction); mv.addObject("appId",appId); return mv; } /** * 修改催收计划实施信息 * @param form * @param request * @return */ @ResponseBody @RequestMapping(value = "updateAction.json") @JRadOperation(JRadOperation.CHANGE) public JRadReturnMap updateAction(@ModelAttribute MaintenanceForm form, HttpServletRequest request) { JRadReturnMap returnMap = WebRequestHelper.requestValidation(getModuleName(), form); if (returnMap.isSuccess()) { try { IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String modifiedBy = user.getId(); String maintenanceStartTime = form.getMaintenanceStartTime(); String maintenanceEndTime = form.getMaintenanceEndTime(); String appId = form.getAppId(); MaintenanceAction maintenanceAction = new MaintenanceAction(); maintenanceAction.setModifiedBy(modifiedBy); maintenanceAction.setId(form.getId()); maintenanceAction.setMaintenancePlanId(form.getMaintenancePlanId()); maintenanceAction.setMaintenanceWay(form.getMaintenanceWay()); maintenanceAction.setMaintenanceResult(form.getMaintenanceResult()); maintenanceAction.setMaintenanceStartTime(DateHelper.getDateFormat(maintenanceStartTime, "yyyy-MM-dd HH:mm:ss")); maintenanceAction.setMaintenanceEndTime(DateHelper.getDateFormat(maintenanceEndTime, "yyyy-MM-dd HH:mm:ss")); boolean flag=maintenanceService.updateMaintenanceAction(maintenanceAction); if(flag){ returnMap.put(ID, maintenanceAction.getMaintenancePlanId()+"/"+appId); returnMap.put(RECORD_ID, maintenanceAction.getId()); returnMap.addGlobalMessage(CHANGE_SUCCESS); }else{ returnMap.setSuccess(false); returnMap.addGlobalError(CustomerInforConstant.UPDATEERROR); } }catch (Exception e) { returnMap.put(JRadConstants.MESSAGE, DataPriConstants.SYS_EXCEPTION_MSG); returnMap.put(JRadConstants.SUCCESS, false); return WebRequestHelper.processException(e); } } return returnMap; } @RequestMapping(value = "getManager.json",method = RequestMethod.GET) public void getManager(HttpServletRequest request,PrintWriter printWriter){ try { IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String userId = user.getId(); List<AccountManagerParameterForm> accountManagerParameterForms = managerBelongMapService.findSubManagerBelongMapByManagerId(userId); JSONArray json = new JSONArray(); json = JSONArray.fromObject(accountManagerParameterForms); printWriter.write(json.toString()); printWriter.flush(); printWriter.close(); }catch(Exception e){ e.printStackTrace(); } } @RequestMapping(value = "getCustomer.json",method = RequestMethod.GET) public void getCustomer(HttpServletRequest request,PrintWriter printWriter){ try { String userId = RequestHelper.getStringValue(request, ID); List<CustomerInfor> customers = customerInforService.findCustomerByManagerId(userId); JSONArray json = new JSONArray(); json = JSONArray.fromObject(customers); printWriter.write(json.toString()); printWriter.flush(); printWriter.close(); }catch(Exception e){ e.printStackTrace(); } } /* *//** * 浏览维护计划日志页面 * * @param filter * @param request * @return *//* @ResponseBody @RequestMapping(value = "log.page", method = { RequestMethod.GET }) @JRadOperation(JRadOperation.BROWSE) public AbstractModelAndView log(@ModelAttribute CustomerInforFilter filter, HttpServletRequest request) { filter.setRequest(request); IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); //查询下属客户经理 List<AccountManagerParameterForm> forms = maintenanceService.findSubListManagerByManagerId(user); if(forms.size()>0){ filter.setCustomerManagerIds(forms); }else{ filter.setCustomerManagerIds(null); } QueryResult<MaintenanceLog> result = customerInforService.findCustomerByFilter(filter); JRadPagedQueryResult<MaintenanceLog> pagedResult = new JRadPagedQueryResult<MaintenanceLog>(filter, result); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_log", request); mv.addObject(PAGED_RESULT, pagedResult); mv.addObject("forms", forms); return mv; }*/ /** * 浏览维护计划日志页面 * * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "log.page", method = { RequestMethod.GET }) @JRadOperation(JRadOperation.BROWSE) public AbstractModelAndView log(@ModelAttribute CustomerInforFilter filter, HttpServletRequest request) { filter.setRequest(request); JRadModelAndView mv; IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); filter.setUserId(user.getId()); QueryResult<CustomerInforFilter> result = customerInforService.findUpdateCustormer(filter); JRadPagedQueryResult<CustomerInforFilter> pagedResult = new JRadPagedQueryResult<CustomerInforFilter>(filter, result); mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_log", request); mv.addObject(PAGED_RESULT, pagedResult); return mv; } /** * 浏览查找维护计划日志页面 * * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "log1.page", method = { RequestMethod.GET }) @JRadOperation(JRadOperation.BROWSE) public AbstractModelAndView log1(@ModelAttribute CustomerInforFilter filter, HttpServletRequest request) { filter.setRequest(request); JRadModelAndView mv; IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); filter.setUserId(user.getId()); filter.setCardId(request.getParameter("cardId")+"%"); filter.setChineseName(request.getParameter("name")+"%"); QueryResult<CustomerInforFilter> result = customerInforService.findUpdateCustormer1(filter); JRadPagedQueryResult<CustomerInforFilter> pagedResult = new JRadPagedQueryResult<CustomerInforFilter>(filter, result); mv = new JRadModelAndView("/customer/maintenance/maintenance_plan_log", request); mv.addObject(PAGED_RESULT, pagedResult); return mv; } /** * 维护计划列表 * * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "log_info.page", method = { RequestMethod.GET }) @JRadOperation(JRadOperation.BROWSE) public AbstractModelAndView log_info(@ModelAttribute MaintenanceFilter filter, HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_log_info", request); String ids = RequestHelper.getStringValue(request, ID); String customerId = ids.split("@")[0]; String productId = ids.split("@")[1]; filter.setRequest(request); // filter.setCustomerId(customerId); // filter.setProductId(productId); String appId = maintenanceService.getAppId(customerId, productId); filter.setAppId(appId); QueryResult<MaintenanceWeb> result = maintenanceService.findMaintenanceWebPlansByFilter(filter); JRadPagedQueryResult<MaintenanceWeb> pagedResult = new JRadPagedQueryResult<MaintenanceWeb>(filter, result); mv.addObject(PAGED_RESULT, pagedResult); mv.addObject("appId", appId); return mv; } /** * 显示维护计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "log_display.page") @JRadOperation(JRadOperation.DISPLAY) public AbstractModelAndView log_display(HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_log_display", request); String [] str = RequestHelper.getStringValue(request, ID).split("/"); String maintenanceId = str[0]; String appId = str[1]; if (StringUtils.isNotEmpty(maintenanceId)) { MaintenanceWeb m = new MaintenanceWeb(); m.setAppId(appId); m.setId(maintenanceId); MaintenanceForm maintenance = maintenanceService.findMaintenance(m); List<MaintenanceWeb> maintenanceActions = maintenanceService.findMaintenanceActionByMaintenanceId(maintenanceId); mv.addObject("maintenanceWeb", m); mv.addObject("maintenance", maintenance); mv.addObject("maintenanceActions",maintenanceActions); } return mv; } /** * 增加催收实施计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "log_createAction.page") @JRadOperation(JRadOperation.CREATE) public AbstractModelAndView log_createAction(HttpServletRequest request) { String maintenanceId = RequestHelper.getStringValue(request, ID); String appId = RequestHelper.getStringValue(request, "appId"); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_log_action_create", request); mv.addObject("maintenanceId",maintenanceId); mv.addObject("appId",appId); return mv; } /** * 修改催收实施计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "log_changeAction.page") @JRadOperation(JRadOperation.CHANGE) public AbstractModelAndView log_changeAction(HttpServletRequest request) { String id = RequestHelper.getStringValue(request, ID); String appId = RequestHelper.getStringValue(request, "appId"); MaintenanceAction maintenanceAction = maintenanceService.findMaintenanceActionById(id); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_log_action_change", request); mv.addObject("maintenanceAction",maintenanceAction); mv.addObject("appId",appId); return mv; } /** * 增加维护计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "log_create.page") @JRadOperation(JRadOperation.CREATE) public AbstractModelAndView log_create(HttpServletRequest request) { IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String userId = user.getId(); String appId= RequestHelper.getStringValue(request, ID); JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_log_create", request); MaintenanceWeb m = new MaintenanceWeb(); m.setAppId(appId); MaintenanceForm maintenance = maintenanceService.findMaintenAndAppInfo(m); mv.addObject("maintenance",maintenance); mv.addObject("appId", appId); mv.addObject("userId",userId); return mv; } /** * 修改维护计划信息页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "log_change.page") @JRadOperation(JRadOperation.CHANGE) public AbstractModelAndView log_change(HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/customer/maintenance/maintenance_log_change", request); String str [] = RequestHelper.getStringValue(request, ID).split("/"); if (StringUtils.isNotEmpty(str[0])) { MaintenanceForm maintenance = maintenanceService.findMaintenanceById(str[0]); String productId = maintenanceService.getProductId(str[1]); mv.addObject("maintenance", maintenance); mv.addObject("productId", productId); } return mv; } }
apache-2.0
ikkentim/SampSharp
src/SampSharp.GameMode/SAMP/Commands/CommandAttribute.cs
2662
// SampSharp // Copyright 2020 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace SampSharp.GameMode.SAMP.Commands { /// <summary> /// Indicates a method is a player command. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class CommandAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="CommandAttribute" /> class. /// </summary> /// <param name="name">The name of the command.</param> public CommandAttribute(string name) : this(new[] {name}) { } /// <summary> /// Initializes a new instance of the <see cref="CommandAttribute" /> class. /// </summary> /// <param name="names">The names of the command.</param> public CommandAttribute(params string[] names) { Names = names; IgnoreCase = true; } /// <summary> /// Gets the names. /// </summary> public string[] Names { get; } /// <summary> /// Gets or sets a value indicating whether this command is a command group help command. The names of this command will be /// ignored, this command will be executed if the command group of this command is run without a specific command. /// </summary> public bool IsGroupHelp { get; set; } /// <summary> /// Gets or sets a value indicating whether to ignore the case of the command. /// </summary> public bool IgnoreCase { get; set; } /// <summary> /// Gets or sets the shortcut. /// </summary> public string Shortcut { get; set; } /// <summary> /// Gets or sets the display name. /// </summary> public string DisplayName { get; set; } /// <summary> /// Gets or sets the usage message. /// </summary> public string UsageMessage { get; set; } /// <summary> /// Gets or sets the permission checker type. /// </summary> public Type PermissionChecker { get; set; } } }
apache-2.0
kr9ly/bright-fw
bright-fw/src/main/java/net/kr9ly/brightfw/dependency/module/helper/image/ActivityGlideImageHelperDelegate.java
681
package net.kr9ly.brightfw.dependency.module.helper.image; import android.support.v4.app.FragmentActivity; import net.kr9ly.brightfw.helper.hook.HookHelper; import net.kr9ly.brightfw.helper.image.ActivityGlideImageHelper; import net.kr9ly.brightfw.helper.image.ImageHelper; public class ActivityGlideImageHelperDelegate implements ImageHelperDelegate { private FragmentActivity activity; public ActivityGlideImageHelperDelegate(FragmentActivity activity) { this.activity = activity; } @Override public ImageHelper imageHelper(HookHelper hookHelper) { return new ActivityGlideImageHelper(hookHelper, activity); } }
apache-2.0
GoogleCloudPlatform/inspec-gcp-pci-profile
controls/2.3.rb
2460
# Copyright 2019 The inspec-gcp-pci-profile Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. gcp_project_id = input('gcp_project_id') pci_version = input('pci_version') pci_url = input('pci_url') pci_section = '2.3' title "[PCI-DSS-#{pci_version}][#{pci_section}] Encrypt all non-console administrative access using strong cryptography." # 2.3 pci_req = "#{pci_section}" pci_req_title = "Encrypt all non-console administrative access using strong cryptography." pci_req_guidance = "If non-console (including remote) administration does not use secure authentication and encrypted communications, sensitive administrative or operational level information (like administrator’s IDs and passwords) can be revealed to an eavesdropper. A malicious individual could use this information to access the network, become administrator, and steal data. Clear-text protocols (such as HTTP, telnet, etc.) do not encrypt traffic or logon details, making it easy for an eavesdropper to intercept this information." pci_req_coverage = 'partial' control "pci-dss-#{pci_version}-#{pci_req}" do title "[PCI-DSS #{pci_version}][#{pci_req}] #{pci_req_title}" desc "#{pci_req_guidance}" impact 1.0 tag project: "#{gcp_project_id}" tag standard: "pci-dss" tag pci_version: "#{pci_version}" tag pci_section: "#{pci_section}" tag pci_req: "#{pci_req}" tag coverage: "#{pci_req_coverage}" ref "PCI DSS #{pci_version}", url: "#{pci_url}" # Ensure telnet is not allowed by any non-GKE firewall rule google_compute_firewalls(project: gcp_project_id).where(firewall_direction: 'INGRESS').where { firewall_name !~ /^gke-/ }.firewall_names.each do |firewall_name| describe "[#{gcp_project_id}] #{firewall_name}" do subject { google_compute_firewall(project: gcp_project_id, name: firewall_name) } it "should not allow Telnet (tcp/23)" do subject.allow_port_protocol?('23', 'tcp').should_not eq(true) end end end end
apache-2.0
amazon-mws-unofficial/mws-fulfillment-inbound-shipment
src/FBAInboundServiceMWS/Model/InboundShipmentPlanRequestItem.php
6791
<?php /******************************************************************************* * Copyright 2009-2015 Amazon Services. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ******************************************************************************* * PHP Version 5 * @category Amazon * @package FBA Inbound Service MWS * @version 2010-10-01 * Library Version: 2015-10-22 * Generated: Thu Oct 22 01:02:38 GMT 2015 */ /** * @see FBAInboundServiceMWS_Model */ require_once (dirname(__FILE__) . '/../Model.php'); /** * FBAInboundServiceMWS_Model_InboundShipmentPlanRequestItem * * Properties: * <ul> * * <li>SellerSKU: string</li> * <li>ASIN: string</li> * <li>Condition: string</li> * <li>Quantity: int</li> * <li>QuantityInCase: int</li> * * </ul> */ class FBAInboundServiceMWS_Model_InboundShipmentPlanRequestItem extends FBAInboundServiceMWS_Model { public function __construct($data = null) { $this->_fields = array ( 'SellerSKU' => array('FieldValue' => null, 'FieldType' => 'string'), 'ASIN' => array('FieldValue' => null, 'FieldType' => 'string'), 'Condition' => array('FieldValue' => null, 'FieldType' => 'string'), 'Quantity' => array('FieldValue' => null, 'FieldType' => 'int'), 'QuantityInCase' => array('FieldValue' => null, 'FieldType' => 'int'), ); parent::__construct($data); } /** * Get the value of the SellerSKU property. * * @return String SellerSKU. */ public function getSellerSKU() { return $this->_fields['SellerSKU']['FieldValue']; } /** * Set the value of the SellerSKU property. * * @param string sellerSKU * @return this instance */ public function setSellerSKU($value) { $this->_fields['SellerSKU']['FieldValue'] = $value; return $this; } /** * Check to see if SellerSKU is set. * * @return true if SellerSKU is set. */ public function isSetSellerSKU() { return !is_null($this->_fields['SellerSKU']['FieldValue']); } /** * Set the value of SellerSKU, return this. * * @param sellerSKU * The new value to set. * * @return This instance. */ public function withSellerSKU($value) { $this->setSellerSKU($value); return $this; } /** * Get the value of the ASIN property. * * @return String ASIN. */ public function getASIN() { return $this->_fields['ASIN']['FieldValue']; } /** * Set the value of the ASIN property. * * @param string asin * @return this instance */ public function setASIN($value) { $this->_fields['ASIN']['FieldValue'] = $value; return $this; } /** * Check to see if ASIN is set. * * @return true if ASIN is set. */ public function isSetASIN() { return !is_null($this->_fields['ASIN']['FieldValue']); } /** * Set the value of ASIN, return this. * * @param asin * The new value to set. * * @return This instance. */ public function withASIN($value) { $this->setASIN($value); return $this; } /** * Get the value of the Condition property. * * @return String Condition. */ public function getCondition() { return $this->_fields['Condition']['FieldValue']; } /** * Set the value of the Condition property. * * @param string condition * @return this instance */ public function setCondition($value) { $this->_fields['Condition']['FieldValue'] = $value; return $this; } /** * Check to see if Condition is set. * * @return true if Condition is set. */ public function isSetCondition() { return !is_null($this->_fields['Condition']['FieldValue']); } /** * Set the value of Condition, return this. * * @param condition * The new value to set. * * @return This instance. */ public function withCondition($value) { $this->setCondition($value); return $this; } /** * Get the value of the Quantity property. * * @return Integer Quantity. */ public function getQuantity() { return $this->_fields['Quantity']['FieldValue']; } /** * Set the value of the Quantity property. * * @param int quantity * @return this instance */ public function setQuantity($value) { $this->_fields['Quantity']['FieldValue'] = $value; return $this; } /** * Check to see if Quantity is set. * * @return true if Quantity is set. */ public function isSetQuantity() { return !is_null($this->_fields['Quantity']['FieldValue']); } /** * Set the value of Quantity, return this. * * @param quantity * The new value to set. * * @return This instance. */ public function withQuantity($value) { $this->setQuantity($value); return $this; } /** * Get the value of the QuantityInCase property. * * @return Integer QuantityInCase. */ public function getQuantityInCase() { return $this->_fields['QuantityInCase']['FieldValue']; } /** * Set the value of the QuantityInCase property. * * @param int quantityInCase * @return this instance */ public function setQuantityInCase($value) { $this->_fields['QuantityInCase']['FieldValue'] = $value; return $this; } /** * Check to see if QuantityInCase is set. * * @return true if QuantityInCase is set. */ public function isSetQuantityInCase() { return !is_null($this->_fields['QuantityInCase']['FieldValue']); } /** * Set the value of QuantityInCase, return this. * * @param quantityInCase * The new value to set. * * @return This instance. */ public function withQuantityInCase($value) { $this->setQuantityInCase($value); return $this; } }
apache-2.0
mcaprari/smack
source/org/jivesoftware/smackx/muc/Occupant.java
3954
/** * $RCSfile$ * $Revision: 7071 $ * $Date: 2007-02-12 00:59:05 +0000 (Mon, 12 Feb 2007) $ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.muc; import org.jivesoftware.smackx.packet.MUCAdmin; import org.jivesoftware.smackx.packet.MUCUser; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.util.StringUtils; /** * Represents the information about an occupant in a given room. The information will always have * the affiliation and role of the occupant in the room. The full JID and nickname are optional. * * @author Gaston Dombiak */ public class Occupant { // Fields that must have a value private String affiliation; private String role; // Fields that may have a value private String jid; private String nick; Occupant(MUCAdmin.Item item) { super(); this.jid = item.getJid(); this.affiliation = item.getAffiliation(); this.role = item.getRole(); this.nick = item.getNick(); } Occupant(Presence presence) { super(); MUCUser mucUser = (MUCUser) presence.getExtension("x", "http://jabber.org/protocol/muc#user"); MUCUser.Item item = mucUser.getItem(); this.jid = item.getJid(); this.affiliation = item.getAffiliation(); this.role = item.getRole(); // Get the nickname from the FROM attribute of the presence this.nick = StringUtils.parseResource(presence.getFrom()); } /** * Returns the full JID of the occupant. If this information was extracted from a presence and * the room is semi or full-anonymous then the answer will be null. On the other hand, if this * information was obtained while maintaining the voice list or the moderator list then we will * always have a full JID. * * @return the full JID of the occupant. */ public String getJid() { return jid; } /** * Returns the affiliation of the occupant. Possible affiliations are: "owner", "admin", * "member", "outcast". This information will always be available. * * @return the affiliation of the occupant. */ public String getAffiliation() { return affiliation; } /** * Returns the current role of the occupant in the room. This information will always be * available. * * @return the current role of the occupant in the room. */ public String getRole() { return role; } /** * Returns the current nickname of the occupant in the room. If this information was extracted * from a presence then the answer will be null. * * @return the current nickname of the occupant in the room or null if this information was * obtained from a presence. */ public String getNick() { return nick; } public boolean equals(Object obj) { if(!(obj instanceof Occupant)) { return false; } Occupant occupant = (Occupant)obj; return jid.equals(occupant.jid); } public int hashCode() { int result; result = affiliation.hashCode(); result = 17 * result + role.hashCode(); result = 17 * result + jid.hashCode(); result = 17 * result + (nick != null ? nick.hashCode() : 0); return result; } }
apache-2.0
smhoekstra/iaf
JavaSource/nl/nn/adapterframework/core/ManagedStateException.java
1135
/* Copyright 2013 Nationale-Nederlanden Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package nl.nn.adapterframework.core; /** * Exception thrown if a {@link IManagable ManagedObject} like an Adapter or Receiver is in * an unexpected or illegal state. * * @version $Id$ * @author Gerrit van Brakel */ public class ManagedStateException extends IbisException { public ManagedStateException() { super(); } public ManagedStateException(String msg) { super(msg); } public ManagedStateException(String errMsg, Throwable t) { super(errMsg, t); } public ManagedStateException(Throwable t) { super(t); } }
apache-2.0
brolaugh/blog
app/Brolaugh/Model/User.php
653
<?php namespace Brolaugh\Model; use \Brolaugh\Core\Database; class User extends Database { protected $id; public $username; private $password; private $email; public function prepare($id) { $stmt = $this->database_connection->prepare("SELECT * FROM user WHERE id = ?"); $stmt->bind_param('i', $id); $stmt->execute(); $res = $stmt->get_result(); if ($res->num_rows > 0) $this->fillSelfWithData($res->fetch_object()); } protected function fillSelfWithData($data) { $this->id = $data->id; $this->username = $data->username; $this->password = $data->password; $this->email = $data->email; } }
apache-2.0
chridou/almhirt
almhirt-common/src/main/scala/almhirt/aggregates/RebuildsAggregateRootFromTimeline.scala
546
package almhirt.aggregates import almhirt.common._ /** Mix in this trait to rebuild aggregate roots from its lifetime. * It uses the [[AggregateRootEventHandler]] to rebuild the aggregate root. */ trait RebuildsAggregateRootFromTimeline[T <: AggregateRoot, E <: AggregateRootEvent] { self: AggregateRootEventHandler[T, E] ⇒ final def rebuildFromTimeline(timeline: Iterable[E]): AggregateRootLifecycle[T] = if (timeline.isEmpty) { Vacat } else { applyEventsPostnatalis(fromEvent(timeline.head), timeline.tail) } }
apache-2.0
arekk/uke
db/schema.rb
5359
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20190713071420) do create_table "bandplans", force: true do |t| t.decimal "mhz_start", precision: 10, scale: 4, null: false t.decimal "mhz_end", precision: 10, scale: 4, null: false t.decimal "step", precision: 5, scale: 2 t.string "purpose" t.text "description" t.datetime "created_at" t.datetime "updated_at" end add_index "bandplans", ["mhz_start", "mhz_end"], name: "index_bandplans_on_mhz_start_and_mhz_end", using: :btree create_table "frequencies", force: true do |t| t.decimal "mhz", precision: 10, scale: 4 t.decimal "step", precision: 5, scale: 2 t.datetime "created_at" t.datetime "updated_at" end add_index "frequencies", ["mhz"], name: "index_frequencies_on_mhz", using: :btree create_table "frequency_assignments", force: true do |t| t.integer "subject_id" t.string "subject_type" t.integer "frequency_id" t.string "usage", limit: 2 t.datetime "created_at" t.datetime "updated_at" t.integer "uke_import_id" end add_index "frequency_assignments", ["frequency_id"], name: "index_frequency_assignments_on_frequency_id", using: :btree add_index "frequency_assignments", ["subject_type", "subject_id", "usage"], name: "assigned_frequencies_on_subject_usage", using: :btree add_index "frequency_assignments", ["subject_type", "subject_id"], name: "index_frequency_assignments_on_subject_type_and_subject_id", using: :btree add_index "frequency_assignments", ["uke_import_id"], name: "index_frequency_assignments_on_uke_import_id", using: :btree create_table "uke_import_news", force: true do |t| t.integer "uke_import_id" t.integer "uke_station_id" t.datetime "created_at" t.datetime "updated_at" end add_index "uke_import_news", ["uke_import_id", "uke_station_id"], name: "index_uke_import_news_on_uke_import_id_and_uke_station_id", using: :btree add_index "uke_import_news", ["uke_import_id"], name: "index_uke_import_news_on_uke_import_id", using: :btree add_index "uke_import_news", ["uke_station_id"], name: "index_uke_import_news_on_uke_station_id", using: :btree create_table "uke_imports", force: true do |t| t.date "released_on" t.boolean "active", default: false t.datetime "created_at" t.datetime "updated_at" end add_index "uke_imports", ["active"], name: "index_uke_imports_on_active", using: :btree create_table "uke_operators", force: true do |t| t.string "name" t.string "address" t.string "name_unified" t.datetime "created_at" t.datetime "updated_at" end add_index "uke_operators", ["name_unified"], name: "index_uke_operators_on_name_unified", using: :btree create_table "uke_permits", force: true do |t| t.string "number" t.date "valid_to" t.datetime "created_at" t.datetime "updated_at" end add_index "uke_permits", ["valid_to"], name: "index_uke_permits_on_valid_to", using: :btree create_table "uke_stations", force: true do |t| t.string "name" t.string "purpose", limit: 2 t.string "net", limit: 1 t.decimal "lon", precision: 10, scale: 6 t.decimal "lat", precision: 10, scale: 6 t.integer "radius" t.string "location" t.string "location_geocoded" t.decimal "erp", precision: 5, scale: 1 t.decimal "ant_efficiency", precision: 5, scale: 1 t.integer "ant_height" t.string "ant_polarisation", limit: 2 t.boolean "directional" t.integer "uke_operator_id" t.integer "uke_permit_id" t.datetime "created_at" t.datetime "updated_at" t.string "name_unified", null: false t.integer "uke_import_id", default: 1 end add_index "uke_stations", ["lon", "lat"], name: "index_uke_stations_on_lon_and_lat", using: :btree add_index "uke_stations", ["name_unified"], name: "index_uke_stations_on_name_unified", using: :btree add_index "uke_stations", ["uke_import_id"], name: "index_uke_stations_on_uke_import_id", using: :btree add_index "uke_stations", ["uke_operator_id"], name: "index_uke_stations_on_uke_operator_id", using: :btree add_index "uke_stations", ["uke_permit_id"], name: "index_uke_stations_on_uke_permit_id", using: :btree end
apache-2.0
NikoYuwono/retrofit
retrofit/src/test/java/retrofit2/RequestBuilderTest.java
56927
// Copyright 2013 Square, Inc. package retrofit2; import java.io.IOException; import java.lang.reflect.Method; import java.math.BigInteger; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.Buffer; import org.junit.Ignore; import org.junit.Test; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.HEAD; import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Multipart; import retrofit2.http.OPTIONS; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.PartMap; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; import retrofit2.http.Url; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @SuppressWarnings({"UnusedParameters", "unused"}) // Parameters inspected reflectively. public final class RequestBuilderTest { private static final MediaType TEXT_PLAIN = MediaType.parse("text/plain"); @Test public void customMethodNoBody() { class Example { @HTTP(method = "CUSTOM1", path = "/foo") Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("CUSTOM1"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo"); assertThat(request.body()).isNull(); } @Ignore("https://github.com/square/okhttp/issues/229") @Test public void customMethodWithBody() { class Example { @HTTP(method = "CUSTOM2", path = "/foo", hasBody = true) Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("CUSTOM2"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo"); assertBody(request.body(), "hi"); } @Test public void onlyOneEncodingIsAllowedMultipartFirst() { class Example { @Multipart // @FormUrlEncoded // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Only one encoding annotation is allowed.\n for method Example.method"); } } @Test public void onlyOneEncodingIsAllowedFormEncodingFirst() { class Example { @FormUrlEncoded // @Multipart // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Only one encoding annotation is allowed.\n for method Example.method"); } } @Test public void invalidPathParam() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Path("hey!") String thing) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Path parameter name must match \\{([a-zA-Z][a-zA-Z0-9_-]*)\\}." + " Found: hey! (parameter #1)\n for method Example.method"); } } @Test public void pathParamNotAllowedInQuery() throws Exception { class Example { @GET("/foo?bar={bar}") // Call<ResponseBody> method(@Path("bar") String thing) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "URL query string \"bar={bar}\" must not have replace block." + " For dynamic query parameters use @Query.\n for method Example.method"); } } @Test public void multipleParameterAnnotationsNotAllowed() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Body @Query("nope") String o) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multiple Retrofit annotations found, only one allowed. (parameter #1)\n for method Example.method"); } } @interface NonNull {} @Test public void multipleParameterAnnotationsOnlyOneRetrofitAllowed() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Query("maybe") @NonNull Object o) { return null; } } Request request = buildRequest(Example.class, "yep"); assertThat(request.url().toString()).isEqualTo("http://example.com/?maybe=yep"); } @Test public void twoMethodsFail() { class Example { @PATCH("/foo") // @POST("/foo") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Only one HTTP method is allowed. Found: PATCH and POST.\n for method Example.method"); } } @Test public void lackingMethod() { class Example { Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "HTTP method annotation is required (e.g., @GET, @POST, etc.).\n for method Example.method"); } } @Test public void implicitMultipartForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@Part("a") int a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"); } } @Test public void implicitMultipartWithPartMapForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@PartMap Map<String, String> params) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"); } } @Test public void multipartFailsOnNonBodyMethod() { class Example { @Multipart // @GET("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multipart can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"); } } @Test public void multipartFailsWithNoParts() { class Example { @Multipart // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multipart method must contain at least one @Part.\n for method Example.method"); } } @Test public void implicitFormEncodingByFieldForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@Field("a") int a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Field parameters can only be used with form encoding. (parameter #1)\n for method Example.method"); } } @Test public void implicitFormEncodingByFieldMapForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@FieldMap parameters can only be used with form encoding. (parameter #1)\n for method Example.method"); } } @Test public void formEncodingFailsOnNonBodyMethod() { class Example { @FormUrlEncoded // @GET("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"); } } @Test public void formEncodingFailsWithNoParts() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Form-encoded method must contain at least one @Field.\n for method Example.method"); } } @Test public void headersFailWhenEmptyOnMethod() { class Example { @GET("/") // @Headers({}) // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Headers annotation is empty.\n for method Example.method"); } } @Test public void headersFailWhenMalformed() { class Example { @GET("/") // @Headers("Malformed") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Headers value must be in the form \"Name: Value\". Found: \"Malformed\"\n for method Example.method"); } } @Test public void pathParamNonPathParamAndTypedBytes() { class Example { @PUT("/{a}") // Call<ResponseBody> method(@Path("a") int a, @Path("b") int b, @Body int c) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "URL \"/{a}\" does not contain \"{b}\". (parameter #2)\n for method Example.method"); } } @Test public void parameterWithoutAnnotation() { class Example { @GET("/") // Call<ResponseBody> method(String a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "No Retrofit annotation found. (parameter #1)\n for method Example.method"); } } @Test public void nonBodyHttpMethodWithSingleEntity() { class Example { @GET("/") // Call<ResponseBody> method(@Body String o) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Non-body HTTP method cannot contain @Body.\n for method Example.method"); } } @Test public void queryMapMustBeAMap() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap List<String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@QueryMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void queryMapRejectsNullKeys() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Map<String, String> a) { return null; } } Map<String, String> queryParams = new LinkedHashMap<>(); queryParams.put("ping", "pong"); queryParams.put(null, "kat"); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Query map contained null key."); } } @Test public void twoBodies() { class Example { @PUT("/") // Call<ResponseBody> method(@Body String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multiple @Body method annotations found. (parameter #2)\n for method Example.method"); } } @Test public void bodyInNonBodyRequest() { class Example { @Multipart // @PUT("/") // Call<ResponseBody> method(@Part("one") String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Body parameters cannot be used with form or multi-part encoding. (parameter #2)\n for method Example.method"); } } @Test public void get() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void delete() { class Example { @DELETE("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("DELETE"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertNull(request.body()); } @Test public void head() { class Example { @HEAD("/foo/bar/") // Call<Void> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("HEAD"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headWithoutVoidThrows() { class Example { @HEAD("/foo/bar/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "HEAD method must use Void as response type.\n for method Example.method"); } } @Test public void post() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void put() { class Example { @PUT("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("PUT"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void patch() { class Example { @PATCH("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("PATCH"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void options() { class Example { @OPTIONS("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("OPTIONS"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithPathParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "po ng"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/"); assertThat(request.body()).isNull(); } @Test public void getWithUnusedAndInvalidNamedPathParam() { class Example { @GET("/foo/bar/{ping}/{kit,kat}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/%7Bkit,kat%7D/"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedPathParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "po%20ng"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/"); assertThat(request.body()).isNull(); } @Test public void pathParamRequired() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Path parameter \"ping\" value must not be null."); } } @Test public void getWithQueryParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query(value = "pi%20ng", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "p%20o%20n%20g"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?pi%20ng=p%20o%20n%20g"); assertThat(request.body()).isNull(); } @Test public void queryParamOptionalOmitsQuery() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); } @Test public void queryParamOptional() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("foo") String foo, @Query("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "bar", null, "kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?foo=bar&kit=kat"); } @Test public void getWithQueryUrlAndParam() { class Example { @GET("/foo/bar/?hi=mom") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom&ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithQuery() { class Example { @GET("/foo/bar/?hi=mom") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit, @Query("riff") String riff) { return null; } } Request request = buildRequest(Example.class, "pong", "kat", "raff"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/?kit=kat&riff=raff"); assertThat(request.body()).isNull(); } @Test public void getWithQueryThenPathThrows() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Query("kit") String kit, @Path("ping") String ping) { return null; } } try { buildRequest(Example.class, "kat", "pong"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Path parameter must not come after a @Query. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithPathAndQueryQuestionMarkParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong?", "kat?"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong%3F/?kit=kat?"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryAmpersandParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong&", "kat&"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong&/?kit=kat%26"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryHashParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong#", "kat#"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong%23/?kit=kat%23"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") List<Object> keys) { return null; } } List<Object> values = Arrays.<Object>asList(1, 2, null, "three"); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") Object[] keys) { return null; } } Object[] values = { 1, 2, null, "three" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamPrimitiveArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") int[] keys) { return null; } } int[] values = { 1, 2, 3 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=3"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamMap() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryMap Map<String, Object> query) { return null; } } Map<String, Object> params = new LinkedHashMap<>(); params.put("kit", "kat"); params.put("foo", null); params.put("ping", "pong"); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?kit=kat&ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryParamMap() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryMap(encoded = true) Map<String, Object> query) { return null; } } Map<String, Object> params = new LinkedHashMap<>(); params.put("kit", "k%20t"); params.put("foo", null); params.put("pi%20ng", "p%20g"); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?kit=k%20t&pi%20ng=p%20g"); assertThat(request.body()).isNull(); } @Test public void getAbsoluteUrl() { class Example { @GET("http://example2.com/foo/bar/") Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithStringUrl() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithJavaUriUrl() { class Example { @GET Call<ResponseBody> method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create("foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithStringUrlAbsolute() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "https://example2.com/foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithJavaUriUrlAbsolute() { class Example { @GET Call<ResponseBody> method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create("https://example2.com/foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithUrlAbsoluteSameHost() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "http://example.com/foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithNonStringUrlThrows() { class Example { @GET Call<ResponseBody> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Url must be String, java.net.URI, or android.net.Uri type. (parameter #1)\n" + " for method Example.method"); } } @Test public void getUrlAndUrlParamThrows() { class Example { @GET("foo/bar") Call<ResponseBody> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Url cannot be used with @GET URL (parameter #1)\n" + " for method Example.method"); } } @Test public void getWithoutUrlThrows() { class Example { @GET Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Missing either @GET URL or @Url parameter.\n" + " for method Example.method"); } } @Test public void getWithUrlThenPathThrows() { class Example { @GET Call<ResponseBody> method(@Url String url, @Path("hey") String hey) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path parameters may not be used with @Url. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithPathThenUrlThrows() { class Example { @GET Call<ResponseBody> method(@Path("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path can only be used with relative url on @GET (parameter #1)\n" + " for method Example.method"); } } @Test public void getWithQueryThenUrlThrows() { class Example { @GET("foo/bar") Call<ResponseBody> method(@Query("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "hey", "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @Query (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithUrlThenQuery() { class Example { @GET Call<ResponseBody> method(@Url String url, @Query("hey") String hey) { return null; } } Request request = buildRequest(Example.class, "foo/bar/", "hey!"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hey=hey!"); } @Test public void postWithUrl() { class Example { @POST Call<ResponseBody> method(@Url String url, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "hi"); Request request = buildRequest(Example.class, "http://example.com/foo/bar", body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar"); assertBody(request.body(), "hi"); } @Test public void normalPostWithPathParam() { class Example { @POST("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!"); Request request = buildRequest(Example.class, "pong", body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/"); assertBody(request.body(), "Hi!"); } @Test public void emptyBody() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), ""); } @Ignore("https://github.com/square/okhttp/issues/229") @Test public void customMethodEmptyBody() { class Example { @HTTP(method = "CUSTOM", path = "/foo/bar/", hasBody = true) // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("CUSTOM"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), ""); } @Test public void bodyResponseBody() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void bodyRequired() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Body parameter value must not be null."); } } @Test public void bodyWithPathParams() { class Example { @POST("/foo/bar/{ping}/{kit}/") // Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body, @Path("kit") String kit) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!"); Request request = buildRequest(Example.class, "pong", body, "kat"); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/kat/"); assertBody(request.body(), "Hi!"); } @Test public void simpleMultipart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String ping, @Part("kit") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, "pong", RequestBody.create( MediaType.parse("text/plain"), "kat")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("\r\nkat\r\n--"); } @Test public void multipartArray() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String[] ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { new String[] { "pong1", "pong2" } }); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong1\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong2\r\n--"); } @Test public void multipartIterable() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") List<String> ping) { return null; } } Request request = buildRequest(Example.class, Arrays.asList("pong1", "pong2")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong1\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong2\r\n--"); } @Test public void multipartWithEncoding() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part(value = "ping", encoding = "8-bit") String ping, @Part(value = "kit", encoding = "7-bit") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, "pong", RequestBody.create( MediaType.parse("text/plain"), "kat")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("Content-Transfer-Encoding: 7-bit") .contains("\r\nkat\r\n--"); } @Test public void multipartPartMap() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("foo", null); // Should be skipped. params.put("kit", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("\r\nkat\r\n--"); assertThat(bodyString).doesNotContain("name=\"foo\"\r\n"); } @Test public void multipartPartMapWithEncoding() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap(encoding = "8-bit") Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("foo", null); // Should be skipped. params.put("kit", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\nkat\r\n--"); assertThat(bodyString).doesNotContain("name=\"foo\"\r\n"); } @Test public void multipartPartMapRejectsNullKeys() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put(null, RequestBody.create(null, "kat")); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Part map contained null key."); } } @Test public void multipartPartMapMustBeMap() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap List<Object> parts) { return null; } } try { buildRequest(Example.class, Collections.emptyList()); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void multipartNullRemovesPart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String ping, @Part("fizz") String fizz) { return null; } } Request request = buildRequest(Example.class, "pong", null); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong\r\n--"); } @Test public void multipartPartOptional() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") RequestBody ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Multipart body must have at least one part."); } } @Test public void simpleFormEncoded() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "bar", "pong"); assertBody(request.body(), "foo=bar&ping=pong"); } @Test public void formEncodedWithEncodedNameFieldParam() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field(value = "na%20me", encoded = true) String foo) { return null; } } Request request = buildRequest(Example.class, "ba%20r"); assertBody(request.body(), "na%20me=ba%20r"); } @Test public void formEncodedFieldOptional() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping, @Field("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "bar", null, "kat"); assertBody(request.body(), "foo=bar&kit=kat"); } @Test public void formEncodedFieldList() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") List<Object> fields, @Field("kit") String kit) { return null; } } List<Object> values = Arrays.<Object>asList("foo", "bar", null, 3); Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=foo&foo=bar&foo=3&kit=kat"); } @Test public void formEncodedFieldArray() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") Object[] fields, @Field("kit") String kit) { return null; } } Object[] values = { 1, 2, null, "three" }; Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=1&foo=2&foo=three&kit=kat"); } @Test public void formEncodedFieldPrimitiveArray() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") int[] fields, @Field("kit") String kit) { return null; } } int[] values = { 1, 2, 3 }; Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=1&foo=2&foo=3&kit=kat"); } @Test public void formEncodedWithEncodedNameFieldParamMap() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@FieldMap(encoded = true) Map<String, Object> fieldMap) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("k%20it", "k%20at"); fieldMap.put("pin%20g", "po%20ng"); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), "k%20it=k%20at&pin%20g=po%20ng"); } @Test public void formEncodedFieldMap() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@FieldMap Map<String, Object> fieldMap) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put("foo", null); fieldMap.put("ping", "pong"); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), "kit=kat&ping=pong"); } @Test public void fieldMapRejectsNullKeys() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, Object> a) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put("foo", null); fieldMap.put(null, "pong"); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Field map contained null key."); } } @Test public void fieldMapMustBeAMap() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap List<String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@FieldMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void simpleHeaders() { class Example { @GET("/foo/bar/") @Headers({ "ping: pong", "kit: kat" }) Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.get("kit")).isEqualTo("kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamToString() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("kit") BigInteger kit) { return null; } } Request request = buildRequest(Example.class, new BigInteger("1234")); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(1); assertThat(headers.get("kit")).isEqualTo("1234"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParam() { class Example { @GET("/foo/bar/") // @Headers("ping: pong") // Call<ResponseBody> method(@Header("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "kat"); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.get("kit")).isEqualTo("kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("foo") List<String> kit) { return null; } } Request request = buildRequest(Example.class, Arrays.asList("bar", null, "baz")); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values("foo")).containsExactly("bar", "baz"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("foo") String[] kit) { return null; } } Request request = buildRequest(Example.class, (Object) new String[] { "bar", null, "baz" }); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values("foo")).containsExactly("bar", "baz"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void contentTypeAnnotationHeaderOverrides() { class Example { @POST("/") // @Headers("Content-Type: text/not-plain") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "hi"); Request request = buildRequest(Example.class, body); assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain"); } @Test public void contentTypeAnnotationHeaderAddsHeaderWithNoBody() { class Example { @DELETE("/") // @Headers("Content-Type: text/not-plain") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.headers().get("Content-Type")).isEqualTo("text/not-plain"); } @Test public void contentTypeParameterHeaderOverrides() { class Example { @POST("/") // Call<ResponseBody> method(@Header("Content-Type") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "Plain"); Request request = buildRequest(Example.class, "text/not-plain", body); assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain"); } private static void assertBody(RequestBody body, String expected) { assertThat(body).isNotNull(); Buffer buffer = new Buffer(); try { body.writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo(expected); } catch (IOException e) { throw new RuntimeException(e); } } static Request buildRequest(Class<?> cls, Object... args) { final AtomicReference<Request> requestRef = new AtomicReference<>(); okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() { @Override public okhttp3.Call newCall(Request request) { requestRef.set(request); throw new UnsupportedOperationException("Not implemented"); } }; Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://example.com/") .addConverterFactory(new ToStringConverterFactory()) .callFactory(callFactory) .build(); Method method = TestingUtils.onlyMethod(cls); MethodHandler handler = retrofit.loadMethodHandler(method); Call<?> invoke = (Call<?>) handler.invoke(args); try { invoke.execute(); throw new AssertionError(); } catch (UnsupportedOperationException ignored) { return requestRef.get(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AssertionError(e); } } }
apache-2.0
googlearchive/science-journal
OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/whistlepunk/metadata/TriggerListFragment.java
19772
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk.metadata; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SwitchCompat; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.TextView; import com.google.android.apps.forscience.javalib.Success; import com.google.android.apps.forscience.whistlepunk.AccessibilityUtils; import com.google.android.apps.forscience.whistlepunk.AppSingleton; import com.google.android.apps.forscience.whistlepunk.DataController; import com.google.android.apps.forscience.whistlepunk.LoggingConsumer; import com.google.android.apps.forscience.whistlepunk.R; import com.google.android.apps.forscience.whistlepunk.WhistlePunkApplication; import com.google.android.apps.forscience.whistlepunk.accounts.AppAccount; import com.google.android.apps.forscience.whistlepunk.analytics.TrackerConstants; import com.google.android.apps.forscience.whistlepunk.filemetadata.Experiment; import com.google.android.apps.forscience.whistlepunk.filemetadata.SensorLayoutPojo; import com.google.android.apps.forscience.whistlepunk.filemetadata.SensorTrigger; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** The fragment for displaying a list of triggers. */ public class TriggerListFragment extends Fragment { private static final String ARG_ACCOUNT_KEY = "account_key"; private static final String ARG_SENSOR_ID = "sensor_id"; private static final String ARG_EXPERIMENT_ID = "experiment_id"; private static final String ARG_LAYOUT_POSITION = "layout_position"; public static final String ARG_TRIGGER_ORDER = "trigger_order"; private static final String KEY_TRIGGER_ORDER = "trigger_order"; private static final String TAG = "TriggerListFragment"; private static String sensorId; private AppAccount appAccount; private String experimentId; private SensorLayoutPojo sensorLayout; private TriggerListAdapter triggerAdapter; private int layoutPosition; private ArrayList<String> triggerOrder; private Experiment experiment; private boolean needsSave = false; public static TriggerListFragment newInstance( AppAccount appAccount, String sensorId, String experimentId, int position, ArrayList<String> triggerOrder) { TriggerListFragment fragment = new TriggerListFragment(); Bundle args = new Bundle(); args.putString(ARG_ACCOUNT_KEY, appAccount.getAccountKey()); args.putString(ARG_SENSOR_ID, sensorId); args.putString(ARG_EXPERIMENT_ID, experimentId); args.putInt(ARG_LAYOUT_POSITION, position); args.putStringArrayList(ARG_TRIGGER_ORDER, triggerOrder); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); appAccount = WhistlePunkApplication.getAccount(getContext(), getArguments(), ARG_ACCOUNT_KEY); sensorId = getArguments().getString(ARG_SENSOR_ID); experimentId = getArguments().getString(ARG_EXPERIMENT_ID); layoutPosition = getArguments().getInt(ARG_LAYOUT_POSITION); if (savedInstanceState != null) { triggerOrder = savedInstanceState.getStringArrayList(KEY_TRIGGER_ORDER); } else { triggerOrder = getArguments().getStringArrayList(ARG_TRIGGER_ORDER); } setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); String sensorName = AppSingleton.getInstance(getActivity()) .getSensorAppearanceProvider(appAccount) .getAppearance(sensorId) .getName(getActivity()); actionBar.setTitle(getString(R.string.title_fragment_trigger_list, sensorName)); super.onCreateOptionsMenu(menu, inflater); } @Override public void onStart() { super.onStart(); WhistlePunkApplication.getUsageTracker(getActivity()) .trackScreenView(TrackerConstants.SCREEN_TRIGGER_LIST); } @Override public void onResume() { super.onResume(); loadExperiment(); } @Override public void onPause() { if (needsSave) { getDataController() .updateExperiment( experimentId, LoggingConsumer.<Success>expectSuccess(TAG, "updating sensor layout onPause")); } super.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveTriggerOrder(); outState.putStringArrayList(KEY_TRIGGER_ORDER, triggerOrder); } private DataController getDataController() { return AppSingleton.getInstance(getActivity()).getDataController(appAccount); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_trigger_list, parent, false); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } RecyclerView triggerList = (RecyclerView) view.findViewById(R.id.trigger_recycler_view); triggerList.setLayoutManager( new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false)); triggerAdapter = new TriggerListAdapter(this); triggerList.setAdapter(triggerAdapter); FloatingActionButton addButton = (FloatingActionButton) view.findViewById(R.id.add_trigger_button); addButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { launchEditTriggerActivity(null); } }); return view; } private void loadExperiment() { getDataController() .getExperimentById( experimentId, new LoggingConsumer<Experiment>(TAG, "get experiment") { @Override public void success(Experiment experiment) { TriggerListFragment.this.experiment = experiment; for (SensorLayoutPojo layout : experiment.getSensorLayouts()) { if (TextUtils.equals(layout.getSensorId(), sensorId)) { sensorLayout = layout; } } Comparator<SensorTrigger> cp; if (triggerOrder != null) { // If this is not the first load, use the saved order to define a new // order, but insert new triggers at the top. cp = new Comparator<SensorTrigger>() { @Override public int compare(SensorTrigger lhs, SensorTrigger rhs) { int lhsIndex = triggerOrder.indexOf(lhs.getTriggerId()); int rhsIndex = triggerOrder.indexOf(rhs.getTriggerId()); if (lhsIndex == rhsIndex && lhsIndex == -1) { // If they are both not found, they are both new. return Long.compare(rhs.getLastUsed(), lhs.getLastUsed()); } return Integer.compare(lhsIndex, rhsIndex); } }; } else { // Only do this sort on the first load. cp = new Comparator<SensorTrigger>() { @Override public int compare(SensorTrigger lhs, SensorTrigger rhs) { boolean lhsIsActive = isTriggerActive(lhs); boolean rhsIsActive = isTriggerActive(rhs); if (lhsIsActive && !rhsIsActive) { return -1; } if (!lhsIsActive && rhsIsActive) { return 1; } return Long.compare(rhs.getLastUsed(), lhs.getLastUsed()); } }; } // Sort sensor triggers List<SensorTrigger> triggers = experiment.getSensorTriggersForSensor(sensorId); Collections.sort(triggers, cp); triggerAdapter.setSensorTriggers(triggers); } }); } private void launchEditTriggerActivity(SensorTrigger trigger) { Intent intent = new Intent(getActivity(), EditTriggerActivity.class); if (trigger != null) { intent.putExtra(EditTriggerActivity.EXTRA_TRIGGER_ID, trigger.getTriggerId()); } intent.putExtra(EditTriggerActivity.EXTRA_ACCOUNT_KEY, appAccount.getAccountKey()); intent.putExtra(EditTriggerActivity.EXTRA_EXPERIMENT_ID, experimentId); intent.putExtra(EditTriggerActivity.EXTRA_SENSOR_ID, sensorId); // Also send the Sensor Layout and the position so that this fragment can be recreated on // completion, and the order in which the triggers are shown so that the order does not // change when the user gets back. intent.putExtra( EditTriggerActivity.EXTRA_SENSOR_LAYOUT_BLOB, sensorLayout.toProto().toByteArray()); intent.putExtra(TriggerListActivity.EXTRA_LAYOUT_POSITION, layoutPosition); saveTriggerOrder(); intent.putExtra(TriggerListActivity.EXTRA_TRIGGER_ORDER, triggerOrder); getActivity().startActivity(intent); } private void saveTriggerOrder() { triggerOrder = new ArrayList<>(); for (SensorTrigger trigger : triggerAdapter.sensorTriggers) { triggerOrder.add(trigger.getTriggerId()); } } private void deleteTrigger(final SensorTrigger trigger, final int index) { final boolean isActive = isTriggerActive(trigger); final DataController dc = getDataController(); // Set up the undo snackbar. final Snackbar bar = AccessibilityUtils.makeSnackbar( getView(), getActivity().getResources().getString(R.string.sensor_trigger_deleted), Snackbar.LENGTH_SHORT); bar.setAction( R.string.snackbar_undo, new View.OnClickListener() { boolean undone = false; @Override public void onClick(View v) { if (undone) { return; } undone = true; experiment.addSensorTrigger(trigger); if (isActive) { TriggerHelper.addTriggerToLayoutActiveTriggers(sensorLayout, trigger.getTriggerId()); experiment.updateSensorLayout(layoutPosition, sensorLayout); } dc.updateExperiment( experimentId, new LoggingConsumer<Success>(TAG, "update exp: re-add deleted trigger") { @Override public void success(Success value) { if (isActive) { // If it was active, re-add it to the Layout. triggerAdapter.addTriggerAtIndex(trigger, index); } else { triggerAdapter.addTriggerAtIndex(trigger, index); } } }); } }); // Do the deletion, first by removing it from the layout and next by removing it // from the trigger database. TriggerHelper.removeTriggerFromLayoutActiveTriggers(sensorLayout, trigger.getTriggerId()); experiment.removeSensorTrigger(trigger); experiment.updateSensorLayout(layoutPosition, sensorLayout); dc.updateExperiment( experimentId, new LoggingConsumer<Success>(TAG, "delete trigger") { @Override public void success(Success value) { bar.show(); triggerAdapter.removeTrigger(trigger); } }); } private boolean isTriggerActive(SensorTrigger trigger) { return sensorLayout.getActiveSensorTriggerIds().contains(trigger.getTriggerId()); } private void setSensorTriggerActive(SensorTrigger trigger, boolean isActive) { // Don't do the work if the state is already correct. if (isTriggerActive(trigger) == isActive) { return; } // Make a note that a trigger was changed and needs saving, but don't bother updating the // experiment triggers at this time. // Unlike delete (which is updated immediately), and edit (where saving is handled in // another fragment), toggling the active state doesn't need to be written to the database // until we exit the fragment. needsSave = true; if (isActive) { TriggerHelper.addTriggerToLayoutActiveTriggers(sensorLayout, trigger.getTriggerId()); } else { TriggerHelper.removeTriggerFromLayoutActiveTriggers(sensorLayout, trigger.getTriggerId()); } experiment.updateSensorLayout(layoutPosition, sensorLayout); // Note: Last used time is not updated when the trigger is activated / deactivated, and the // list should not be resorted at this time. } private static class TriggerListAdapter extends RecyclerView.Adapter<TriggerListAdapter.ViewHolder> { private static final int VIEW_TYPE_TRIGGER = 0; private static final int VIEW_TYPE_EMPTY = 1; List<SensorTrigger> sensorTriggers = new ArrayList<>(); private final WeakReference<TriggerListFragment> parentReference; public TriggerListAdapter(TriggerListFragment parent) { parentReference = new WeakReference<TriggerListFragment>(parent); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); int viewId; if (viewType == VIEW_TYPE_EMPTY) { viewId = R.layout.empty_trigger_list; } else { viewId = R.layout.trigger_list_item; } return new ViewHolder(inflater.inflate(viewId, parent, false), viewType); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { if (getItemViewType(position) == VIEW_TYPE_EMPTY) { return; } final SensorTrigger trigger = sensorTriggers.get(position); if (parentReference.get() == null) { return; } holder.description.setText( TriggerHelper.buildDescription( trigger, parentReference.get().getActivity(), parentReference.get().appAccount)); holder.menuButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Context context = holder.menuButton.getContext(); PopupMenu popup = new PopupMenu( context, holder.menuButton, Gravity.NO_GRAVITY, R.attr.actionOverflowMenuStyle, 0); popup.getMenuInflater().inflate(R.menu.menu_sensor_trigger, popup.getMenu()); popup.setOnMenuItemClickListener( new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.edit_trigger) { if (parentReference.get() != null) { parentReference.get().launchEditTriggerActivity(trigger); } return true; } else if (item.getItemId() == R.id.delete_trigger) { if (parentReference.get() != null) { parentReference .get() .deleteTrigger(trigger, sensorTriggers.indexOf(trigger)); } return true; } return false; } }); popup.show(); } }); holder.activationSwitch.setOnCheckedChangeListener(null); holder.activationSwitch.setChecked(parentReference.get().isTriggerActive(trigger)); holder.activationSwitch.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (parentReference.get() != null) { parentReference.get().setSensorTriggerActive(trigger, isChecked); } } }); } @Override public void onViewRecycled(TriggerListAdapter.ViewHolder holder) { int position = holder.getAdapterPosition(); if (position == RecyclerView.NO_POSITION) { return; } holder.activationSwitch.setOnCheckedChangeListener(null); holder.menuButton.setOnClickListener(null); } @Override public int getItemCount() { return sensorTriggers.size() == 0 ? 1 : sensorTriggers.size(); } @Override public int getItemViewType(int position) { if (position == 0 && sensorTriggers.size() == 0) { return VIEW_TYPE_EMPTY; } return VIEW_TYPE_TRIGGER; } public void setSensorTriggers(List<SensorTrigger> sensorTriggers) { this.sensorTriggers = sensorTriggers; notifyDataSetChanged(); } public void removeTrigger(SensorTrigger trigger) { if (sensorTriggers.contains(trigger)) { sensorTriggers.remove(trigger); } notifyDataSetChanged(); } public void addTriggerAtIndex(SensorTrigger trigger, int index) { sensorTriggers.add(index, trigger); notifyDataSetChanged(); } public static class ViewHolder extends RecyclerView.ViewHolder { int viewType; TextView description; ImageButton menuButton; SwitchCompat activationSwitch; public ViewHolder(View itemView, int viewType) { super(itemView); this.viewType = viewType; if (viewType == VIEW_TYPE_TRIGGER) { description = (TextView) itemView.findViewById(R.id.trigger_description); menuButton = (ImageButton) itemView.findViewById(R.id.btn_trigger_menu); activationSwitch = (SwitchCompat) itemView.findViewById(R.id.trigger_activation_switch); } } } } }
apache-2.0
rjsteinert/taktaktak
application/views/backend/reports/game/index.php
11513
<?php if($the_action == 'report'): ?> <table class="zebra"> <tr> <th style="text-align:center">Juego</th> <th style="text-align:center">Desarrollador</th> <th style="text-align:center">Total de usuarios</th> <th style="text-align:center">Tiempo (seg)</th> <th style="text-align:center">Score</th> <th style="text-align:center">Veces&nbsp;jugadas</th> </tr> <?php foreach($data as $row) { ?> <tr> <td><?=$row['game']?></td> <td style="text-align:center"><?=$row['developer']?></td> <td style="text-align:center"><?=$row['jugadores']?></td> <td style="text-align:center"><?=$row['tot_time']?></td> <td style="text-align:center"><?=$row['tot_score']?></td> <td style="text-align:center"><?=$row['num_games']?></td> </tr> <?php } ?> </table> <?php else: ?> <script type="text/javascript"> $(document).ready(function() { $("#reporte").click(function() { $('#filters_player').attr('action', 'reports/game/report'); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#game_asc").click(function(){ $('#order_by').val("game ASC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#game_desc").click(function(){ $('#order_by').val("game DESC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#dev_asc").click(function(){ $('#order_by').val("developer ASC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#dev_desc").click(function(){ $('#order_by').val("developer DESC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#score_asc").click(function(){ $('#order_by').val("tot_score ASC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#score_desc").click(function(){ $('#order_by').val("tot_score DESC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#time_asc").click(function(){ $('#order_by').val("tot_time ASC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#time_desc").click(function(){ $('#order_by').val("tot_time DESC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#num_asc").click(function(){ $('#order_by').val("num_games ASC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#num_desc").click(function(){ $('#order_by').val("num_games DESC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#users_asc").click(function(){ $('#order_by').val("jugadores ASC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); $("#users_desc").click(function(){ $('#order_by').val("jugadores DESC"); $('#filters_player').submit(); $('#filters_player').attr('action', ''); }); }); </script> <div class="overview"> <p class="welcome"> <?=__('Reporte de Juegos')?> <br /> <form name="filters_player" id="filters_player" method="get"> <input type="hidden" name="csrf_token" value="<?=Security::token()?>" /> <input type="hidden" name="page" id="page" value="<?=$page?>" /> <input type="hidden" name="order_by" id="order_by" value="" /> <div class="filter"> <label>Estado</label> <select name="state_id"> <option value="">- Seleccione -</option> <?php foreach($states as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['state_id']) { echo "selected"; } ?>><?=$row['name']?></option> <?php endforeach; ?> </select> </div> <div class="filter date"> <label>Rango fechas</label> <input type="text" name="date_start" class="date" value="<?=$params['date_start']?>" /> <input type="text" name="date_end" class="space date" value="<?=$params['date_end']?>" /> </div> <div class="filter"> <label>Desarrollador</label> <select name="developer_id"> <option value="">- Seleccione -</option> <?php foreach($developers as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['developer_id']) { echo "selected"; } ?>><?=$row['title']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <label>Juego</label> <select name="game_id"> <option value="">- Seleccione -</option> <?php foreach($games as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['game_id']) { echo "selected"; } ?>><?=$row['title']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <label>Grado escolar</label> <select name="school_year_id"> <option value="">- Seleccione -</option> <?php foreach($school_years as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['school_year_id']) { echo "selected"; } ?>><?=$row['school_year']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <label>Materia</label> <select name="asignature_id"> <option value="">- Seleccione -</option> <?php foreach($asignatures as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['asignature_id']) { echo "selected"; } ?>><?=$row['asignature']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <label>Actividad favorita</label> <select name="activity_id"> <option value="">- Seleccione -</option> <?php foreach($activities as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['activity_id']) { echo "selected"; } ?>><?=$row['activity']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <label>Como te enteraste</label> <select name="how_id"> <option value="">- Seleccione -</option> <?php foreach($how_id as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['how_id']) { echo "selected"; } ?>><?=$row['how']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <label>Género</label> <select name="gender"> <option value="">- Seleccione -</option> <option value="1" <?php if($params['gender']==1) { echo "selected"; } ?>>niño</option> <option value="2" <?php if($params['gender']==2) { echo "selected"; } ?>>niña</option> <option value="3" <?php if($params['gender']==3) { echo "selected"; } ?>>adulto</option> </select> </div> <div class="filter"> <label>Campaña origen</label> <select name="source_id"> <option value="">- Seleccione -</option> <?php foreach($source_id as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['source_id']) { echo "selected"; } ?>><?=$row['source']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <label>Sub Origen</label> <select name="location_id"> <option value="">- Seleccione -</option> <?php foreach($location_id as $row): ?> <option value="<?=$row['id']?>" <?php if($row['id']==$params['location_id']) { echo "selected"; } ?>><?=$row['location']?></option> <?php endforeach; ?> </select> </div> <div class="filter"> <input type="submit" value="Buscar" class="submit"> </div> </form> <div class="filter"><input type="button" id="reporte" name="reporte" value="Exportar reporte" class="submit"></div> </p> <p style="width: 100%; height: 20px;float: left;">&nbsp;</p> <input type="hidden" name="order_by1" id="order_by1" value="" /> <div style="float: left; width: 900px;"> <!--<h3><?=__('Información del sitio')?></h3>--> <table class="zebra"> <?echo $page_links;?> <tr> <th>Juego<img align="right" src="../assets/images/backend/bullet_arrow_down.png" id="game_desc"/><img id="game_asc" align="right" src="../assets/images/backend/bullet_arrow_up.png" /></th> <th>Desarrollador<img align="right" src="../assets/images/backend/bullet_arrow_down.png" id="dev_desc" /><img id="dev_asc" align="right" src="../assets/images/backend/bullet_arrow_up.png" /></th> <th style="text-align:center">Total de usuarios<img align="right" src="../assets/images/backend/bullet_arrow_down.png" id="users_desc" /><img id="users_asc" align="right" src="../assets/images/backend/bullet_arrow_up.png" /></th> <th style="text-align:center">Tiempo (seg)<img align="right" src="../assets/images/backend/bullet_arrow_down.png" id="time_desc" /><img id="time_asc" align="right" src="../assets/images/backend/bullet_arrow_up.png" /></th> <th style="text-align:center">Score<img align="right" src="../assets/images/backend/bullet_arrow_down.png" id="score_desc" /><img id="score_asc" align="right" src="../assets/images/backend/bullet_arrow_up.png" /></th> <th style="text-align:center">Veces&nbsp;jugadas<img align="right" src="../assets/images/backend/bullet_arrow_down.png" id="num_desc" /><img id="num_asc" align="right" src="../assets/images/backend/bullet_arrow_up.png" /></th> </tr> <?php foreach($data as $row) { ?> <tr> <td><?=$row['game']?></td> <td><?=$row['developer']?></td> <td style="text-align:center"><?=$row['jugadores']?></td> <td style="text-align:center"><?=$row['tot_time']?></td> <td style="text-align:center"><?=$row['tot_score']?></td> <td style="text-align:center"><?=$row['num_games']?></td> </tr> <?php } ?> </table> </div> </div> <?php endif; ?>
apache-2.0
omnypay/omnypay-sdk-android
ExampleApp/OmnyPayAllSdkDemo/src/main/java/net/omnypay/sdk/allsdkdemo/model/AuthenticationRequestParam.java
3720
/** * Copyright 2016 OmnyPay Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.omnypay.sdk.allsdkdemo.model; /** * This class is the model representation of AuthenticationRequestParam */ import com.google.gson.annotations.SerializedName; public class AuthenticationRequestParam { @SerializedName("merchant-id") private String merchantId = null; @SerializedName("username") private String username = null; @SerializedName("password") private String password = null; public AuthenticationRequestParam merchantId(String merchantId) { this.merchantId = merchantId; return this; } /** * Get merchantId * @return merchantId **/ public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public AuthenticationRequestParam username(String username) { this.username = username; return this; } /** * Get username * @return username **/ public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public AuthenticationRequestParam password(String password) { this.password = password; return this; } /** * Get password * @return password **/ public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AuthenticationRequestParam that = (AuthenticationRequestParam) o; if (merchantId != null ? !merchantId.equals(that.merchantId) : that.merchantId != null) return false; if (username != null ? !username.equals(that.username) : that.username != null) return false; return password != null ? password.equals(that.password) : that.password == null; } @Override public int hashCode() { int result = merchantId != null ? merchantId.hashCode() : 0; result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AuthenticationRequestParam {\n"); sb.append(" merchantId: ").append(toIndentedString(merchantId)).append("\n"); sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
drostron/quasar
js/src/test/scala/quasar/jscore/jscore.scala
6189
/* * Copyright 2014–2017 SlamData Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package quasar.jscore import slamdata.Predef._ import quasar.RenderTree.ops._ import quasar.TreeMatchers import quasar.fp._ import quasar.javascript.Js import org.specs2.scalaz._ import scalaz._, Scalaz._ class JsCoreSpecs extends quasar.Qspec with TreeMatchers with ScalazMatchers { "toJs" should { "de-sugar Let as AnonFunDecl" in { val let = Let(Name("a"), BinOp(Add, ident("c"), ident("d")), BinOp(Mult, ident("a"), ident("a"))) let.toJs must_== Js.Call( Js.AnonFunDecl(List("a"), List(Js.Return(Js.BinOp("*", Js.Ident("a"), Js.Ident("a"))))), List(Js.BinOp("+", Js.Ident("c"), Js.Ident("d")))) } "de-sugar nested Lets as single AnonFunDecl" in { val let = Let( Name("a"), Literal(Js.Num(1, false)), Let( Name("b"), Literal(Js.Num(1, false)), BinOp(Add, ident("a"), ident("a")))) let.toJs must_== Js.Call( Js.AnonFunDecl( List("a", "b"), List(Js.Return(Js.BinOp("+", Js.Ident("a"), Js.Ident("b"))))), List(Js.Num(1, false))) }.pendingUntilFixed "don't null-check method call on newly-constructed instance" in { val expr = Call(Select(New(Name("Date"), List[JsCore]()), "getUTCSeconds"), List()) expr.toJs.pprint(0) must_= "(new Date()).getUTCSeconds()" } "don't null-check method call on newly-constructed Array" in { val expr = Call(Select(Arr(List(Literal(Js.Num(0, false)), Literal(Js.Num(1, false)))), "indexOf"), List(ident("x"))) expr.toJs.pprint(0) must_= "[0, 1].indexOf(x)" } "splice obj constructor" in { val expr = SpliceObjects(List(Obj(ListMap(Name("foo") -> Select(ident("bar"), "baz"))))) expr.toJs.pprint(0) must_== "(function (__rez) { __rez.foo = bar.baz; return __rez })({ })" } "splice other expression" in { val expr = SpliceObjects(List(ident("foo"))) expr.toJs.pprint(0) must_== """(function (__rez) { | for (var __attr in (foo)) if (foo.hasOwnProperty(__attr)) __rez[__attr] = foo[__attr]; | return __rez |})( | { })""".stripMargin } "splice arrays" in { val expr = SpliceArrays(List( Arr(List( Select(ident("foo"), "bar"))), ident("foo"))) expr.toJs.pprint(0) must_== """(function (__rez) { | __rez.push(foo.bar); | for (var __elem in (foo)) if (foo.hasOwnProperty(__elem)) __rez.push(foo[__elem]); | return __rez |})( | [])""".stripMargin } } "simplify" should { "inline select(obj)" in { val x = Select( Obj(ListMap( Name("a") -> ident("x"), Name("b") -> ident("y") )), "a") x.simplify must_=== ident("x") } "inline object components" in { val x = Let(Name("a"), Obj(ListMap( Name("x") -> ident("y"), Name("q") -> If(ident("r"), Select(ident("r"), "foo"), ident("bar")))), Arr(List( Select(ident("a"), "x"), Select(ident("a"), "x"), Select(ident("a"), "q")))) x.simplify must_=== Arr(List(ident("y"), ident("y"), If(ident("r"), Select(ident("r"), "foo"), ident("bar")))) } } "RenderTree" should { "render flat expression" in { val expr = Select(ident("foo"), "bar") expr.render.shows must_= "JsCore(foo.bar)" } "render obj as nested" in { val expr = Obj(ListMap(Name("foo") -> ident("bar"))) expr.render.shows must_== """Obj |╰─ Key(foo: bar)""".stripMargin } "render mixed" in { val expr = Obj(ListMap(Name("foo") -> Call(Select(ident("bar"), "baz"), List()))) expr.render.shows must_== """Obj |╰─ Key(foo: bar.baz())""".stripMargin } } "JsFn" should { "substitute with shadowing Let" in { val fn = JsFn(Name("x"), BinOp(Add, ident("x"), Let(Name("x"), BinOp(Add, Literal(Js.Num(1, false)), ident("x")), ident("x")))) val exp = BinOp(Add, Literal(Js.Num(2, false)), Let(Name("x"), BinOp(Add, Literal(Js.Num(1, false)), Literal(Js.Num(2, false))), ident("x"))) fn(Literal(Js.Num(2, false))) must_=== exp } "substitute with shadowing Fun" in { val fn = JsFn(Name("x"), BinOp(Add, ident("x"), Call( Fun(List(Name("x")), ident("x")), List(Literal(Js.Num(1, false)))))) val exp = BinOp(Add, Literal(Js.Num(2, false)), Call( Fun(List(Name("x")), ident("x")), List(Literal(Js.Num(1, false))))) fn(Literal(Js.Num(2, false))) must_=== exp } "toString" should { "be the same as the equivalent JS" in { val js = JsFn(Name("val"), Obj(ListMap( Name("a") -> Select(ident("val"), "x"), Name("b") -> Select(ident("val"), "y")))) js.toString must equal("""{ "a": _.x, "b": _.y }""") js(ident("_")).toJs.pprint(0) must equal("""{ "a": _.x, "b": _.y }""") } } ">>>" should { "do _.foo, then _.bar" in { val x = ident("x") val a = JsFn(Name("val"), Select(ident("val"), "foo")) val b = JsFn(Name("val"), Select(ident("val"), "bar")) (a >>> b)(x).toJs.pprint(0) must_= "x.foo.bar" } } } }
apache-2.0
digimead/digi-TABuddy-model
src/test/scala/org/digimead/tabuddy/model/ModelSpec.scala
5125
/** * TABuddy-Model - a human-centric K,V framework * * Copyright (c) 2012-2014 Alexey Aksenov ezh@ezh.msk.ru * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.digimead.tabuddy.model import TestDSL._ import java.util.UUID import org.digimead.digi.lib.DependencyInjection import org.digimead.digi.lib.log.api.XLoggable import org.digimead.lib.test.LoggingHelper import org.digimead.tabuddy.model.graph.Graph import org.digimead.tabuddy.model.serialization.StubSerialization import org.scalatest.{ FunSpec, Matchers } class ModelSpec extends FunSpec with Matchers with LoggingHelper with XLoggable { lazy val diConfig = org.digimead.digi.lib.default ~ org.digimead.tabuddy.model.default before { DependencyInjection(diConfig, false) } describe("A Model") { it("should attach and detach element") { import TestDSL._ val graph = Graph[Model]('john1, Model.scope, StubSerialization.Identifier, UUID.randomUUID()) { g ⇒ } val model1 = graph.model.eSet('AAAKey, "AAA").eSet('BBBKey, "BBB").eRelative val rA1 = model1.getRecord('rA) { r ⇒ r.getRecord('rB) { r ⇒ r.getRecord('rLeaf) { r ⇒ r.name = "123" } } }.eRelative val rB1 = (rA1 & RecordLocation('rB)).eRelative val rLeaf1 = (rB1 & RecordLocation('rLeaf)).eRelative val graphCopy = graph.copy(origin = 'john2)(_ ⇒ ()) graphCopy.nodes.size should be(graph.nodes.size) graphCopy.nodes.values.toSeq.sortBy(_.unique) should be(graph.nodes.values.toSeq.sortBy(_.unique)) graphCopy.nodes.values.toSeq.sortBy(_.unique).corresponds(graph.nodes.values.toSeq.sortBy(_.unique))(_.unique == _.unique) should be(true) graphCopy.nodes.values.toSeq.sortBy(_.unique).corresponds(graph.nodes.values.toSeq.sortBy(_.unique))(_ ne _) should be(true) graphCopy.node.safeRead(_.iteratorRecursive).size should be(graphCopy.nodes.values.size - 1) (graphCopy.node.safeRead(_.iteratorRecursive).toSeq :+ graphCopy.node).sortBy(_.unique) should be(graphCopy.nodes.values.toSeq.sortBy(_.unique)) (graphCopy.node.safeRead(_.iteratorRecursive).toSeq :+ graphCopy.node).sortBy(_.unique).corresponds(graphCopy.nodes.values.toSeq.sortBy(_.unique))(_ eq _) should be(true) graphCopy.model should equal(graphCopy.model.eModel) graphCopy.model.eq(graphCopy.model.eModel) should be(true) val recordCopy = graphCopy.model.eNode.safeRead(_.head).rootBox.e recordCopy.eModel.eq(graphCopy.model.eModel) should be(true) recordCopy.eId.name should be("rA") recordCopy.eNode.safeRead(_.size) should be(1) model1.eNode.safeRead(_.iteratorRecursive.toSeq) should have size (3) model1.eNode.safeRead(_.iterator.toSeq) should have size (1) rB1.eNode.safeRead(_.iterator.toSeq) should have size (1) rLeaf1.eNode.safeRead(_.children) should be('empty) (graphCopy.model & RecordLocation('rA) & RecordLocation('rB) & RecordLocation('rLeaf)).eNode.safeRead(_.children) should be('empty) val m1 = graph.modified val q = (graph.model & RecordLocation('rA) & RecordLocation('rB) & RecordLocation('rLeaf) | RecordLocation('rX)).eRelative graph.modified should be > (m1) val m2 = graph.modified q.eSet[String]('abc, "abc") graph.modified should be > (m2) } it("should proper nodes copy functions") { import TestDSL._ val graph = Graph[Model]('john1, Model.scope, StubSerialization.Identifier, UUID.randomUUID()) { g ⇒ } val model1 = graph.model.eSet('AAAKey, "AAA").eSet('BBBKey, "BBB").eRelative val rA1 = model1.getRecord('rA) { r ⇒ r.getRecord('rB) { r ⇒ r.getRecord('rLeaf) { r ⇒ r.name = "123" } } }.eRelative graph.node.safeRead(_.iteratorRecursive.size) should be(3) val rA2Node = rA1.eNode.copy(id = 'rA2, unique = UUID.randomUUID()) rA1.eNode.safeRead { node ⇒ rA2Node.safeRead { node2 ⇒ node.iteratorRecursive.corresponds(node2.iteratorRecursive) { (a, b) ⇒ a.ne(b) && a.unique != b.unique && a.id == b.id && a.modified == b.modified && a.elementType == b.elementType } } } should be(true) graph.node.safeRead(_.iteratorRecursive.size) should be(6) val rA3Node = rA1.eNode.copy(id = 'rA3, unique = UUID.randomUUID(), recursive = false) println(model1.eDump(true)) graph.node.safeRead(_.iteratorRecursive.size) should be(7) } } override def beforeAll(configMap: org.scalatest.ConfigMap) { adjustLoggingBeforeAll(configMap) } }
apache-2.0
mavasani/roslyn-analyzers
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotRaiseReservedExceptionTypes.cs
8910
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { /// <summary> /// CA2201: Do not raise reserved exception types /// /// Too generic: /// System.Exception /// System.ApplicationException /// System.SystemException /// /// Reserved: /// System.OutOfMemoryException /// System.IndexOutOfRangeException /// System.ExecutionEngineException /// System.NullReferenceException /// System.StackOverflowException /// System.Runtime.InteropServices.ExternalException /// System.Runtime.InteropServices.COMException /// System.Runtime.InteropServices.SEHException /// System.AccessViolationException /// /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DoNotRaiseReservedExceptionTypesAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2201"; private static readonly ImmutableArray<string> s_tooGenericExceptions = ImmutableArray.Create("System.Exception", "System.ApplicationException", "System.SystemException"); private static readonly ImmutableArray<string> s_reservedExceptions = ImmutableArray.Create("System.OutOfMemoryException", "System.IndexOutOfRangeException", "System.ExecutionEngineException", "System.NullReferenceException", "System.StackOverflowException", "System.Runtime.InteropServices.ExternalException", "System.Runtime.InteropServices.COMException", "System.Runtime.InteropServices.SEHException", "System.AccessViolationException"); private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DoNotRaiseReservedExceptionTypesTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTooGeneric = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DoNotRaiseReservedExceptionTypesMessageTooGeneric), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageReserved = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DoNotRaiseReservedExceptionTypesMessageReserved), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DoNotRaiseReservedExceptionTypesDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static DiagnosticDescriptor TooGenericRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageTooGeneric, DiagnosticCategory.Usage, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor ReservedRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageReserved, DiagnosticCategory.Usage, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); private static readonly SymbolDisplayFormat s_symbolDisplayFormat = new(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(TooGenericRule, ReservedRule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction( compilationStartContext => { ImmutableHashSet<INamedTypeSymbol> tooGenericExceptionSymbols = CreateSymbolSet(compilationStartContext.Compilation, s_tooGenericExceptions); ImmutableHashSet<INamedTypeSymbol> reservedExceptionSymbols = CreateSymbolSet(compilationStartContext.Compilation, s_reservedExceptions); if (tooGenericExceptionSymbols.IsEmpty && reservedExceptionSymbols.IsEmpty) { return; } compilationStartContext.RegisterOperationAction( context => AnalyzeObjectCreation(context, tooGenericExceptionSymbols, reservedExceptionSymbols), OperationKind.ObjectCreation); }); } private static ImmutableHashSet<INamedTypeSymbol> CreateSymbolSet(Compilation compilation, IEnumerable<string> exceptionNames) { HashSet<INamedTypeSymbol>? set = null; foreach (string exp in exceptionNames) { INamedTypeSymbol? symbol = compilation.GetOrCreateTypeByMetadataName(exp); if (symbol == null) { continue; } if (set == null) { set = new HashSet<INamedTypeSymbol>(); } set.Add(symbol); } return set != null ? set.ToImmutableHashSet() : ImmutableHashSet<INamedTypeSymbol>.Empty; } private static void AnalyzeObjectCreation( OperationAnalysisContext context, ImmutableHashSet<INamedTypeSymbol> tooGenericExceptionSymbols, ImmutableHashSet<INamedTypeSymbol> reservedExceptionSymbols) { var objectCreation = (IObjectCreationOperation)context.Operation; var typeSymbol = objectCreation.Constructor.ContainingType; if (tooGenericExceptionSymbols.Contains(typeSymbol)) { context.ReportDiagnostic(objectCreation.CreateDiagnostic(TooGenericRule, typeSymbol.ToDisplayString(s_symbolDisplayFormat))); } else if (reservedExceptionSymbols.Contains(typeSymbol)) { context.ReportDiagnostic(objectCreation.CreateDiagnostic(ReservedRule, typeSymbol.ToDisplayString(s_symbolDisplayFormat))); } } } }
apache-2.0
grafeas/kritis
pkg/kritis/policy/violation.go
1028
/* Copyright 2018 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package policy // Reason defines violation reason type type Reason string // ViolationType defines type of the violation type ViolationType int // A list of security policy violations // TODO: Add Attestation checking violations const ( UnqualifiedImageViolation ViolationType = iota FixUnavailableViolation SeverityViolation ) // Violation represents a Policy Violation. type Violation interface { Type() ViolationType Reason() Reason Details() interface{} }
apache-2.0
biospi/mzmlb
pwiz/pwiz/analysis/spectrum_processing/SpectrumList_IonMobility.cpp
3236
// // $Id: SpectrumList_IonMobility.cpp 10494 2017-02-21 16:53:20Z pcbrefugee $ // // // Original author: Matt Chambers <matt.chambers <a.t> vanderbilt.edu> // // Copyright 2016 Vanderbilt University - Nashville, TN 37232 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #define PWIZ_SOURCE #include "SpectrumList_IonMobility.hpp" #include "pwiz/utility/misc/Std.hpp" #include "pwiz/data/vendor_readers/Agilent/SpectrumList_Agilent.hpp" //#include "pwiz/data/vendor_readers/Waters/SpectrumList_Waters.hpp" namespace pwiz { namespace analysis { using namespace msdata; using namespace pwiz::util; PWIZ_API_DECL SpectrumList_IonMobility::SpectrumList_IonMobility(const msdata::SpectrumListPtr& inner) : SpectrumListWrapper(inner), mode_(0) { detail::SpectrumList_Agilent* agilent = dynamic_cast<detail::SpectrumList_Agilent*>(&*inner); if (agilent) { mode_ = 1; } /*detail::SpectrumList_Waters* waters = dynamic_cast<detail::SpectrumList_Waters*>(&*inner); if (waters) { mode_ = 2; }*/ } PWIZ_API_DECL bool SpectrumList_IonMobility::accept(const msdata::SpectrumListPtr& inner) { return dynamic_cast<detail::SpectrumList_Agilent*>(&*inner) != NULL /*|| dynamic_cast<detail::SpectrumList_Waters*>(&*inner)*/; } PWIZ_API_DECL SpectrumPtr SpectrumList_IonMobility::spectrum(size_t index, bool getBinaryData) const { return inner_->spectrum(index, getBinaryData); } PWIZ_API_DECL bool SpectrumList_IonMobility::canConvertDriftTimeAndCCS() const { switch (mode_) { case 0: default: return false; // Only Agilent provides this capabilty, for now case 1: return dynamic_cast<detail::SpectrumList_Agilent*>(&*inner_)->canConvertDriftTimeAndCCS(); } } PWIZ_API_DECL double SpectrumList_IonMobility::driftTimeToCCS(double driftTime, double mz, int charge) const { switch (mode_) { case 0: default: throw runtime_error("SpectrumList_IonMobility::driftTimeToCCS] function only supported when reading native Agilent MassHunter files with ion-mobility data"); case 1: return dynamic_cast<detail::SpectrumList_Agilent*>(&*inner_)->driftTimeToCCS(driftTime, mz, charge); } } PWIZ_API_DECL double SpectrumList_IonMobility::ccsToDriftTime(double ccs, double mz, int charge) const { switch (mode_) { case 0: default: throw runtime_error("SpectrumList_IonMobility::ccsToDriftTime] function only supported when reading native Agilent MassHunter files with ion-mobility data"); case 1: return dynamic_cast<detail::SpectrumList_Agilent*>(&*inner_)->ccsToDriftTime(ccs, mz, charge); } } } // namespace analysis } // namespace pwiz
apache-2.0
snowplow/schema-ddl
modules/json4s/src/test/scala/com.snowplowanalytics.iglu.schemaddl/jsonschema/json4s/StringSpec.scala
2104
/* * Copyright (c) 2012-2022 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.iglu.schemaddl.jsonschema.json4s // json4s import org.json4s._ import org.json4s.jackson.JsonMethods.parse import com.snowplowanalytics.iglu.schemaddl.jsonschema.Schema import com.snowplowanalytics.iglu.schemaddl.jsonschema.ToSchema import com.snowplowanalytics.iglu.schemaddl.jsonschema.properties.StringProperty.{Format, MaxLength, MinLength} import com.snowplowanalytics.iglu.schemaddl.jsonschema.json4s.implicits._ // specs2 import org.specs2.Specification class StringSpec extends Specification { def is = s2""" Check JSON Schema string specification parse correct minLength $e1 parse maxLength with ipv4 format $e2 parse unknown format $e3 """ def e1 = { val schema = parse( """ |{"minLength": 32} """.stripMargin) Schema.parse(schema) must beSome(Schema(minLength = Some(MinLength(32)))) } def e2 = { val schema = parse( """ |{"maxLength": 32, "format": "ipv4"} """.stripMargin) Schema.parse(schema) must beSome(Schema(maxLength = Some(MaxLength(32)), format = Some(Format.Ipv4Format))) } def e3 = { implicitly[ToSchema[JValue]] val schema = parse( """ |{"maxLength": 32, "format": "unknown"} """.stripMargin) Schema.parse(schema) must beSome(Schema(maxLength = Some(MaxLength(32)), format = Some(Format.CustomFormat("unknown")))) } }
apache-2.0
algorithm-ninja/cotton
src/main.cpp
18593
#include "box.hpp" #include "logger.hpp" #include <vector> #include <fstream> #include "util.hpp" #include <option.hpp> #include <positional.hpp> #include <command.hpp> #ifdef COTTON_UNIX #include <signal.h> #include <string.h> #include <stdlib.h> #endif #ifdef COTTON_WINDOWS #include <windows.h> #include <tchar.h> #endif BoxCreators* box_creators; CottonLogger* logger; #ifdef COTTON_UNIX void sig_handler(int sig) { logger->error(255, "Received signal " + std::to_string(sig) + " (" + strsignal(sig) + ")"); logger->write(); _Exit(0); } #endif std::unique_ptr<Sandbox> load_box(const std::string& box_root, const std::string& box_id) { try { std::ifstream fin(Sandbox::box_base_path(box_root, std::stoi(box_id)) + "boxinfo"); boost::archive::text_iarchive ia{fin}; Sandbox* s; ia >> s; s->set_error_handler(logger->get_error_function()); s->set_warning_handler(logger->get_warning_function()); return std::unique_ptr<Sandbox>(s); } catch (std::exception& e) { logger->error(3, std::string("Error loading the sandbox: ") + e.what()); return nullptr; } } void save_box(const std::string& box_root, std::unique_ptr<Sandbox>& s) { try { std::ofstream fout(Sandbox::box_base_path(box_root, s->get_id()) + "boxinfo"); boost::archive::text_oarchive oa{fout}; Sandbox* ptr = s.get(); oa << ptr; } catch (std::exception& e) { logger->error(3, std::string("Error saving the sandbox: ") + e.what()); } } namespace program_options { template<> time_limit_t from_char_ptr(const char* ptr) { return time_limit_t(from_char_ptr<double>(ptr)); } template<> space_limit_t from_char_ptr(const char* ptr) { return space_limit_t(from_char_ptr<double>(ptr)); } DEFINE_OPTION(help, "print this message", 'h'); DEFINE_OPTION(box_root, "specify a different folder to put sandboxes in", 'r'); DEFINE_OPTION(json, "force JSON output", 'j'); DEFINE_OPTION(box_id, "id of the sandbox", 'b'); DEFINE_OPTION(box_type, "type of the sandbox to be created"); DEFINE_OPTION(value, "value to set"); DEFINE_OPTION(stream, "the stream to operate on"); DEFINE_OPTION(external_path, "path on the system"); DEFINE_OPTION(internal_path, "path in the sandbox"); DEFINE_OPTION(rw, "read-write"); DEFINE_OPTION(exec, "executable to run"); DEFINE_OPTION(arg, "arguments for the executable"); DEFINE_COMMAND(list, "list available implementations"); DEFINE_COMMAND(create, "create a sandbox", positional<_box_type, const char*, 1>()); DEFINE_COMMAND(check, "check if a sandbox is consistent"); DEFINE_COMMAND(get_root, "gets the root path of the sandbox"); DEFINE_COMMAND(cpu_limit, "gets or sets the cpu time limit", positional<_value, time_limit_t, 0, 1>()); DEFINE_COMMAND(wall_limit, "gets or sets the wall clock limit", positional<_value, time_limit_t, 0, 1>()); DEFINE_COMMAND(memory_limit, "gets or sets the memory limit", positional<_value, space_limit_t, 0, 1>()); DEFINE_COMMAND(disk_limit, "gets or sets the disk limit", positional<_value, space_limit_t, 0, 1>()); DEFINE_COMMAND(process_limit, "gets or sets the process limit", positional<_value, int, 0, 1>()); DEFINE_COMMAND(redirect, "gets or sets i/o redirections", positional<_stream, const char*, 1>(), positional<_value, const char*, 0, 1>()); DEFINE_COMMAND(mount, "enables paths in the sandbox, or gets information on a path", option<_rw, void>(), positional<_internal_path, const char*, 1>(), positional<_external_path, const char*, 0, 1>()); DEFINE_COMMAND(umount, "disables paths in the sandbox", positional<_internal_path, const char*, 1>()); DEFINE_COMMAND(run, "run program in the sandbox", positional<_exec, const char*, 1>(), positional<_arg, const char*, 0, 1000>()); DEFINE_COMMAND(running_time, "get last command's cpu time"); DEFINE_COMMAND(wall_time, "get last command's wall time"); DEFINE_COMMAND(memory_usage, "get last command's memory usage"); DEFINE_COMMAND(status, "get last command's exit reason"); DEFINE_COMMAND(return_code, "get last command's return code"); DEFINE_COMMAND(signal, "get last command's killing signal"); DEFINE_COMMAND(clear, "resets the sandbox to a clean state"); DEFINE_COMMAND(destroy, "deletes the sandbox"); DEFINE_COMMAND(cotton, "Cotton sandbox", option<_help, void>(), option<_box_root, const char*>("/tmp"), option<_json, void>(), option<_box_id, const char*>(), &list_command, &create_command, &check_command, &get_root_command, &cpu_limit_command, &wall_limit_command, &memory_limit_command, &disk_limit_command, &process_limit_command, &redirect_command, &mount_command, &umount_command, &run_command, &running_time_command, &wall_time_command, &memory_usage_command, &status_command, &return_code_command, &signal_command, &clear_command, &destroy_command); template<> void command_callback(const decltype(cotton_command)& cc) { if (cc.has_option<_help>()) { cc.print_help(std::cerr); exit(0); } if (cc.has_option<_json>()) { delete logger; logger = new CottonJSONLogger; } } #define TEST_FEATURE(feature) if (features & Sandbox::feature) std::get<2>(res.back()).emplace_back(#feature); template<> void command_callback(const decltype(cotton_command)& cc, const decltype(list_command)& lc) { std::vector<std::tuple<std::string, int, std::vector<std::string>>> res; for (const auto& creator: *box_creators) { std::unique_ptr<Sandbox> s(creator.second(cc.get_option<_box_root>())); s->set_error_handler(logger->get_error_function()); s->set_warning_handler(logger->get_warning_function()); if (!s->is_available()) continue; res.emplace_back(creator.first, s->get_overhead(), std::vector<std::string>{}); Sandbox::feature_mask_t features = s->get_features(); TEST_FEATURE(memory_limit); TEST_FEATURE(cpu_limit); TEST_FEATURE(wall_time_limit); TEST_FEATURE(process_limit); TEST_FEATURE(process_limit_full); TEST_FEATURE(disk_limit); TEST_FEATURE(disk_limit_full); TEST_FEATURE(folder_mount); TEST_FEATURE(memory_usage); TEST_FEATURE(running_time); TEST_FEATURE(wall_time); TEST_FEATURE(clearable); TEST_FEATURE(process_isolation); TEST_FEATURE(io_redirection); TEST_FEATURE(network_isolation); TEST_FEATURE(return_code); TEST_FEATURE(signal); } logger->result(res); } #undef TEST_FEATURE template<> void command_callback(const decltype(cotton_command)& cc, const decltype(create_command)& crc) { if (!box_creators->count(crc.get_positional<_box_type>()[0])) { logger->error(2, "The given box type does not exist!"); return; } auto box_creator = (*box_creators)[crc.get_positional<_box_type>()[0]]; std::unique_ptr<Sandbox> s(box_creator(cc.get_option<_box_root>())); s->set_error_handler(logger->get_error_function()); s->set_warning_handler(logger->get_warning_function()); if (!s->is_available()) { logger->error(2, "The given box type is not available!"); return; } s->create_box(); save_box(cc.get_option<_box_root>(), s); logger->result(s->get_id()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(check_command)& chc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? false : s->check()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(get_root_command)& grc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? "" : s->get_root()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(memory_limit_command)& lc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); if (lc.count_positional<_value>() > 0) { auto val = lc.get_positional<_value>()[0]; logger->result(s.get() == nullptr ? false : s->set_memory_limit(val)); save_box(cc.get_option<_box_root>(), s); } else { logger->result(s.get() == nullptr ? 0 : s->get_memory_limit()); } } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(cpu_limit_command)& lc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); if (lc.count_positional<_value>() > 0) { auto val = lc.get_positional<_value>()[0]; logger->result(s.get() == nullptr ? false : s->set_time_limit(val)); save_box(cc.get_option<_box_root>(), s); } else { logger->result(s.get() == nullptr ? 0 : s->get_time_limit()); } } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(wall_limit_command)& lc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); if (lc.count_positional<_value>() > 0) { auto val = lc.get_positional<_value>()[0]; logger->result(s.get() == nullptr ? false : s->set_wall_time_limit(val)); save_box(cc.get_option<_box_root>(), s); } else { logger->result(s.get() == nullptr ? 0 : s->get_wall_time_limit()); } } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(process_limit_command)& lc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); if (lc.count_positional<_value>() > 0) { auto val = lc.get_positional<_value>()[0]; logger->result(s.get() == nullptr ? false : s->set_process_limit(val)); save_box(cc.get_option<_box_root>(), s); } else { logger->result(s.get() == nullptr ? 0 : s->get_process_limit()); } } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(disk_limit_command)& lc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); if (lc.count_positional<_value>() > 0) { auto val = lc.get_positional<_value>()[0]; logger->result(s.get() == nullptr ? false : s->set_disk_limit(val)); save_box(cc.get_option<_box_root>(), s); } else { logger->result(s.get() == nullptr ? 0 : s->get_disk_limit()); } } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(redirect_command)& rc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); std::string stream = rc.get_positional<_stream>()[0]; if (rc.count_positional<_value>() > 0) { if (s.get() == nullptr) { logger->result(false); return; } std::string val = rc.get_positional<_value>()[0]; if (val == "-") val = ""; if (stream == "stdin") { logger->result(s->redirect_stdin(val)); } else if (stream == "stdout") { logger->result(s->redirect_stdout(val)); } else if (stream == "stderr") { logger->result(s->redirect_stderr(val)); } else { logger->error(2, "Invalid redirect type given"); logger->result(false); } save_box(cc.get_option<_box_root>(), s); } else { if (s.get() == nullptr) { logger->result(""); return; } if (stream == "stdin") { logger->result(s->get_stdin()); } else if (stream == "stdout") { logger->result(s->get_stdout()); } else if (stream == "stderr") { logger->result(s->get_stderr()); } else { logger->error(2, "Invalid redirect type given"); logger->result(false); } } } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(mount_command)& mc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); std::string inner_path = mc.get_positional<_internal_path>()[0]; if (mc.count_positional<_external_path>() > 0) { std::string val = mc.get_positional<_external_path>()[0]; logger->result(s.get() == nullptr ? false : s->mount(inner_path, val, mc.has_option<_rw>())); save_box(cc.get_option<_box_root>(), s); } else { logger->result(s.get() == nullptr ? "" : s->mount(inner_path)); } } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(umount_command)& uc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); std::string inner_path = uc.get_positional<_internal_path>()[0]; logger->result(s.get() == nullptr ? false : s->umount(inner_path)); save_box(cc.get_option<_box_root>(), s); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(run_command)& rc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); std::string exec = rc.get_positional<_exec>()[0]; auto args = rc.get_positional<_arg>(); std::vector<std::string> s_args; for (const auto str: args) s_args.emplace_back(str); logger->result(s.get() == nullptr ? false : s->run(exec, s_args)); save_box(cc.get_option<_box_root>(), s); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(memory_usage_command)& muc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? space_limit_t(0) : s->get_memory_usage()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(running_time_command)& rtc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? time_limit_t(0) : s->get_running_time()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(wall_time_command)& rtc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? time_limit_t(0) : s->get_wall_time()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(status_command)& rtc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? "" : s->get_status()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(return_code_command)& rtc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? 0 : s->get_return_code()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(signal_command)& rtc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? 0 : s->get_signal()); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(clear_command)& rtc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? false : s->clear()); save_box(cc.get_option<_box_root>(), s); } template<> void command_callback(const decltype(cotton_command)& cc, const decltype(destroy_command)& rtc) { if (!cc.has_option<_box_id>()) { logger->error(2, "You need to specify a box id!"); return; } auto s = load_box(cc.get_option<_box_root>(), cc.get_option<_box_id>()); logger->result(s.get() == nullptr ? false : s->delete_box()); } } // namespace program_options int main(int argc, const char** argv) { #ifdef COTTON_UNIX // Immediately drop privileges if the program is setuid, do nothing otherwise. setreuid(geteuid(), getuid()); if (!isatty(fileno(stdout))) logger = new CottonJSONLogger; else logger = new CottonTTYLogger; signal(SIGHUP, sig_handler); signal(SIGINT, sig_handler); signal(SIGQUIT, sig_handler); signal(SIGILL, sig_handler); signal(SIGABRT, sig_handler); signal(SIGFPE, sig_handler); signal(SIGSEGV, sig_handler); signal(SIGPIPE, sig_handler); signal(SIGTERM, sig_handler); signal(SIGBUS, sig_handler); #else logger = new CottonTTYLogger; #endif try { program_options::cotton_command.parse(argc, argv); } catch (std::exception& e) { logger->error(255, std::string("Unandled exception! ") + e.what()); } logger->write(); }
apache-2.0
kevinsawicki/maven-android-plugin
src/test/java/com/jayway/maven/plugins/android/standalonemojos/MojoProjectStub.java
4229
package com.jayway.maven.plugins.android.standalonemojos; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.model.Resource; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.plugin.testing.stubs.MavenProjectStub; import org.junit.Assert; /** * Basic MavenProject implementation that can be used for testing. */ public class MojoProjectStub extends MavenProjectStub { private File basedir; private Build build; private Properties props = new Properties(); public MojoProjectStub(File projectDir) { this.basedir = projectDir; props.setProperty("basedir", this.basedir.getAbsolutePath()); File pom = new File(getBasedir(), "plugin-config.xml"); MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model = null; FileReader fileReader = null; try { fileReader = new FileReader(pom); model = pomReader.read(fileReader); setModel(model); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(fileReader); } setGroupId(model.getGroupId()); setArtifactId(model.getArtifactId()); setVersion(model.getVersion()); setName(model.getName()); setUrl(model.getUrl()); setPackaging(model.getPackaging()); setFile(pom); build = model.getBuild(); if(build == null) { build = new Build(); } File srcDir = getStandardDir(getBuild().getSourceDirectory(), "src/main/java"); getBuild().setSourceDirectory(srcDir.getAbsolutePath()); File targetDir = getStandardDir(getBuild().getDirectory(), "target"); getBuild().setDirectory(targetDir.getAbsolutePath()); File outputDir = getStandardDir(getBuild().getOutputDirectory(), "target/classes"); getBuild().setOutputDirectory(outputDir.getAbsolutePath()); List<Resource> resources = new ArrayList<Resource>(); resources.addAll(getBuild().getResources()); if (resources.isEmpty()) { resources = new ArrayList<Resource>(); Resource resource = new Resource(); File resourceDir = normalize("src/main/resources"); resource.setDirectory(resourceDir.getAbsolutePath()); makeDirs(resourceDir); resources.add(resource); } else { // Make this project work on windows ;-) for (Resource resource : resources) { File dir = normalize(resource.getDirectory()); resource.setDirectory(dir.getAbsolutePath()); } } getBuild().setResources(resources); } @Override public Properties getProperties() { return props; } @Override public Build getBuild() { return this.build; } private File getStandardDir(String dirPath, String defaultPath) { File dir; if (StringUtils.isBlank(dirPath)) { dir = normalize(defaultPath); } else { dir = normalize(dirPath); } makeDirs(dir); return dir; } /** * Normalize a path. * <p> * Ensure path is absolute, and has proper system file separators. * * @param path the raw path. * @return */ private File normalize(final String path) { String ospath = FilenameUtils.separatorsToSystem(path); File file = new File(ospath); if(file.isAbsolute()) { return file; } else { return new File(getBasedir(), ospath); } } private void makeDirs(File dir) { if (dir.exists()) { return; } Assert.assertTrue("Unable to make directories: " + dir, dir.mkdirs()); } @Override public File getBasedir() { return this.basedir; } }
apache-2.0
captiosus/treadmill
treadmill/api/identity_group.py
2894
"""Implementation of identity group API. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import fnmatch from treadmill import context from treadmill import schema from treadmill import authz from treadmill import master _LOGGER = logging.getLogger(__name__) class API(object): """Treadmill Identity Group REST api.""" def __init__(self): def _list(match=None): """List configured identity groups.""" if match is None: match = '*' zkclient = context.GLOBAL.zk.conn groups = [ master.get_identity_group(zkclient, group) for group in master.identity_groups(zkclient) ] filtered = [ group for group in groups if group is not None and fnmatch.fnmatch(group['_id'], match) ] return sorted(filtered) @schema.schema( {'$ref': 'identity_group.json#/resource_id'}, ) def get(rsrc_id): """Get application group configuration.""" zkclient = context.GLOBAL.zk.conn return master.get_identity_group(zkclient, rsrc_id) @schema.schema( {'$ref': 'identity_group.json#/resource_id'}, {'allOf': [{'$ref': 'identity_group.json#/resource'}, {'$ref': 'identity_group.json#/verbs/create'}]} ) def create(rsrc_id, rsrc): """Create (configure) application group.""" zkclient = context.GLOBAL.zk.conn master.update_identity_group(zkclient, rsrc_id, rsrc['count']) return master.get_identity_group(zkclient, rsrc_id) @schema.schema( {'$ref': 'identity_group.json#/resource_id'}, {'allOf': [{'$ref': 'identity_group.json#/resource'}, {'$ref': 'identity_group.json#/verbs/update'}]} ) def update(rsrc_id, rsrc): """Update application configuration.""" zkclient = context.GLOBAL.zk.conn master.update_identity_group(zkclient, rsrc_id, rsrc['count']) return master.get_identity_group(zkclient, rsrc_id) @schema.schema( {'$ref': 'identity_group.json#/resource_id'}, ) def delete(rsrc_id): """Delete configured application group.""" zkclient = context.GLOBAL.zk.conn master.delete_identity_group(zkclient, rsrc_id) return None self.list = _list self.get = get self.create = create self.update = update self.delete = delete def init(authorizer): """Returns module API wrapped with authorizer function.""" api = API() return authz.wrap(api, authorizer)
apache-2.0
CaMnter/Robotlegs4Android
robotlegs4android/src/main/java/com/camnter/robotlegs4android/base/ContextEvent.java
1621
/* * Copyright (C) 2015 CaMnter yuanyu.camnter@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.camnter.robotlegs4android.base; /** * Description:ContextEvent * Created by:CaMnter */ public class ContextEvent extends Event { /*********************************** * Startup ****************************************/ public static final String STARTUP = "startup"; public static final String STARTUP_COMPLETE = "startupComplete"; /*********************************** * Shutdown ***************************************/ public static final String SHUTDOWN = "shutdown"; public static final String SHUTDOWN_COMPLETE = "shutdownComplete"; /************************************************************************************/ /** * @param type type */ public ContextEvent(String type) { super(type); } /** * Get The Event Type * 取得事件类型 * * @return The Event Type 事件类型 */ public String getEventType() { return this.getType(); } }
apache-2.0
liufeiit/io-remoting
src/main/java/io/remoting/protocol/ProtocolFactory.java
325
package io.remoting.protocol; /** * @author 刘飞 E-mail:liufei_it@126.com * * @version 1.0.0 * @since 2017年5月22日 下午4:41:51 */ public interface ProtocolFactory { int getProtocolCode(); void encode(Object body, RemotingCommand command); <T> T decode(Class<T> bodyType, RemotingCommand command); }
apache-2.0
gitblit/gitblit-cookbook-plugin
src/main/java/com/gitblit/plugin/cookbook/MyTicketHook.java
1448
/* * Copyright 2014 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.plugin.cookbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.fortsoft.pf4j.Extension; import com.gitblit.extensions.TicketHook; import com.gitblit.models.TicketModel; import com.gitblit.models.TicketModel.Change; /** * Example ticket hook. * * @author James Moger * */ @Extension public class MyTicketHook extends TicketHook { final Logger log = LoggerFactory.getLogger(getClass()); @Override public void onNewTicket(TicketModel ticket) { log.info(String.format("%s %s ticket #%d created", getClass().getSimpleName(), ticket.repository, ticket.number)); } @Override public void onUpdateTicket(TicketModel ticket, Change change) { log.info(String.format("%s %s ticket #%d updated", getClass().getSimpleName(), ticket.repository, ticket.number)); } }
apache-2.0
nickbabcock/dropwizard
dropwizard-e2e/src/test/java/com/example/validation/InjectValidatorTest.java
1787
package com.example.validation; import io.dropwizard.Configuration; import io.dropwizard.testing.junit.DropwizardAppRule; import org.junit.ClassRule; import org.junit.Test; import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import static io.dropwizard.testing.ResourceHelpers.resourceFilePath; import static org.assertj.core.api.Assertions.assertThat; public class InjectValidatorTest { @ClassRule public static final DropwizardAppRule<Configuration> RULE = new DropwizardAppRule<>( DefaultValidatorApp.class, resourceFilePath("app1/config.yml") ); @Test public void shouldValidateNormally() { final Client client = RULE.client(); final String url = String.format("http://localhost:%d/default", RULE.getLocalPort()); final WebTarget target = client.target(url); Response validRequest = target .queryParam("value", "right") .request().get(); Response invalidRequest = target .queryParam("value", "wrong") .request().get(); assertThat(validRequest.getStatus()).isEqualTo(204); assertThat(invalidRequest.getStatus()).isEqualTo(400); assertThat(invalidRequest.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param value must be one of [right]\"]}"); } @Test public void shouldInjectValidator() { final Client client = RULE.client(); final String url = String.format("http://localhost:%d/injectable", RULE.getLocalPort()); final Response response = client.target(url) .queryParam("value", "right") .request() .get(); assertThat(response.getStatus()).isEqualTo(204); } }
apache-2.0
spee140622/j_s_rabbitmq
src/main/java/org/m/rabbitmq/simple/helloworld/Send/Send.java
1090
package org.m.rabbitmq.simple.helloworld.Send; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; /** * @version 1.1 * Created by wenzhouyang on 6/25/2014. */ public class Send { private final static String QUEUE_NAME = "hello"; public static void main(String[] args) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.184.128"); factory.setUsername("guest"); factory.setPassword("guest"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "hello World!"; for (int i=0; i<100;i++) { channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("sent '" + message + "' on " + System.currentTimeMillis() ); } channel.close(); connection.close(); } }
apache-2.0
Costo/azure-storage-net
Lib/Common/Shared/Protocol/Constants.cs
56145
// ----------------------------------------------------------------------------------------- // <copyright file="Constants.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Shared.Protocol { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; /// <summary> /// Contains storage constants. /// </summary> #if WINDOWS_RT internal #else public #endif static class Constants { /// <summary> /// Constant for the max value of ParallelOperationThreadCount for Block Blobs. /// </summary> public const int MaxParallelOperationThreadCount = 64; /// <summary> /// Maximum number of shared access policy identifiers supported by server. /// </summary> public const int MaxSharedAccessPolicyIdentifiers = 5; /// <summary> /// Default Write Block Size used by Blob stream. /// </summary> public const int DefaultWriteBlockSizeBytes = (int)(4 * Constants.MB); /// <summary> /// The maximum size of a blob before it must be separated into blocks. /// </summary> public const long MaxSingleUploadBlobSize = 64 * MB; /// <summary> /// The maximum size of a single block. /// </summary> public const int MaxBlockSize = (int)(4 * Constants.MB); /// <summary> /// The maximum size of a range get operation that returns content MD5. /// </summary> public const int MaxRangeGetContentMD5Size = (int)(4 * Constants.MB); /// <summary> /// The maximum number of blocks. /// </summary> public const long MaxBlockNumber = 50000; /// <summary> /// The maximum size of a blob with blocks. /// </summary> public const long MaxBlobSize = MaxBlockNumber * MaxBlockSize; /// <summary> /// Constant for the max value of MaximumExecutionTime. /// </summary> public static readonly TimeSpan MaxMaximumExecutionTime = TimeSpan.FromDays(24.0); /// <summary> /// Default client side timeout for all service clients. /// </summary> public static readonly TimeSpan DefaultClientSideTimeout = TimeSpan.FromMinutes(5); /// <summary> /// Default server side timeout for all service clients. /// </summary> [Obsolete("Server-side timeout is not required by default.")] public static readonly TimeSpan DefaultServerSideTimeout = TimeSpan.FromSeconds(90); /// <summary> /// Maximum Retry Policy back-off /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Backoff", Justification = "Reviewed")] public static readonly TimeSpan MaximumRetryBackoff = TimeSpan.FromHours(1); /// <summary> /// Maximum allowed timeout for any request. /// </summary> public static readonly TimeSpan MaximumAllowedTimeout = TimeSpan.FromSeconds(int.MaxValue); /// <summary> /// Default size of buffer for unknown sized requests. /// </summary> internal const int DefaultBufferSize = (int)(64 * KB); /// <summary> /// Common name to be used for all loggers. /// </summary> internal const string LogSourceName = "Microsoft.WindowsAzure.Storage"; /// <summary> /// The size of a page in a PageBlob. /// </summary> public const int PageSize = 512; /// <summary> /// A constant representing a kilo-byte (Non-SI version). /// </summary> public const long KB = 1024; /// <summary> /// A constant representing a megabyte (Non-SI version). /// </summary> public const long MB = 1024 * KB; /// <summary> /// A constant representing a megabyte (Non-SI version). /// </summary> public const long GB = 1024 * MB; /// <summary> /// XML element for committed blocks. /// </summary> public const string CommittedBlocksElement = "CommittedBlocks"; /// <summary> /// XML element for uncommitted blocks. /// </summary> public const string UncommittedBlocksElement = "UncommittedBlocks"; /// <summary> /// XML element for blocks. /// </summary> public const string BlockElement = "Block"; /// <summary> /// XML element for names. /// </summary> public const string NameElement = "Name"; /// <summary> /// XML element for sizes. /// </summary> public const string SizeElement = "Size"; /// <summary> /// XML element for block lists. /// </summary> public const string BlockListElement = "BlockList"; /// <summary> /// XML element for queue message lists. /// </summary> public const string MessagesElement = "QueueMessagesList"; /// <summary> /// XML element for queue messages. /// </summary> public const string MessageElement = "QueueMessage"; /// <summary> /// XML element for message IDs. /// </summary> public const string MessageIdElement = "MessageId"; /// <summary> /// XML element for insertion times. /// </summary> public const string InsertionTimeElement = "InsertionTime"; /// <summary> /// XML element for expiration times. /// </summary> public const string ExpirationTimeElement = "ExpirationTime"; /// <summary> /// XML element for pop receipts. /// </summary> public const string PopReceiptElement = "PopReceipt"; /// <summary> /// XML element for the time next visible fields. /// </summary> public const string TimeNextVisibleElement = "TimeNextVisible"; /// <summary> /// XML element for message texts. /// </summary> public const string MessageTextElement = "MessageText"; /// <summary> /// XML element for dequeue counts. /// </summary> public const string DequeueCountElement = "DequeueCount"; /// <summary> /// XML element for page ranges. /// </summary> public const string PageRangeElement = "PageRange"; /// <summary> /// XML element for page list elements. /// </summary> public const string PageListElement = "PageList"; /// <summary> /// XML element for page range start elements. /// </summary> public const string StartElement = "Start"; /// <summary> /// XML element for page range end elements. /// </summary> public const string EndElement = "End"; /// <summary> /// XML element for delimiters. /// </summary> public const string DelimiterElement = "Delimiter"; /// <summary> /// XML element for blob prefixes. /// </summary> public const string BlobPrefixElement = "BlobPrefix"; /// <summary> /// XML element for content type fields. /// </summary> public const string CacheControlElement = "Cache-Control"; /// <summary> /// XML element for content type fields. /// </summary> public const string ContentTypeElement = "Content-Type"; /// <summary> /// XML element for content encoding fields. /// </summary> public const string ContentEncodingElement = "Content-Encoding"; /// <summary> /// XML element for content language fields. /// </summary> public const string ContentLanguageElement = "Content-Language"; /// <summary> /// XML element for content length fields. /// </summary> public const string ContentLengthElement = "Content-Length"; /// <summary> /// XML element for content MD5 fields. /// </summary> public const string ContentMD5Element = "Content-MD5"; /// <summary> /// XML element for enumeration results. /// </summary> public const string EnumerationResultsElement = "EnumerationResults"; /// <summary> /// XML element for service endpoint. /// </summary> public const string ServiceEndpointElement = "ServiceEndpoint"; /// <summary> /// XML element for container name. /// </summary> public const string ContainerNameElement = "ContainerName"; /// <summary> /// XML element for share name. /// </summary> public const string ShareNameElement = "ShareName"; /// <summary> /// XML element for directory path. /// </summary> public const string DirectoryPathElement = "DirectoryPath"; /// <summary> /// XML element for blobs. /// </summary> public const string BlobsElement = "Blobs"; /// <summary> /// XML element for prefixes. /// </summary> public const string PrefixElement = "Prefix"; /// <summary> /// XML element for maximum results. /// </summary> public const string MaxResultsElement = "MaxResults"; /// <summary> /// XML element for markers. /// </summary> public const string MarkerElement = "Marker"; /// <summary> /// XML element for the next marker. /// </summary> public const string NextMarkerElement = "NextMarker"; /// <summary> /// XML element for the ETag. /// </summary> public const string EtagElement = "Etag"; /// <summary> /// XML element for the last modified date. /// </summary> public const string LastModifiedElement = "Last-Modified"; /// <summary> /// XML element for the Url. /// </summary> public const string UrlElement = "Url"; /// <summary> /// XML element for blobs. /// </summary> public const string BlobElement = "Blob"; /// <summary> /// XML element for copy ID. /// </summary> public const string CopyIdElement = "CopyId"; /// <summary> /// XML element for copy status. /// </summary> public const string CopyStatusElement = "CopyStatus"; /// <summary> /// XML element for copy source. /// </summary> public const string CopySourceElement = "CopySource"; /// <summary> /// XML element for copy progress. /// </summary> public const string CopyProgressElement = "CopyProgress"; /// <summary> /// XML element for copy completion time. /// </summary> public const string CopyCompletionTimeElement = "CopyCompletionTime"; /// <summary> /// XML element for copy status description. /// </summary> public const string CopyStatusDescriptionElement = "CopyStatusDescription"; /// <summary> /// Constant signaling a page blob. /// </summary> public const string PageBlobValue = "PageBlob"; /// <summary> /// Constant signaling a block blob. /// </summary> public const string BlockBlobValue = "BlockBlob"; /// <summary> /// Constant signaling an append blob. /// </summary> public const string AppendBlobValue = "AppendBlob"; /// <summary> /// Constant signaling the blob is locked. /// </summary> public const string LockedValue = "locked"; /// <summary> /// Constant signaling the blob is unlocked. /// </summary> public const string UnlockedValue = "unlocked"; /// <summary> /// Constant signaling the resource is available for leasing. /// </summary> public const string LeaseAvailableValue = "available"; /// <summary> /// Constant signaling the resource is leased. /// </summary> public const string LeasedValue = "leased"; /// <summary> /// Constant signaling the resource's lease has expired. /// </summary> public const string LeaseExpiredValue = "expired"; /// <summary> /// Constant signaling the resource's lease is breaking. /// </summary> public const string LeaseBreakingValue = "breaking"; /// <summary> /// Constant signaling the resource's lease is broken. /// </summary> public const string LeaseBrokenValue = "broken"; /// <summary> /// Constant signaling the resource's lease is infinite. /// </summary> public const string LeaseInfiniteValue = "infinite"; /// <summary> /// Constant signaling the resource's lease is fixed (finite). /// </summary> public const string LeaseFixedValue = "fixed"; /// <summary> /// Constant for a pending copy. /// </summary> public const string CopyPendingValue = "pending"; /// <summary> /// Constant for a successful copy. /// </summary> public const string CopySuccessValue = "success"; /// <summary> /// Constant for an aborted copy. /// </summary> public const string CopyAbortedValue = "aborted"; /// <summary> /// Constant for a failed copy. /// </summary> public const string CopyFailedValue = "failed"; /// <summary> /// Constant for unavailable geo-replication status. /// </summary> public const string GeoUnavailableValue = "unavailable"; /// <summary> /// Constant for live geo-replication status. /// </summary> public const string GeoLiveValue = "live"; /// <summary> /// Constant for bootstrap geo-replication status. /// </summary> public const string GeoBootstrapValue = "bootstrap"; /// <summary> /// XML element for blob types. /// </summary> public const string BlobTypeElement = "BlobType"; /// <summary> /// XML element for the lease status. /// </summary> public const string LeaseStatusElement = "LeaseStatus"; /// <summary> /// XML element for the lease status. /// </summary> public const string LeaseStateElement = "LeaseState"; /// <summary> /// XML element for the lease status. /// </summary> public const string LeaseDurationElement = "LeaseDuration"; /// <summary> /// XML element for snapshots. /// </summary> public const string SnapshotElement = "Snapshot"; /// <summary> /// XML element for containers. /// </summary> public const string ContainersElement = "Containers"; /// <summary> /// XML element for a container. /// </summary> public const string ContainerElement = "Container"; /// <summary> /// XML element for shares. /// </summary> public const string SharesElement = "Shares"; /// <summary> /// XML element for a share. /// </summary> public const string ShareElement = "Share"; /// <summary> /// XML element for Share Quota. /// </summary> public const string QuotaElement = "Quota"; /// <summary> /// XML element for file ranges. /// </summary> public const string FileRangeElement = "Range"; /// <summary> /// XML element for file list elements. /// </summary> public const string FileRangeListElement = "Ranges"; /// <summary> /// XML element for files. /// </summary> public const string EntriesElement = "Entries"; /// <summary> /// XML element for files. /// </summary> public const string FileElement = "File"; /// <summary> /// XML element for directory. /// </summary> public const string FileDirectoryElement = "Directory"; /// <summary> /// XML element for queues. /// </summary> public const string QueuesElement = "Queues"; /// <summary> /// Version 2 of the XML element for the queue name. /// </summary> public const string QueueNameElement = "Name"; /// <summary> /// XML element for the queue. /// </summary> public const string QueueElement = "Queue"; /// <summary> /// XML element for properties. /// </summary> public const string PropertiesElement = "Properties"; /// <summary> /// XML element for the metadata. /// </summary> public const string MetadataElement = "Metadata"; /// <summary> /// XML element for an invalid metadata name. /// </summary> public const string InvalidMetadataName = "x-ms-invalid-name"; /// <summary> /// XML element for maximum results. /// </summary> public const string MaxResults = "MaxResults"; /// <summary> /// XML element for committed blocks. /// </summary> public const string CommittedElement = "Committed"; /// <summary> /// XML element for uncommitted blocks. /// </summary> public const string UncommittedElement = "Uncommitted"; /// <summary> /// XML element for the latest. /// </summary> public const string LatestElement = "Latest"; /// <summary> /// XML element for signed identifiers. /// </summary> public const string SignedIdentifiers = "SignedIdentifiers"; /// <summary> /// XML element for a signed identifier. /// </summary> public const string SignedIdentifier = "SignedIdentifier"; /// <summary> /// XML element for access policies. /// </summary> public const string AccessPolicy = "AccessPolicy"; /// <summary> /// XML attribute for IDs. /// </summary> public const string Id = "Id"; /// <summary> /// XML element for the start time of an access policy. /// </summary> public const string Start = "Start"; /// <summary> /// XML element for the end of an access policy. /// </summary> public const string Expiry = "Expiry"; /// <summary> /// XML element for the permissions of an access policy. /// </summary> public const string Permission = "Permission"; /// <summary> /// The URI path component to access the messages in a queue. /// </summary> public const string Messages = "messages"; /// <summary> /// XML element for exception details. /// </summary> internal const string ErrorException = "exceptiondetails"; /// <summary> /// XML root element for errors. /// </summary> public const string ErrorRootElement = "Error"; /// <summary> /// XML element for error codes. /// </summary> public const string ErrorCode = "Code"; /// <summary> /// XML element for error codes returned by the preview tenants. /// </summary> internal const string ErrorCodePreview = "code"; /// <summary> /// XML element for error messages. /// </summary> public const string ErrorMessage = "Message"; /// <summary> /// XML element for error messages. /// </summary> internal const string ErrorMessagePreview = "message"; /// <summary> /// XML element for exception messages. /// </summary> public const string ErrorExceptionMessage = "ExceptionMessage"; /// <summary> /// XML element for stack traces. /// </summary> public const string ErrorExceptionStackTrace = "StackTrace"; /// <summary> /// Namespace of the entity container. /// </summary> internal const string EdmEntityTypeNamespaceName = "AzureTableStorage"; /// <summary> /// Name of the entity container. /// </summary> internal const string EdmEntityTypeName = "DefaultContainer"; /// <summary> /// Name of the entity set. /// </summary> internal const string EntitySetName = "Tables"; /// <summary> /// Namespace name for primitive types. /// </summary> internal const string Edm = "Edm."; /// <summary> /// Default namespace name for Tables. /// </summary> internal const string DefaultNamespaceName = "account"; /// <summary> /// Default name for Tables. /// </summary> internal const string DefaultTableName = "TableName"; /// <summary> /// Header value to set Accept to XML. /// </summary> internal const string XMLAcceptHeaderValue = "application/xml"; /// <summary> /// Header value to set Accept to AtomPub. /// </summary> internal const string AtomAcceptHeaderValue = "application/atom+xml,application/atomsvc+xml,application/xml"; /// <summary> /// Header value to set Accept to JsonLight. /// </summary> internal const string JsonLightAcceptHeaderValue = "application/json;odata=minimalmetadata"; /// <summary> /// Header value to set Accept to JsonFullMetadata. /// </summary> internal const string JsonFullMetadataAcceptHeaderValue = "application/json;odata=fullmetadata"; /// <summary> /// Header value to set Accept to JsonNoMetadata. /// </summary> internal const string JsonNoMetadataAcceptHeaderValue = "application/json;odata=nometadata"; /// <summary> /// Header value to set Content-Type to AtomPub. /// </summary> internal const string AtomContentTypeHeaderValue = "application/atom+xml"; /// <summary> /// Header value to set Content-Type to JSON. /// </summary> internal const string JsonContentTypeHeaderValue = "application/json"; /// <summary> /// The prefix used in all ETags. /// </summary> internal const string ETagPrefix = "\"datetime'"; /// <summary> /// Constants for HTTP headers. /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Reviewed.")] [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed.")] public static class HeaderConstants { static HeaderConstants() { #if WINDOWS_PHONE && WINDOWS_DESKTOP UserAgentComment = string.Format(CultureInfo.InvariantCulture, "(.NET CLR {0}; Windows Phone {1})", Environment.Version, Environment.OSVersion.Version); #elif WINDOWS_PHONE && WINDOWS_RT UserAgentComment = "(Windows Runtime Phone)"; #elif WINDOWS_RT UserAgentComment = "(Windows Runtime)"; #elif ASPNET_K #if DNXCORE50 UserAgentComment = "(ASP.NET Core 5.0)"; #else UserAgentComment = "(ASP.NET 5.0)"; #endif #elif PORTABLE UserAgentComment = "(Portable Class Library)"; #else UserAgentComment = string.Format(CultureInfo.InvariantCulture, "(.NET CLR {0}; {1} {2})", Environment.Version, Environment.OSVersion.Platform, Environment.OSVersion.Version); #endif UserAgent = UserAgentProductName + "/" + UserAgentProductVersion + " " + UserAgentComment; } /// <summary> /// Specifies the value to use for UserAgent header. /// </summary> public static readonly string UserAgent; /// <summary> /// Specifies the comment to use for UserAgent header. /// </summary> public static readonly string UserAgentComment; /// <summary> /// Specifies the value to use for UserAgent header. /// </summary> public const string UserAgentProductName = "WA-Storage"; /// <summary> /// Specifies the value to use for UserAgent header. /// </summary> #if ASPNET_K || PORTABLE public const string UserAgentProductVersion = "5.0.3-preview"; #else public const string UserAgentProductVersion = "5.0.2"; #endif /// <summary> /// Master Windows Azure Storage header prefix. /// </summary> public const string PrefixForStorageHeader = "x-ms-"; /// <summary> /// True Header. /// </summary> public const string TrueHeader = "true"; /// <summary> /// False Header. /// </summary> public const string FalseHeader = "false"; /// <summary> /// Header prefix for properties. /// </summary> public const string PrefixForStorageProperties = "x-ms-prop-"; /// <summary> /// Header prefix for metadata. /// </summary> public const string PrefixForStorageMetadata = "x-ms-meta-"; /// <summary> /// Header that specifies content disposition. /// </summary> public const string ContentDispositionResponseHeader = "Content-Disposition"; /// <summary> /// Header that specifies content length. /// </summary> public const string ContentLengthHeader = "Content-Length"; /// <summary> /// Header that specifies content language. /// </summary> public const string ContentLanguageHeader = "Content-Language"; /// <summary> /// Header that specifies the ETag value for the resource. /// </summary> public const string EtagHeader = "ETag"; /// <summary> /// Header for data ranges. /// </summary> public const string RangeHeader = PrefixForStorageHeader + "range"; /// <summary> /// Header for range content MD5. /// </summary> public const string RangeContentMD5Header = PrefixForStorageHeader + "range-get-content-md5"; /// <summary> /// Header for storage version. /// </summary> public const string StorageVersionHeader = PrefixForStorageHeader + "version"; /// <summary> /// Header for copy source. /// </summary> public const string CopySourceHeader = PrefixForStorageHeader + "copy-source"; /// <summary> /// Header for the If-Match condition. /// </summary> public const string SourceIfMatchHeader = PrefixForStorageHeader + "source-if-match"; /// <summary> /// Header for the If-Modified-Since condition. /// </summary> public const string SourceIfModifiedSinceHeader = PrefixForStorageHeader + "source-if-modified-since"; /// <summary> /// Header for the If-None-Match condition. /// </summary> public const string SourceIfNoneMatchHeader = PrefixForStorageHeader + "source-if-none-match"; /// <summary> /// Header for the If-Unmodified-Since condition. /// </summary> public const string SourceIfUnmodifiedSinceHeader = PrefixForStorageHeader + "source-if-unmodified-since"; /// <summary> /// Header for the file type. /// </summary> public const string FileType = PrefixForStorageHeader + "type"; /// <summary> /// Header that specifies file caching control. /// </summary> public const string FileCacheControlHeader = PrefixForStorageHeader + "cache-control"; /// <summary> /// Request header that specifies the file content disposition. /// </summary> public const string FileContentDispositionRequestHeader = PrefixForStorageHeader + "content-disposition"; /// <summary> /// Header that specifies file content encoding. /// </summary> public const string FileContentEncodingHeader = PrefixForStorageHeader + "content-encoding"; /// <summary> /// Header that specifies file content language. /// </summary> public const string FileContentLanguageHeader = PrefixForStorageHeader + "content-language"; /// <summary> /// Header that specifies file content MD5. /// </summary> public const string FileContentMD5Header = PrefixForStorageHeader + "content-md5"; /// <summary> /// Header that specifies file content type. /// </summary> public const string FileContentTypeHeader = PrefixForStorageHeader + "content-type"; /// <summary> /// Header that specifies file content length. /// </summary> public const string FileContentLengthHeader = PrefixForStorageHeader + "content-length"; /// <summary> /// Header that specifies the file write mode. /// </summary> public const string FileRangeWrite = PrefixForStorageHeader + "write"; /// <summary> /// Header for the blob type. /// </summary> public const string BlobType = PrefixForStorageHeader + "blob-type"; /// <summary> /// Header for snapshots. /// </summary> public const string SnapshotHeader = PrefixForStorageHeader + "snapshot"; /// <summary> /// Header to delete snapshots. /// </summary> public const string DeleteSnapshotHeader = PrefixForStorageHeader + "delete-snapshots"; /// <summary> /// Header that specifies blob caching control. /// </summary> public const string BlobCacheControlHeader = PrefixForStorageHeader + "blob-cache-control"; /// <summary> /// Request header that specifies the blob content disposition. /// </summary> public const string BlobContentDispositionRequestHeader = PrefixForStorageHeader + "blob-content-disposition"; /// <summary> /// Header that specifies blob content encoding. /// </summary> public const string BlobContentEncodingHeader = PrefixForStorageHeader + "blob-content-encoding"; /// <summary> /// Header that specifies blob content language. /// </summary> public const string BlobContentLanguageHeader = PrefixForStorageHeader + "blob-content-language"; /// <summary> /// Header that specifies blob content MD5. /// </summary> public const string BlobContentMD5Header = PrefixForStorageHeader + "blob-content-md5"; /// <summary> /// Header that specifies blob content type. /// </summary> public const string BlobContentTypeHeader = PrefixForStorageHeader + "blob-content-type"; /// <summary> /// Header that specifies blob content length. /// </summary> public const string BlobContentLengthHeader = PrefixForStorageHeader + "blob-content-length"; /// <summary> /// Header that specifies blob sequence number. /// </summary> public const string BlobSequenceNumber = PrefixForStorageHeader + "blob-sequence-number"; /// <summary> /// Header that specifies sequence number action. /// </summary> public const string SequenceNumberAction = PrefixForStorageHeader + "sequence-number-action"; /// <summary> /// Header that specifies committed block count. /// </summary> public const string BlobCommittedBlockCount = PrefixForStorageHeader + "blob-committed-block-count"; /// <summary> /// Header that specifies the blob append offset. /// </summary> public const string BlobAppendOffset = PrefixForStorageHeader + "blob-append-offset"; /// <summary> /// Header for the If-Sequence-Number-LE condition. /// </summary> public const string IfSequenceNumberLEHeader = PrefixForStorageHeader + "if-sequence-number-le"; /// <summary> /// Header for the If-Sequence-Number-LT condition. /// </summary> public const string IfSequenceNumberLTHeader = PrefixForStorageHeader + "if-sequence-number-lt"; /// <summary> /// Header for the If-Sequence-Number-EQ condition. /// </summary> public const string IfSequenceNumberEqHeader = PrefixForStorageHeader + "if-sequence-number-eq"; /// <summary> /// Header for the blob-condition-maxsize condition. /// </summary> public const string IfMaxSizeLessThanOrEqualHeader = PrefixForStorageHeader + "blob-condition-maxsize"; /// <summary> /// Header for the blob-condition-appendpos condition. /// </summary> public const string IfAppendPositionEqualHeader = PrefixForStorageHeader + "blob-condition-appendpos"; /// <summary> /// Header that specifies lease ID. /// </summary> public const string LeaseIdHeader = PrefixForStorageHeader + "lease-id"; /// <summary> /// Header that specifies lease status. /// </summary> public const string LeaseStatus = PrefixForStorageHeader + "lease-status"; /// <summary> /// Header that specifies lease status. /// </summary> public const string LeaseState = PrefixForStorageHeader + "lease-state"; /// <summary> /// Header that specifies page write mode. /// </summary> public const string PageWrite = PrefixForStorageHeader + "page-write"; /// <summary> /// Header that specifies approximate message count of a queue. /// </summary> public const string ApproximateMessagesCount = PrefixForStorageHeader + "approximate-messages-count"; /// <summary> /// Header that specifies the date. /// </summary> public const string Date = PrefixForStorageHeader + "date"; /// <summary> /// Header indicating the request ID. /// </summary> public const string RequestIdHeader = PrefixForStorageHeader + "request-id"; /// <summary> /// Header indicating the client request ID. /// </summary> public const string ClientRequestIdHeader = PrefixForStorageHeader + "client-request-id"; /// <summary> /// Header that specifies public access to blobs. /// </summary> public const string BlobPublicAccess = PrefixForStorageHeader + "blob-public-access"; /// <summary> /// Format string for specifying ranges. /// </summary> public const string RangeHeaderFormat = "bytes={0}-{1}"; /// <summary> /// Current storage version header value. /// Every time this version changes, assembly version needs to be updated as well. /// </summary> public const string TargetStorageVersion = "2015-02-21"; /// <summary> /// Specifies the file type. /// </summary> public const string File = "File"; /// <summary> /// Specifies the page blob type. /// </summary> public const string PageBlob = "PageBlob"; /// <summary> /// Specifies the block blob type. /// </summary> public const string BlockBlob = "BlockBlob"; /// <summary> /// Specifies the append blob type. /// </summary> public const string AppendBlob = "AppendBlob"; /// <summary> /// Specifies only snapshots are to be included. /// </summary> public const string SnapshotsOnlyValue = "only"; /// <summary> /// Specifies snapshots are to be included. /// </summary> public const string IncludeSnapshotsValue = "include"; /// <summary> /// Header that specifies the pop receipt for a message. /// </summary> public const string PopReceipt = PrefixForStorageHeader + "popreceipt"; /// <summary> /// Header that specifies the next visible time for a message. /// </summary> public const string NextVisibleTime = PrefixForStorageHeader + "time-next-visible"; /// <summary> /// Header that specifies whether to peek-only. /// </summary> public const string PeekOnly = "peekonly"; /// <summary> /// Header that specifies whether data in the container may be accessed publicly and what level of access is to be allowed. /// </summary> public const string ContainerPublicAccessType = PrefixForStorageHeader + "blob-public-access"; /// <summary> /// Header that specifies the lease action to perform. /// </summary> public const string LeaseActionHeader = PrefixForStorageHeader + "lease-action"; /// <summary> /// Header that specifies the proposed lease ID for a leasing operation. /// </summary> public const string ProposedLeaseIdHeader = PrefixForStorageHeader + "proposed-lease-id"; /// <summary> /// Header that specifies the duration of a lease. /// </summary> public const string LeaseDurationHeader = PrefixForStorageHeader + "lease-duration"; /// <summary> /// Header that specifies the break period of a lease. /// </summary> public const string LeaseBreakPeriodHeader = PrefixForStorageHeader + "lease-break-period"; /// <summary> /// Header that specifies the remaining lease time. /// </summary> public const string LeaseTimeHeader = PrefixForStorageHeader + "lease-time"; /// <summary> /// Header that specifies the key name for explicit keys. /// </summary> public const string KeyNameHeader = PrefixForStorageHeader + "key-name"; /// <summary> /// Header that specifies the copy ID. /// </summary> public const string CopyIdHeader = PrefixForStorageHeader + "copy-id"; /// <summary> /// Header that specifies the conclusion time of the last attempted blob copy operation /// where this blob was the destination blob. /// </summary> public const string CopyCompletionTimeHeader = PrefixForStorageHeader + "copy-completion-time"; /// <summary> /// Header that specifies the copy status. /// </summary> public const string CopyStatusHeader = PrefixForStorageHeader + "copy-status"; /// <summary> /// Header that specifies the copy progress. /// </summary> public const string CopyProgressHeader = PrefixForStorageHeader + "copy-progress"; /// <summary> /// Header that specifies a copy error message. /// </summary> public const string CopyDescriptionHeader = PrefixForStorageHeader + "copy-status-description"; /// <summary> /// Header that specifies the copy action. /// </summary> public const string CopyActionHeader = PrefixForStorageHeader + "copy-action"; /// <summary> /// The value of the copy action header that signifies an abort operation. /// </summary> public const string CopyActionAbort = "abort"; /// <summary> /// Header that specifies the share size, in gigabytes. /// </summary> public const string ShareSize = PrefixForStorageHeader + "share-size"; /// <summary> /// Header that specifies the share quota, in gigabytes. /// </summary> public const string ShareQuota = PrefixForStorageHeader + "share-quota"; /// <summary> /// Header that specifies the Accept type for the response payload. /// </summary> internal const string PayloadAcceptHeader = "Accept"; /// <summary> /// Header that specifies the Content type for the request payload. /// </summary> internal const string PayloadContentTypeHeader = "Content-Type"; } /// <summary> /// Constants for query strings. /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Reviewed.")] public static class QueryConstants { /// <summary> /// Query component for snapshot time. /// </summary> public const string Snapshot = "snapshot"; /// <summary> /// Query component for the signed SAS start time. /// </summary> public const string SignedStart = "st"; /// <summary> /// Query component for the signed SAS expiry time. /// </summary> public const string SignedExpiry = "se"; /// <summary> /// Query component for the signed SAS resource. /// </summary> public const string SignedResource = "sr"; /// <summary> /// Query component for the SAS table name. /// </summary> public const string SasTableName = "tn"; /// <summary> /// Query component for the signed SAS permissions. /// </summary> public const string SignedPermissions = "sp"; /// <summary> /// Query component for the SAS start partition key. /// </summary> public const string StartPartitionKey = "spk"; /// <summary> /// Query component for the SAS start row key. /// </summary> public const string StartRowKey = "srk"; /// <summary> /// Query component for the SAS end partition key. /// </summary> public const string EndPartitionKey = "epk"; /// <summary> /// Query component for the SAS end row key. /// </summary> public const string EndRowKey = "erk"; /// <summary> /// Query component for the signed SAS identifier. /// </summary> public const string SignedIdentifier = "si"; /// <summary> /// Query component for the signing SAS key. /// </summary> public const string SignedKey = "sk"; /// <summary> /// Query component for the signed SAS version. /// </summary> public const string SignedVersion = "sv"; /// <summary> /// Query component for SAS signature. /// </summary> public const string Signature = "sig"; /// <summary> /// Query component for SAS cache control. /// </summary> public const string CacheControl = "rscc"; /// <summary> /// Query component for SAS content type. /// </summary> public const string ContentType = "rsct"; /// <summary> /// Query component for SAS content encoding. /// </summary> public const string ContentEncoding = "rsce"; /// <summary> /// Query component for SAS content language. /// </summary> public const string ContentLanguage = "rscl"; /// <summary> /// Query component for SAS content disposition. /// </summary> public const string ContentDisposition = "rscd"; /// <summary> /// Query component for SAS API version. /// </summary> public const string ApiVersion = "api-version"; /// <summary> /// Query component for message time-to-live. /// </summary> public const string MessageTimeToLive = "messagettl"; /// <summary> /// Query component for message visibility timeout. /// </summary> public const string VisibilityTimeout = "visibilitytimeout"; /// <summary> /// Query component for the number of messages. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Num", Justification = "Reviewed : Num is allowed in an identifier name.")] public const string NumOfMessages = "numofmessages"; /// <summary> /// Query component for message pop receipt. /// </summary> public const string PopReceipt = "popreceipt"; /// <summary> /// Query component for resource type. /// </summary> public const string ResourceType = "restype"; /// <summary> /// Query component for the operation (component) to access. /// </summary> public const string Component = "comp"; /// <summary> /// Query component for the copy ID. /// </summary> public const string CopyId = "copyid"; } /// <summary> /// Constants for Result Continuations /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Reviewed.")] public static class ContinuationConstants { /// <summary> /// Top Element for Continuation Tokens /// </summary> public const string ContinuationTopElement = "ContinuationToken"; /// <summary> /// XML element for the next marker. /// </summary> public const string NextMarkerElement = "NextMarker"; /// <summary> /// XML element for the next partition key. /// </summary> public const string NextPartitionKeyElement = "NextPartitionKey"; /// <summary> /// XML element for the next row key. /// </summary> public const string NextRowKeyElement = "NextRowKey"; /// <summary> /// XML element for the next table name. /// </summary> public const string NextTableNameElement = "NextTableName"; /// <summary> /// XML element for the target location. /// </summary> public const string TargetLocationElement = "TargetLocation"; /// <summary> /// XML element for the token version. /// </summary> public const string VersionElement = "Version"; /// <summary> /// Stores the current token version value. /// </summary> public const string CurrentVersion = "2.0"; /// <summary> /// XML element for the token type. /// </summary> public const string TypeElement = "Type"; /// <summary> /// Specifies the blob continuation token type. /// </summary> public const string BlobType = "Blob"; /// <summary> /// Specifies the queue continuation token type. /// </summary> public const string QueueType = "Queue"; /// <summary> /// Specifies the table continuation token type. /// </summary> public const string TableType = "Table"; /// <summary> /// Specifies the file continuation token type. /// </summary> public const string FileType = "File"; } /// <summary> /// Constants for version strings /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Reviewed.")] public static class VersionConstants { /// <summary> /// Constant for the 2013-08-15 version. /// </summary> public const string August2013 = "2013-08-15"; /// <summary> /// Constant for the 2012-02-12 version. /// </summary> public const string February2012 = "2012-02-12"; } /// <summary> /// Constants for analytics client /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Reviewed.")] public static class AnalyticsConstants { /// <summary> /// Constant for the logs container. /// </summary> public const string LogsContainer = "$logs"; /// <summary> /// Constant for the blob capacity metrics table. /// </summary> public const string MetricsCapacityBlob = "$MetricsCapacityBlob"; /// <summary> /// Constant for the blob service primary location hourly metrics table. /// </summary> public const string MetricsHourPrimaryTransactionsBlob = "$MetricsHourPrimaryTransactionsBlob"; /// <summary> /// Constant for the table service primary location hourly metrics table. /// </summary> public const string MetricsHourPrimaryTransactionsTable = "$MetricsHourPrimaryTransactionsTable"; /// <summary> /// Constant for the queue service primary location hourly metrics table. /// </summary> public const string MetricsHourPrimaryTransactionsQueue = "$MetricsHourPrimaryTransactionsQueue"; /// <summary> /// Constant for the blob service primary location minute metrics table. /// </summary> public const string MetricsMinutePrimaryTransactionsBlob = "$MetricsMinutePrimaryTransactionsBlob"; /// <summary> /// Constant for the table service primary location minute metrics table. /// </summary> public const string MetricsMinutePrimaryTransactionsTable = "$MetricsMinutePrimaryTransactionsTable"; /// <summary> /// Constant for the queue service primary location minute metrics table. /// </summary> public const string MetricsMinutePrimaryTransactionsQueue = "$MetricsMinutePrimaryTransactionsQueue"; /// <summary> /// Constant for the blob service secondary location hourly metrics table. /// </summary> public const string MetricsHourSecondaryTransactionsBlob = "$MetricsHourSecondaryTransactionsBlob"; /// <summary> /// Constant for the table service secondary location hourly metrics table. /// </summary> public const string MetricsHourSecondaryTransactionsTable = "$MetricsHourSecondaryTransactionsTable"; /// <summary> /// Constant for the queue service secondary location hourly metrics table. /// </summary> public const string MetricsHourSecondaryTransactionsQueue = "$MetricsHourSecondaryTransactionsQueue"; /// <summary> /// Constant for the blob service secondary location minute metrics table. /// </summary> public const string MetricsMinuteSecondaryTransactionsBlob = "$MetricsMinuteSecondaryTransactionsBlob"; /// <summary> /// Constant for the table service secondary location minute metrics table. /// </summary> public const string MetricsMinuteSecondaryTransactionsTable = "$MetricsMinuteSecondaryTransactionsTable"; /// <summary> /// Constant for the queue service secondary location minute metrics table. /// </summary> public const string MetricsMinuteSecondaryTransactionsQueue = "$MetricsMinuteSecondaryTransactionsQueue"; /// <summary> /// Constant for default logging version. /// </summary> public const string LoggingVersionV1 = "1.0"; /// <summary> /// Constant for default metrics version. /// </summary> public const string MetricsVersionV1 = "1.0"; } /// <summary> /// Constants for client encryption. /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Reviewed.")] public static class EncryptionConstants { /// <summary> /// Constant for the encryption protocol. /// </summary> internal const string EncryptionProtocolV1 = "1.0"; /// <summary> /// Encryption metadata key for key wrapping IV. /// </summary> internal const string KeyWrappingIV = "KeyWrappingIV"; /// <summary> /// Metadata header to store encryption materials. /// </summary> public const string BlobEncryptionData = "encryptiondata"; /// <summary> /// Property name to store the encryption metadata. /// </summary> public const string TableEncryptionKeyDetails = "_ClientEncryptionMetadata1"; /// <summary> /// Additional property name to store the encryption metadata. /// </summary> public const string TableEncryptionPropertyDetails = "_ClientEncryptionMetadata2"; } } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/main/java/com/hazelcast/client/config/XmlClientConfigBuilder.java
6920
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.config; import com.hazelcast.client.config.impl.ClientConfigSections; import com.hazelcast.client.config.impl.ClientDomConfigProcessor; import com.hazelcast.client.config.impl.XmlClientConfigLocator; import com.hazelcast.config.AbstractXmlConfigBuilder; import com.hazelcast.config.InvalidConfigurationException; import com.hazelcast.internal.config.ConfigLoader; import com.hazelcast.internal.nio.IOUtil; import com.hazelcast.internal.util.ExceptionUtil; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.spi.annotation.PrivateApi; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; import static com.hazelcast.internal.util.Preconditions.checkNotNull; import static com.hazelcast.internal.util.Preconditions.checkTrue; import static com.hazelcast.internal.util.StringUtil.LINE_SEPARATOR; import static com.hazelcast.internal.util.XmlUtil.getNsAwareDocumentBuilderFactory; /** * Loads the {@link com.hazelcast.client.config.ClientConfig} using XML. */ public class XmlClientConfigBuilder extends AbstractXmlConfigBuilder { private static final ILogger LOGGER = Logger.getLogger(XmlClientConfigBuilder.class); private final InputStream in; public XmlClientConfigBuilder(String resource) throws IOException { URL url = ConfigLoader.locateConfig(resource); checkTrue(url != null, "Could not load " + resource); this.in = url.openStream(); } public XmlClientConfigBuilder(File file) throws IOException { checkNotNull(file, "File is null!"); this.in = new FileInputStream(file); } public XmlClientConfigBuilder(URL url) throws IOException { checkNotNull(url, "URL is null!"); this.in = url.openStream(); } public XmlClientConfigBuilder(InputStream in) { this.in = in; } /** * Loads the client config using the following resolution mechanism: * <ol> * <li>first it checks if a system property 'hazelcast.client.config' is set. If it exist and * it begins with 'classpath:', then a classpath resource is loaded. Else it will assume it is a file * reference. The configuration file or resource will be loaded only if the postfix of its name ends * with `.xml`.</li> * <li>it checks if a hazelcast-client.xml is available in the working dir</li> * <li>it checks if a hazelcast-client.xml is available on the classpath</li> * <li>it loads the hazelcast-client-default.xml</li> * </ol> */ public XmlClientConfigBuilder() { this((XmlClientConfigLocator) null); } /** * Constructs a {@link XmlClientConfigBuilder} that loads the configuration * with the provided {@link XmlClientConfigLocator}. * <p> * If the provided {@link XmlClientConfigLocator} is {@code null}, a new * instance is created and the config is located in every possible * places. For these places, please see {@link XmlClientConfigLocator}. * <p> * If the provided {@link XmlClientConfigLocator} is not {@code null}, it * is expected that it already located the configuration XML to load * from. No further attempt to locate the configuration XML is made * if the configuration XML is not located already. * * @param locator the configured locator to use */ @PrivateApi public XmlClientConfigBuilder(XmlClientConfigLocator locator) { if (locator == null) { locator = new XmlClientConfigLocator(); locator.locateEverywhere(); } this.in = locator.getIn(); } @Override protected Document parse(InputStream inputStream) throws Exception { DocumentBuilder builder = getNsAwareDocumentBuilderFactory().newDocumentBuilder(); try { return builder.parse(inputStream); } catch (Exception e) { String msg = "Failed to parse Config Stream" + LINE_SEPARATOR + "Exception: " + e.getMessage() + LINE_SEPARATOR + "HazelcastClient startup interrupted."; LOGGER.severe(msg); throw new InvalidConfigurationException(e.getMessage(), e); } finally { IOUtil.closeResource(inputStream); } } public XmlClientConfigBuilder setProperties(Properties properties) { setPropertiesInternal(properties); return this; } @Override protected ConfigType getConfigType() { return ConfigType.CLIENT; } public ClientConfig build() { return build(Thread.currentThread().getContextClassLoader()); } public ClientConfig build(ClassLoader classLoader) { ClientConfig clientConfig = new ClientConfig(); build(clientConfig, classLoader); return clientConfig; } void build(ClientConfig clientConfig, ClassLoader classLoader) { clientConfig.setClassLoader(classLoader); try { parseAndBuildConfig(clientConfig); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } finally { IOUtil.closeResource(in); } } private void parseAndBuildConfig(ClientConfig clientConfig) throws Exception { Document doc = parse(in); Element root = doc.getDocumentElement(); checkRootElement(root); try { root.getTextContent(); } catch (Throwable e) { domLevel3 = false; } process(root); schemaValidation(root.getOwnerDocument()); new ClientDomConfigProcessor(domLevel3, clientConfig).buildConfig(root); } private void checkRootElement(Element root) { String rootNodeName = root.getNodeName(); if (!ClientConfigSections.HAZELCAST_CLIENT.getName().equals(rootNodeName)) { throw new InvalidConfigurationException("Invalid root element in xml configuration! " + "Expected: <" + ClientConfigSections.HAZELCAST_CLIENT.getName() + ">, Actual: <" + rootNodeName + ">."); } } }
apache-2.0
dvorka/mindraider
mr7/src/main/java/com/mindcognition/mindraider/application/model/tag/TagEntryImpl.java
4543
/* =========================================================================== Copyright 2002-2010 Martin Dvorak Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================== */ package com.mindcognition.mindraider.application.model.tag; import java.util.Hashtable; /** * Tag entry in the tag navigator hash. */ public class TagEntryImpl implements TagEntry { /** * number of references to tag */ int cardinality; /** * tag label */ String label; /** * tag URI */ String uri; /** * tagged resources */ private Hashtable<String,TaggedResourceEntry> resources; /** * Constructor. */ public TagEntryImpl() { } /** * Constructor. * * @param uri * @param label * @param cardinality */ public TagEntryImpl(String uri, String label, int cardinality) { resources=new Hashtable<String,TaggedResourceEntry>(); setTagUri(uri); setTagLabel(label); this.cardinality=cardinality; } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#getCardinality() */ public int getCardinality() { return cardinality; } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#getTagLabel() */ public String getTagLabel() { return label; } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#getTagUri() */ public String getTagUri() { return uri; } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#setCardinality() */ public void setCardinality(int cardinality) { this.cardinality=cardinality; } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#setTagLabel() */ public void setTagLabel(String label) { this.label=label.toLowerCase(); } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#setTagUri(java.lang.String) */ public void setTagUri(String uri) { this.uri=uri; } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#inc() */ public void inc() { cardinality++; } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#addResource(com.emental.tag.widget.TaggedResourceEntry) */ public void addResource(TaggedResourceEntry taggedResource) { // avoid duplicities if(taggedResource!=null) { if(resources.get(taggedResource.conceptUri)==null) { resources.put(taggedResource.conceptUri,taggedResource); } } } /* * (non-Javadoc) * @see com.emental.tag.widget.TagEntry#getResources() */ public TaggedResourceEntry[] getResources() { if(resources.size()==0) { return null; } else { TaggedResourceEntry[] resourceArray = resources.values().toArray(new TaggedResourceEntry[resources.size()]); return resourceArray; } } public void dec() { cardinality--; } public boolean isDead() { return cardinality<=0; } public String getTagLabelAsHtml() { return label.replaceAll("" , "&nbsp;"); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((uri == null) ? 0 : uri.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final TagEntryImpl other = (TagEntryImpl) obj; if (uri == null) { if (other.uri != null) return false; } else if (!uri.equals(other.uri)) return false; return true; } }
apache-2.0
mkjensen/barriers
src/com/martinkampjensen/thesis/model/BarrierTree.java
2079
/** * Copyright 2010-2011 Martin Kamp Jensen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.martinkampjensen.thesis.model; import java.io.Serializable; /** * A {@link BarrierTree} is a full binary tree that has a {@link Node} as its * root. The internal {@link Node}s represent barrier values between leaf * {@link Node}s. * * @see <a href="http://en.wikipedia.org/wiki/Binary_tree">Binary tree</a> */ public interface BarrierTree extends Serializable { /** * Calculates different measures that can be used to classify this object. * The method should only perform calculations the first time it is called. */ void calculateMeasures(); /** * Recalculates measures that depend on a value from a {@link BarrierForest} * which this object has been made a part of. * * @see #calculateMeasures() */ void recalculateMeasures(BarrierForest forest); // TODO: Document BarrierTree measures. int getNumberOfLeaves(); double getMinimumValue(); double getMinimumBarrierValue(); double getMaximumBarrierValue(); double getTotalBarrierValue(); double getTotalConnectionValue(); Node getMinimum(); Node getMinimumBarrier(); Node getMaximumBarrier(); /** * Returns the root of this tree. * * @return the root of this tree. */ Node getRoot(); /** * Traverses the tree and returns the node with a specific id. * * @param id id of the node to find. * @return the node if it exists, or <code>null</code>. */ Node find(int id); }
apache-2.0
kidaa/aurora
src/test/java/org/apache/aurora/scheduler/cron/quartz/AuroraCronJobTest.java
5386
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aurora.scheduler.cron.quartz; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.twitter.common.base.Supplier; import com.twitter.common.testing.easymock.EasyMockTest; import com.twitter.common.util.BackoffHelper; import org.apache.aurora.gen.AssignedTask; import org.apache.aurora.gen.CronCollisionPolicy; import org.apache.aurora.gen.ScheduleStatus; import org.apache.aurora.gen.ScheduledTask; import org.apache.aurora.scheduler.state.StateChangeResult; import org.apache.aurora.scheduler.state.StateManager; import org.apache.aurora.scheduler.storage.Storage; import org.apache.aurora.scheduler.storage.db.DbUtil; import org.apache.aurora.scheduler.storage.entities.IScheduledTask; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.quartz.JobExecutionException; import static org.apache.aurora.scheduler.storage.Storage.MutableStoreProvider; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class AuroraCronJobTest extends EasyMockTest { public static final String TASK_ID = "A"; private Storage storage; private StateManager stateManager; private BackoffHelper backoffHelper; private AuroraCronJob auroraCronJob; @Before public void setUp() { storage = DbUtil.createStorage(); stateManager = createMock(StateManager.class); backoffHelper = createMock(BackoffHelper.class); auroraCronJob = new AuroraCronJob( new AuroraCronJob.Config(backoffHelper), storage, stateManager); } @Test public void testExecuteNonexistentIsNoop() throws JobExecutionException { control.replay(); auroraCronJob.doExecute(QuartzTestUtil.AURORA_JOB_KEY); } @Test public void testEmptyStorage() throws JobExecutionException { stateManager.insertPendingTasks( EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject()); expectLastCall().times(3); control.replay(); populateStorage(CronCollisionPolicy.CANCEL_NEW); auroraCronJob.doExecute(QuartzTestUtil.AURORA_JOB_KEY); storage = DbUtil.createStorage(); populateStorage(CronCollisionPolicy.KILL_EXISTING); auroraCronJob.doExecute(QuartzTestUtil.AURORA_JOB_KEY); storage = DbUtil.createStorage(); populateStorage(CronCollisionPolicy.RUN_OVERLAP); auroraCronJob.doExecute(QuartzTestUtil.AURORA_JOB_KEY); } @Test public void testCancelNew() throws JobExecutionException { control.replay(); populateTaskStore(); populateStorage(CronCollisionPolicy.CANCEL_NEW); auroraCronJob.doExecute(QuartzTestUtil.AURORA_JOB_KEY); } @Test public void testKillExisting() throws Exception { Capture<Supplier<Boolean>> capture = createCapture(); expect(stateManager.changeState( EasyMock.anyObject(), eq(TASK_ID), eq(Optional.absent()), eq(ScheduleStatus.KILLING), eq(AuroraCronJob.KILL_AUDIT_MESSAGE))) .andReturn(StateChangeResult.SUCCESS); backoffHelper.doUntilSuccess(EasyMock.capture(capture)); stateManager.insertPendingTasks( EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject()); control.replay(); populateStorage(CronCollisionPolicy.KILL_EXISTING); populateTaskStore(); auroraCronJob.doExecute(QuartzTestUtil.AURORA_JOB_KEY); assertFalse(capture.getValue().get()); storage.write( new Storage.MutateWork.NoResult.Quiet() { @Override public void execute(MutableStoreProvider storeProvider) { storeProvider.getUnsafeTaskStore().deleteAllTasks(); } }); assertTrue(capture.getValue().get()); } private void populateTaskStore() { storage.write(new Storage.MutateWork.NoResult.Quiet() { @Override public void execute(MutableStoreProvider storeProvider) { storeProvider.getUnsafeTaskStore().saveTasks(ImmutableSet.of( IScheduledTask.build(new ScheduledTask() .setStatus(ScheduleStatus.RUNNING) .setAssignedTask(new AssignedTask() .setTaskId(TASK_ID) .setTask(QuartzTestUtil.JOB.getTaskConfig().newBuilder()))) )); } }); } private void populateStorage(final CronCollisionPolicy policy) { storage.write(new Storage.MutateWork.NoResult.Quiet() { @Override public void execute(MutableStoreProvider storeProvider) { storeProvider.getCronJobStore().saveAcceptedJob( QuartzTestUtil.makeSanitizedCronJob(policy).getSanitizedConfig().getJobConfig()); } }); } }
apache-2.0
orientechnologies/orientdb-studio
src/app/administration/stats/security/security.component.ts
1254
import { Component, Input, ElementRef, NgZone, OnDestroy, ViewChild, OnInit, ViewContainerRef } from "@angular/core"; import { AgentService, MetricService, PermissionService } from "../../../core/services"; import { SecurityService } from "../../../core/services/security.service"; declare const angular: any; @Component({ selector: "security-management", templateUrl: "./security.component.html", styles: [""] }) class SecurityManagerComponent implements OnInit, OnDestroy { ee: boolean; security: any; tab = "auditing"; private databases: string[]; private canEdit = false; constructor( private agent: AgentService, private securityService: SecurityService, private metrics: MetricService, private permissionService: PermissionService ) {} ngOnInit(): void { this.ee = this.agent.active; if (this.ee) { this.canEdit = this.permissionService.isAllow("server.security.edit"); Promise.all([ this.metrics.listDatabases(), this.securityService.getConfig() ]).then(response => { this.databases = response[0].databases; this.security = response[1]; }); } } ngOnDestroy(): void {} } export { SecurityManagerComponent };
apache-2.0
henrichg/PhoneProfilesPlus
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/GeofenceScanWorker.java
21500
package sk.henrichg.phoneprofilesplus; import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Worker; import androidx.work.WorkerParameters; // DO NOT REMOVE. MUST EXISTS !!! @SuppressWarnings("unused") public class GeofenceScanWorker extends Worker { //private final Context context; static final String WORK_TAG = "GeofenceScannerJob"; static final String WORK_TAG_SHORT = "GeofenceScannerJobShort"; public GeofenceScanWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { super(context, workerParams); //this.context = context; } @NonNull @Override public Result doWork() { // PPApplication.logE("[IN_WORKER] GeofenceScanWorker.doWork", "xxxx"); /*try { //PPApplication.logE("GeofenceScanWorker.doWork", "---------------------------------------- START"); //CallsCounter.logCounter(context, "GeofenceScanWorker.doWork", "GeofenceScanWorker_doWork"); if (!PPApplication.getApplicationStarted(true)) // application is not started return Result.success(); if (Event.isEventPreferenceAllowed(EventPreferencesLocation.PREF_EVENT_LOCATION_ENABLED, context).allowed != PreferenceAllowed.PREFERENCE_ALLOWED) { cancelWork(false); //if (PPApplication.logEnabled()) { // PPApplication.logE("GeofenceScanWorker.doWork", "return - not allowed geofence scanning"); // PPApplication.logE("GeofenceScanWorker.doWork", "---------------------------------------- END"); //} return Result.success(); } //boolean isPowerSaveMode = PPApplication.isPowerSaveMode; boolean isPowerSaveMode = DataWrapper.isPowerSaveMode(context); if (isPowerSaveMode && ApplicationPreferences.applicationEventLocationUpdateInPowerSaveMode.equals("2")) { //PPApplication.logE("GeofenceScanWorker.doWork", "update in power save mode is not allowed"); cancelWork(false); //PPApplication.logE("GeofenceScanWorker.doWork", "---------------------------------------- END"); return Result.success(); } if (Event.getGlobalEventsRunning()) { boolean geofenceScannerUpdatesStarted = false; synchronized (PPApplication.locationScannerMutex) { if ((PhoneProfilesService.getInstance() != null) && (PhoneProfilesService.getInstance().getGeofencesScanner() != null)) { LocationScanner scanner = PhoneProfilesService.getInstance().getGeofencesScanner(); if (scanner.mUpdatesStarted) { //PPApplication.logE("GeofenceScanWorker.doWork", "location updates started - save to DB"); //if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isGeofenceScannerStarted()) scanner.updateGeofencesInDB(); geofenceScannerUpdatesStarted = true; } } } if (geofenceScannerUpdatesStarted) { //PPApplication.logE("GeofenceScanWorker.doWork", "location updates started - start EventsHandler"); // start events handler //PPApplication.logE("****** EventsHandler.handleEvents", "START run - from=GeofenceScanWorker.doWork"); // PPApplication.logE("[EVENTS_HANDLER_CALL] GeofenceScanWorker.doWork", "sensorType=SENSOR_TYPE_LOCATION_SCANNER"); EventsHandler eventsHandler = new EventsHandler(context); eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_LOCATION_SCANNER); //PPApplication.logE("****** EventsHandler.handleEvents", "END run - from=GeofenceScanWorker.doWork"); } } //PPApplication.logE("GeofenceScanWorker.doWork - handler", "schedule work"); //scheduleWork(context.getApplicationContext(), false); OneTimeWorkRequest worker = new OneTimeWorkRequest.Builder(MainWorker.class) .addTag(MainWorker.SCHEDULE_LONG_INTERVAL_GEOFENCE_WORK_TAG) //.setInitialDelay(200, TimeUnit.MILLISECONDS) .build(); try { WorkManager workManager = PPApplication.getWorkManagerInstance(); if (workManager != null) { // //if (PPApplication.logEnabled()) { // ListenableFuture<List<WorkInfo>> statuses; // statuses = workManager.getWorkInfosForUniqueWork(MainWorker.SCHEDULE_LONG_INTERVAL_GEOFENCE_WORK_TAG); // try { // List<WorkInfo> workInfoList = statuses.get(); // PPApplication.logE("[TEST BATTERY] GeofenceScanWorker.doWork", "for=" + MainWorker.SCHEDULE_LONG_INTERVAL_GEOFENCE_WORK_TAG + " workInfoList.size()=" + workInfoList.size()); // } catch (Exception ignored) { // } // //} workManager.enqueueUniqueWork(MainWorker.SCHEDULE_LONG_INTERVAL_GEOFENCE_WORK_TAG, ExistingWorkPolicy.REPLACE, worker); } } catch (Exception e) { PPApplication.recordException(e); }*/ /*PPApplication.startHandlerThreadPPScanners(); final Handler handler = new Handler(PPApplication.handlerThreadPPScanners.getLooper()); handler.postDelayed(new Runnable() { @Override public void run() { PPApplication.logE("GeofenceScanWorker.doWork - handler", "schedule work"); scheduleWork(context, false, null, false); } }, 500);*/ //PPApplication.logE("GeofenceScanWorker.doWork", "---------------------------------------- END"); return Result.success(); /*} catch (Exception e) { //Log.e("GeofenceScanWorker.doWork", Log.getStackTraceString(e)); PPApplication.recordException(e); //Handler _handler = new Handler(getApplicationContext().getMainLooper()); //Runnable r = new Runnable() { // public void run() { // android.os.Process.killProcess(PPApplication.pid); // } //}; //_handler.postDelayed(r, 1000); return Result.failure(); }*/ } /* public void onStopped () { //PPApplication.logE("GeofenceScanWorker.onStopped", "xxx"); //CallsCounter.logCounter(context, "GeofenceScanWorker.onStopped", "GeofenceScanWorker_onStopped"); } private static void _scheduleWork(final Context context, boolean shortInterval) { try { if (PPApplication.getApplicationStarted(true)) { WorkManager workManager = PPApplication.getWorkManagerInstance(); if (workManager != null) { //PPApplication.logE("GeofenceScanWorker._scheduleWork", "---------------------------------------- START"); int interval; synchronized (PPApplication.locationScannerMutex) { //if (PPApplication.logEnabled()) { // if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isLocationScannerStarted()) // PPApplication.logE("GeofenceScanWorker._scheduleWork", "mUpdatesStarted=" + PhoneProfilesService.getInstance().getGeofencesScanner().mUpdatesStarted); // else { // PPApplication.logE("GeofenceScanWorker._scheduleWork", "scanner is not started"); // PPApplication.logE("GeofenceScanWorker._scheduleWork", "PhoneProfilesService.getInstance()=" + PhoneProfilesService.getInstance()); // } //} // look at LocationScanner:UPDATE_INTERVAL_IN_MILLISECONDS //int updateDuration = 30; if ((PhoneProfilesService.getInstance() != null) && PhoneProfilesService.getInstance().isLocationScannerStarted() && PhoneProfilesService.getInstance().getGeofencesScanner().mUpdatesStarted) { interval = ApplicationPreferences.applicationEventLocationUpdateInterval * 60; //boolean isPowerSaveMode = PPApplication.isPowerSaveMode; boolean isPowerSaveMode = DataWrapper.isPowerSaveMode(context); if (isPowerSaveMode && ApplicationPreferences.applicationEventLocationUpdateInPowerSaveMode.equals("1")) interval = 2 * interval; //interval = interval - updateDuration; } else { interval = 5; shortInterval = true; } //PPApplication.logE("GeofenceScanWorker._scheduleWork", "interval=" + interval); } if (!shortInterval) { //PPApplication.logE("GeofenceScanWorker._scheduleWork", "delay work"); //int keepResultsDelay = (interval * 5); //if (keepResultsDelay < PPApplication.WORK_PRUNE_DELAY) // keepResultsDelay = PPApplication.WORK_PRUNE_DELAY; OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(GeofenceScanWorker.class) .setInitialDelay(interval, TimeUnit.SECONDS) .addTag(GeofenceScanWorker.WORK_TAG) .build(); // //if (PPApplication.logEnabled()) { // ListenableFuture<List<WorkInfo>> statuses; // statuses = workManager.getWorkInfosForUniqueWork(GeofenceScanWorker.WORK_TAG); // try { // List<WorkInfo> workInfoList = statuses.get(); // PPApplication.logE("[TEST BATTERY] GeofenceScanWorker._scheduleWork", "for=" + GeofenceScanWorker.WORK_TAG + " workInfoList.size()=" + workInfoList.size()); // } catch (Exception ignored) { // } // //} workManager.enqueueUniqueWork(GeofenceScanWorker.WORK_TAG, ExistingWorkPolicy.REPLACE, workRequest); } else { //PPApplication.logE("GeofenceScanWorker._scheduleWork", "start now work"); //waitForFinish(); OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(GeofenceScanWorker.class) .addTag(GeofenceScanWorker.WORK_TAG_SHORT) .build(); // //if (PPApplication.logEnabled()) { // ListenableFuture<List<WorkInfo>> statuses; // statuses = workManager.getWorkInfosForUniqueWork(GeofenceScanWorker.WORK_TAG_SHORT); // try { // List<WorkInfo> workInfoList = statuses.get(); // PPApplication.logE("[TEST BATTERY] GeofenceScanWorker._scheduleWork", "for=" + GeofenceScanWorker.WORK_TAG_SHORT + " workInfoList.size()=" + workInfoList.size()); // } catch (Exception ignored) { // } // //} workManager.enqueueUniqueWork(GeofenceScanWorker.WORK_TAG_SHORT, ExistingWorkPolicy.REPLACE, workRequest); } //PPApplication.logE("GeofenceScanWorker._scheduleWork", "---------------------------------------- END"); } } } catch (Exception e) { //Log.e("GeofenceScanWorker._scheduleWork", Log.getStackTraceString(e)); PPApplication.recordException(e); } } static void scheduleWork(final Context context, final boolean shortInterval) { //PPApplication.logE("GeofenceScanWorker.scheduleWork", "startScanning="+startScanning); PPApplication.startHandlerThreadPPScanners(); final Handler handler = new Handler(PPApplication.handlerThreadPPScanners.getLooper()); //if (shortInterval) { handler.post(new Runnable() { @Override public void run() { //PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadPPScanners", "START run - from=GeofenceScanWorker.scheduleWork" + " shortInterval="+shortInterval); _scheduleWork(context, shortInterval); } }); //} //else { // handler.postDelayed(new Runnable() { // @Override // public void run() { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadPPScanners", "START run - from=GeofenceScanWorker.scheduleWork"); // _scheduleWork(context, shortInterval); // } // }, 500); //} //else // PPApplication.logE("GeofenceScanWorker.scheduleWork", "scanner is not started"); } private static void _cancelWork() { if (isWorkScheduled(false) || isWorkScheduled(true)) { try { waitForFinish(false); waitForFinish(true); PPApplication.cancelWork(WORK_TAG); PPApplication.cancelWork(WORK_TAG_SHORT); //PPApplication.logE("GeofenceScanWorker._cancelWork", "CANCELED"); } catch (Exception e) { //Log.e("GeofenceScanWorker._cancelWork", Log.getStackTraceString(e)); PPApplication.recordException(e); } } } private static void waitForFinish(boolean shortWork) { if (!isWorkRunning(shortWork)) { //PPApplication.logE("GeofenceScanWorker.waitForFinish", "NOT RUNNING"); return; } try { if (PPApplication.getApplicationStarted(true)) { WorkManager workManager = PPApplication.getWorkManagerInstance(); if (workManager != null) { //PPApplication.logE("GeofenceScanWorker.waitForFinish", "START WAIT FOR FINISH"); long start = SystemClock.uptimeMillis(); do { ListenableFuture<List<WorkInfo>> statuses; if (shortWork) statuses = workManager.getWorkInfosForUniqueWork(WORK_TAG_SHORT); else statuses = workManager.getWorkInfosForUniqueWork(WORK_TAG); boolean allFinished = true; //noinspection TryWithIdenticalCatches try { List<WorkInfo> workInfoList = statuses.get(); //PPApplication.logE("[TEST BATTERY] GeofenceScanWorker.waitForFinish", "workInfoList.size()="+workInfoList.size()); for (WorkInfo workInfo : workInfoList) { WorkInfo.State state = workInfo.getState(); if (!state.isFinished()) { allFinished = false; break; } } } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } if (allFinished) { //PPApplication.logE("GeofenceScanWorker.waitForFinish", "FINISHED"); break; } PPApplication.sleep(500); } while (SystemClock.uptimeMillis() - start < 10 * 1000); //PPApplication.logE("GeofenceScanWorker.waitForFinish", "END WAIT FOR FINISH"); } } } catch (Exception e) { //Log.e("GeofenceScanWorker.waitForFinish", Log.getStackTraceString(e)); PPApplication.recordException(e); } } static void cancelWork(final boolean useHandler) { //PPApplication.logE("GeofenceScanWorker.cancelWork", "xxx"); if (useHandler) { PPApplication.startHandlerThreadPPScanners(); final Handler handler = new Handler(PPApplication.handlerThreadPPScanners.getLooper()); handler.post(new Runnable() { @Override public void run() { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadPPScanners", "START run - from=GeofenceScanWorker.cancelWork"); _cancelWork(); } }); } else { _cancelWork(); } } private static boolean isWorkRunning(boolean shortWork) { try { if (PPApplication.getApplicationStarted(true)) { WorkManager workManager = PPApplication.getWorkManagerInstance(); if (workManager != null) { ListenableFuture<List<WorkInfo>> statuses; if (shortWork) statuses = workManager.getWorkInfosForUniqueWork(WORK_TAG_SHORT); else statuses = workManager.getWorkInfosForUniqueWork(WORK_TAG); //noinspection TryWithIdenticalCatches try { List<WorkInfo> workInfoList = statuses.get(); //PPApplication.logE("[TEST BATTERY] GeofenceScanWorker.isWorkRunning", "workInfoList.size()="+workInfoList.size()); boolean running = false; for (WorkInfo workInfo : workInfoList) { WorkInfo.State state = workInfo.getState(); running = state == WorkInfo.State.RUNNING; break; } return running; } catch (ExecutionException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } } else return false; } else return false; } catch (Exception e) { //Log.e("GeofenceScanWorker.isWorkRunning", Log.getStackTraceString(e)); PPApplication.recordException(e); return false; } } static boolean isWorkScheduled(boolean shortWork) { //PPApplication.logE("GeofenceScanWorker.isWorkScheduled", "xxx"); try { if (PPApplication.getApplicationStarted(true)) { WorkManager workManager = PPApplication.getWorkManagerInstance(); if (workManager != null) { ListenableFuture<List<WorkInfo>> statuses; if (shortWork) statuses = workManager.getWorkInfosForUniqueWork(WORK_TAG_SHORT); else statuses = workManager.getWorkInfosForUniqueWork(WORK_TAG); //noinspection TryWithIdenticalCatches try { List<WorkInfo> workInfoList = statuses.get(); //PPApplication.logE("[TEST BATTERY] GeofenceScanWorker.isWorkScheduled", "workInfoList.size()="+workInfoList.size()); boolean running = false; for (WorkInfo workInfo : workInfoList) { WorkInfo.State state = workInfo.getState(); running = (state == WorkInfo.State.RUNNING) || (state == WorkInfo.State.ENQUEUED); break; } return running; } catch (ExecutionException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } } else return false; } else return false; } catch (Exception e) { //Log.e("GeofenceScanWorker.isWorkScheduled", Log.getStackTraceString(e)); PPApplication.recordException(e); return false; } } */ }
apache-2.0
yjwLEO/coolweather
app/src/main/java/com/example/coolweather/db/County.java
845
package com.example.coolweather.db; import org.litepal.crud.DataSupport; /** * Created by asus-pc on 2017/2/26. */ public class County extends DataSupport { private int id; private String countyName; private String weatherId; private int cityId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getWeatherId() { return weatherId; } public void setWeatherId(String weatherId) { this.weatherId = weatherId; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
apache-2.0
lpxz/grail-lucene358684
src/test/org/apache/lucene/TestSearch.java
4494
package org.apache.lucene; /** * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.GregorianCalendar; import java.io.PrintWriter; import java.io.StringWriter; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.lucene.store.*; import org.apache.lucene.document.*; import org.apache.lucene.analysis.*; import org.apache.lucene.index.*; import org.apache.lucene.search.*; import org.apache.lucene.queryParser.*; /** JUnit adaptation of an older test case SearchTest. * @author dmitrys@earthlink.net * @version $Id: TestSearch.java 150494 2004-09-06 22:29:22Z dnaber $ */ public class TestSearch extends TestCase { /** Main for running test case by itself. */ public static void main(String args[]) { TestRunner.run (new TestSuite(TestSearch.class)); } /** This test performs a number of searches. It also compares output * of searches using multi-file index segments with single-file * index segments. * * TODO: someone should check that the results of the searches are * still correct by adding assert statements. Right now, the test * passes if the results are the same between multi-file and * single-file formats, even if the results are wrong. */ public void testSearch() throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); doTestSearch(pw, false); pw.close(); sw.close(); String multiFileOutput = sw.getBuffer().toString(); //System.out.println(multiFileOutput); sw = new StringWriter(); pw = new PrintWriter(sw, true); doTestSearch(pw, true); pw.close(); sw.close(); String singleFileOutput = sw.getBuffer().toString(); assertEquals(multiFileOutput, singleFileOutput); } private void doTestSearch(PrintWriter out, boolean useCompoundFile) throws Exception { Directory directory = new RAMDirectory(); Analyzer analyzer = new SimpleAnalyzer(); IndexWriter writer = new IndexWriter(directory, analyzer, true); writer.setUseCompoundFile(useCompoundFile); String[] docs = { "a b c d e", "a b c d e a b c d e", "a b c d e f g h i j", "a c e", "e c a", "a c e a c e", "a c e a b c" }; for (int j = 0; j < docs.length; j++) { Document d = new Document(); d.add(new Field("contents", docs[j], Field.Store.YES, Field.Index.TOKENIZED)); writer.addDocument(d); } writer.close(); Searcher searcher = new IndexSearcher(directory); String[] queries = { "a b", "\"a b\"", "\"a b c\"", "a c", "\"a c\"", "\"a c e\"", }; Hits hits = null; QueryParser parser = new QueryParser("contents", analyzer); parser.setPhraseSlop(4); for (int j = 0; j < queries.length; j++) { Query query = parser.parse(queries[j]); out.println("Query: " + query.toString("contents")); //DateFilter filter = // new DateFilter("modified", Time(1997,0,1), Time(1998,0,1)); //DateFilter filter = DateFilter.Before("modified", Time(1997,00,01)); //System.out.println(filter); hits = searcher.search(query); out.println(hits.length() + " total results"); for (int i = 0 ; i < hits.length() && i < 10; i++) { Document d = hits.doc(i); out.println(i + " " + hits.score(i) // + " " + DateField.stringToDate(d.get("modified")) + " " + d.get("contents")); } } searcher.close(); } static long Time(int year, int month, int day) { GregorianCalendar calendar = new GregorianCalendar(); calendar.set(year, month, day); return calendar.getTime().getTime(); } }
apache-2.0
mahkoh/rust
src/libstd/sys/common/net2.rs
13396
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use ffi::CString; use io::{self, Error, ErrorKind}; use libc::{self, c_int, c_char, c_void, socklen_t}; use mem; use net::{SocketAddr, Shutdown}; use sys::c; use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t}; use sys_common::{AsInner, FromInner, IntoInner}; //////////////////////////////////////////////////////////////////////////////// // sockaddr and misc bindings //////////////////////////////////////////////////////////////////////////////// fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int, payload: T) -> io::Result<()> { unsafe { let payload = &payload as *const T as *const c_void; try!(cvt(libc::setsockopt(*sock.as_inner(), opt, val, payload, mem::size_of::<T>() as socklen_t))); Ok(()) } } #[allow(dead_code)] fn getsockopt<T: Copy>(sock: &Socket, opt: c_int, val: c_int) -> io::Result<T> { unsafe { let mut slot: T = mem::zeroed(); let mut len = mem::size_of::<T>() as socklen_t; let ret = try!(cvt(c::getsockopt(*sock.as_inner(), opt, val, &mut slot as *mut _ as *mut _, &mut len))); assert_eq!(ret as usize, mem::size_of::<T>()); Ok(slot) } } fn sockname<F>(f: F) -> io::Result<SocketAddr> where F: FnOnce(*mut libc::sockaddr, *mut socklen_t) -> c_int { unsafe { let mut storage: libc::sockaddr_storage = mem::zeroed(); let mut len = mem::size_of_val(&storage) as socklen_t; try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len))); sockaddr_to_addr(&storage, len as usize) } } fn sockaddr_to_addr(storage: &libc::sockaddr_storage, len: usize) -> io::Result<SocketAddr> { match storage.ss_family as libc::c_int { libc::AF_INET => { assert!(len as usize >= mem::size_of::<libc::sockaddr_in>()); Ok(SocketAddr::V4(FromInner::from_inner(unsafe { *(storage as *const _ as *const libc::sockaddr_in) }))) } libc::AF_INET6 => { assert!(len as usize >= mem::size_of::<libc::sockaddr_in6>()); Ok(SocketAddr::V6(FromInner::from_inner(unsafe { *(storage as *const _ as *const libc::sockaddr_in6) }))) } _ => { Err(Error::new(ErrorKind::InvalidInput, "invalid argument", None)) } } } //////////////////////////////////////////////////////////////////////////////// // get_host_addresses //////////////////////////////////////////////////////////////////////////////// extern "system" { fn getaddrinfo(node: *const c_char, service: *const c_char, hints: *const libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int; fn freeaddrinfo(res: *mut libc::addrinfo); } pub struct LookupHost { original: *mut libc::addrinfo, cur: *mut libc::addrinfo, } impl Iterator for LookupHost { type Item = io::Result<SocketAddr>; fn next(&mut self) -> Option<io::Result<SocketAddr>> { unsafe { if self.cur.is_null() { return None } let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr), (*self.cur).ai_addrlen as usize); self.cur = (*self.cur).ai_next as *mut libc::addrinfo; Some(ret) } } } impl Drop for LookupHost { fn drop(&mut self) { unsafe { freeaddrinfo(self.original) } } } pub fn lookup_host(host: &str) -> io::Result<LookupHost> { init(); let c_host = try!(CString::new(host)); let mut res = 0 as *mut _; unsafe { try!(cvt_gai(getaddrinfo(c_host.as_ptr(), 0 as *const _, 0 as *const _, &mut res))); Ok(LookupHost { original: res, cur: res }) } } //////////////////////////////////////////////////////////////////////////////// // TCP streams //////////////////////////////////////////////////////////////////////////////// pub struct TcpStream { inner: Socket, } impl TcpStream { pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> { init(); let sock = try!(Socket::new(addr, libc::SOCK_STREAM)); let (addrp, len) = addr.into_inner(); try!(cvt_r(|| unsafe { libc::connect(*sock.as_inner(), addrp, len) })); Ok(TcpStream { inner: sock }) } pub fn socket(&self) -> &Socket { &self.inner } pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int) } pub fn set_keepalive(&self, seconds: Option<u32>) -> io::Result<()> { let ret = setsockopt(&self.inner, libc::SOL_SOCKET, libc::SO_KEEPALIVE, seconds.is_some() as c_int); match seconds { Some(n) => ret.and_then(|()| self.set_tcp_keepalive(n)), None => ret, } } #[cfg(any(target_os = "macos", target_os = "ios"))] fn set_tcp_keepalive(&self, seconds: u32) -> io::Result<()> { setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE, seconds as c_int) } #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] fn set_tcp_keepalive(&self, seconds: u32) -> io::Result<()> { setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE, seconds as c_int) } #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "dragonfly")))] fn set_tcp_keepalive(&self, _seconds: u32) -> io::Result<()> { Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.inner.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { let ret = try!(cvt(unsafe { libc::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, buf.len() as wrlen_t, 0) })); Ok(ret as usize) } pub fn peer_addr(&self) -> io::Result<SocketAddr> { sockname(|buf, len| unsafe { libc::getpeername(*self.inner.as_inner(), buf, len) }) } pub fn socket_addr(&self) -> io::Result<SocketAddr> { sockname(|buf, len| unsafe { libc::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { use libc::consts::os::bsd44::SHUT_RDWR; let how = match how { Shutdown::Write => libc::SHUT_WR, Shutdown::Read => libc::SHUT_RD, Shutdown::Both => SHUT_RDWR, }; try!(cvt(unsafe { libc::shutdown(*self.inner.as_inner(), how) })); Ok(()) } pub fn duplicate(&self) -> io::Result<TcpStream> { self.inner.duplicate().map(|s| TcpStream { inner: s }) } } //////////////////////////////////////////////////////////////////////////////// // TCP listeners //////////////////////////////////////////////////////////////////////////////// pub struct TcpListener { inner: Socket, } impl TcpListener { pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> { init(); let sock = try!(Socket::new(addr, libc::SOCK_STREAM)); // On platforms with Berkeley-derived sockets, this allows // to quickly rebind a socket, without needing to wait for // the OS to clean up the previous one. if !cfg!(windows) { try!(setsockopt(&sock, libc::SOL_SOCKET, libc::SO_REUSEADDR, 1 as c_int)); } // Bind our new socket let (addrp, len) = addr.into_inner(); try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) })); // Start listening try!(cvt(unsafe { libc::listen(*sock.as_inner(), 128) })); Ok(TcpListener { inner: sock }) } pub fn socket(&self) -> &Socket { &self.inner } pub fn socket_addr(&self) -> io::Result<SocketAddr> { sockname(|buf, len| unsafe { libc::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; let mut len = mem::size_of_val(&storage) as socklen_t; let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)); let addr = try!(sockaddr_to_addr(&storage, len as usize)); Ok((TcpStream { inner: sock, }, addr)) } pub fn duplicate(&self) -> io::Result<TcpListener> { self.inner.duplicate().map(|s| TcpListener { inner: s }) } } //////////////////////////////////////////////////////////////////////////////// // UDP //////////////////////////////////////////////////////////////////////////////// pub struct UdpSocket { inner: Socket, } impl UdpSocket { pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> { init(); let sock = try!(Socket::new(addr, libc::SOCK_DGRAM)); let (addrp, len) = addr.into_inner(); try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) })); Ok(UdpSocket { inner: sock }) } pub fn socket(&self) -> &Socket { &self.inner } pub fn socket_addr(&self) -> io::Result<SocketAddr> { sockname(|buf, len| unsafe { libc::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; let mut addrlen = mem::size_of_val(&storage) as socklen_t; let n = try!(cvt(unsafe { libc::recvfrom(*self.inner.as_inner(), buf.as_mut_ptr() as *mut c_void, buf.len() as wrlen_t, 0, &mut storage as *mut _ as *mut _, &mut addrlen) })); Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize)))) } pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> { let (dstp, dstlen) = dst.into_inner(); let ret = try!(cvt(unsafe { libc::sendto(*self.inner.as_inner(), buf.as_ptr() as *const c_void, buf.len() as wrlen_t, 0, dstp, dstlen) })); Ok(ret as usize) } pub fn set_broadcast(&self, on: bool) -> io::Result<()> { setsockopt(&self.inner, libc::SOL_SOCKET, libc::SO_BROADCAST, on as c_int) } pub fn set_multicast_loop(&self, on: bool) -> io::Result<()> { setsockopt(&self.inner, libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP, on as c_int) } pub fn join_multicast(&self, multi: &SocketAddr) -> io::Result<()> { match *multi { SocketAddr::V4(..) => { self.set_membership(multi, libc::IP_ADD_MEMBERSHIP) } SocketAddr::V6(..) => { self.set_membership(multi, libc::IPV6_ADD_MEMBERSHIP) } } } pub fn leave_multicast(&self, multi: &SocketAddr) -> io::Result<()> { match *multi { SocketAddr::V4(..) => { self.set_membership(multi, libc::IP_DROP_MEMBERSHIP) } SocketAddr::V6(..) => { self.set_membership(multi, libc::IPV6_DROP_MEMBERSHIP) } } } fn set_membership(&self, addr: &SocketAddr, opt: c_int) -> io::Result<()> { match *addr { SocketAddr::V4(ref addr) => { let mreq = libc::ip_mreq { imr_multiaddr: *addr.ip().as_inner(), // interface == INADDR_ANY imr_interface: libc::in_addr { s_addr: 0x0 }, }; setsockopt(&self.inner, libc::IPPROTO_IP, opt, mreq) } SocketAddr::V6(ref addr) => { let mreq = libc::ip6_mreq { ipv6mr_multiaddr: *addr.ip().as_inner(), ipv6mr_interface: 0, }; setsockopt(&self.inner, libc::IPPROTO_IPV6, opt, mreq) } } } pub fn multicast_time_to_live(&self, ttl: i32) -> io::Result<()> { setsockopt(&self.inner, libc::IPPROTO_IP, libc::IP_MULTICAST_TTL, ttl as c_int) } pub fn time_to_live(&self, ttl: i32) -> io::Result<()> { setsockopt(&self.inner, libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int) } pub fn duplicate(&self) -> io::Result<UdpSocket> { self.inner.duplicate().map(|s| UdpSocket { inner: s }) } }
apache-2.0
zhangtengteng/AnyTime-master
src/com/luna/anytime/PersonActivity.java
1240
package com.luna.anytime; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class PersonActivity extends Activity { TextView nameTextView; TextView registerTimeTextView; public PersonActivity() { } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_gerenzhongxin); // nameTextView = (TextView)findViewById(R.id.textView_userName); // registerTimeTextView = (TextView)findViewById(R.id.textView_register_time); // // AVUser currentUser = AVUser.getCurrentUser(); // nameTextView.setText(currentUser.getUsername()); // String date = DateFormat.format("yyyy-MM-dd HH:mm", // currentUser.getCreatedAt()).toString(); // registerTimeTextView.setText(getString(R.string.person_register_time) // .replace("{0}", date)); TextView loginout = (TextView) findViewById(R.id.tv_logout); loginout.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { AVService.logout(); PersonActivity.this.finish(); } }); } }
apache-2.0
epam/DLab
infrastructure-provisioning/src/tensor-rstudio/fabfile.py
8766
#!/usr/bin/python # ***************************************************************************** # # Copyright (c) 2016, EPAM SYSTEMS INC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ****************************************************************************** import logging import json import sys from dlab.fab import * from dlab.meta_lib import * from dlab.actions_lib import * import os import uuid # Main function for provisioning notebook server def run(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) notebook_config = dict() notebook_config['uuid'] = str(uuid.uuid4())[:5] try: params = "--uuid {}".format(notebook_config['uuid']) local("~/scripts/{}.py {}".format('common_prepare_notebook', params)) except Exception as err: traceback.print_exc() append_result("Failed preparing Notebook node.", str(err)) sys.exit(1) try: params = "--uuid {}".format(notebook_config['uuid']) local("~/scripts/{}.py {}".format('tensor-rstudio_configure', params)) except Exception as err: traceback.print_exc() append_result("Failed configuring Notebook node.", str(err)) sys.exit(1) # Main function for terminating exploratory environment def terminate(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('common_terminate_notebook')) except Exception as err: traceback.print_exc() append_result("Failed terminating Notebook node.", str(err)) sys.exit(1) # Main function for stopping notebook server def stop(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('common_stop_notebook')) except Exception as err: traceback.print_exc() append_result("Failed stopping Notebook node.", str(err)) sys.exit(1) # Main function for starting notebook server def start(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('common_start_notebook')) except Exception as err: traceback.print_exc() append_result("Failed starting Notebook node.", str(err)) sys.exit(1) # Main function for configuring notebook server after deploying DataEngine service def configure(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: if os.environ['conf_resource'] == 'dataengine': local("~/scripts/{}.py".format('common_notebook_configure_dataengine')) except Exception as err: traceback.print_exc() append_result("Failed configuring dataengine on Notebook node.", str(err)) sys.exit(1) # Main function for installing additional libraries for notebook def install_libs(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('notebook_install_libs')) except Exception as err: traceback.print_exc() append_result("Failed installing additional libs for Notebook node.", str(err)) sys.exit(1) # Main function for get available libraries for notebook def list_libs(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('notebook_list_libs')) except Exception as err: traceback.print_exc() append_result("Failed get available libraries for notebook node.", str(err)) sys.exit(1) # Main function for manage git credentials on notebook def git_creds(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('notebook_git_creds')) except Exception as err: traceback.print_exc() append_result("Failed to manage git credentials for notebook node.", str(err)) sys.exit(1) # Main function for creating image from notebook def create_image(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('common_create_notebook_image')) except Exception as err: traceback.print_exc() append_result("Failed to create image from notebook node.", str(err)) sys.exit(1) # Main function for deleting existing notebook image def terminate_image(): local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: local("~/scripts/{}.py".format('common_terminate_notebook_image')) except Exception as err: traceback.print_exc() append_result("Failed to create image from notebook node.", str(err)) sys.exit(1)
apache-2.0
bowenli86/flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/io/benchmark/SingleInputGateBenchmarkFactory.java
6454
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.runtime.io.benchmark; import org.apache.flink.core.memory.MemorySegmentProvider; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.io.network.ConnectionID; import org.apache.flink.runtime.io.network.ConnectionManager; import org.apache.flink.runtime.io.network.TaskEventPublisher; import org.apache.flink.runtime.io.network.buffer.NetworkBufferPool; import org.apache.flink.runtime.io.network.metrics.InputChannelMetrics; import org.apache.flink.runtime.io.network.partition.ResultPartitionID; import org.apache.flink.runtime.io.network.partition.ResultPartitionManager; import org.apache.flink.runtime.io.network.partition.consumer.InputChannel; import org.apache.flink.runtime.io.network.partition.consumer.LocalInputChannel; import org.apache.flink.runtime.io.network.partition.consumer.RemoteInputChannel; import org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate; import org.apache.flink.runtime.io.network.partition.consumer.SingleInputGateFactory; import org.apache.flink.runtime.shuffle.NettyShuffleDescriptor; import org.apache.flink.runtime.taskmanager.NettyShuffleEnvironmentConfiguration; import java.io.IOException; /** * A benchmark-specific input gate factory which overrides the respective methods of creating * {@link RemoteInputChannel} and {@link LocalInputChannel} for requesting specific subpartitions. */ public class SingleInputGateBenchmarkFactory extends SingleInputGateFactory { public SingleInputGateBenchmarkFactory( ResourceID taskExecutorResourceId, NettyShuffleEnvironmentConfiguration networkConfig, ConnectionManager connectionManager, ResultPartitionManager partitionManager, TaskEventPublisher taskEventPublisher, NetworkBufferPool networkBufferPool) { super( taskExecutorResourceId, networkConfig, connectionManager, partitionManager, taskEventPublisher, networkBufferPool); } @Override protected InputChannel createKnownInputChannel( SingleInputGate inputGate, int index, NettyShuffleDescriptor inputChannelDescriptor, SingleInputGateFactory.ChannelStatistics channelStatistics, InputChannelMetrics metrics) { ResultPartitionID partitionId = inputChannelDescriptor.getResultPartitionID(); if (inputChannelDescriptor.isLocalTo(taskExecutorResourceId)) { return new TestLocalInputChannel( inputGate, index, partitionId, partitionManager, taskEventPublisher, partitionRequestInitialBackoff, partitionRequestMaxBackoff, metrics); } else { return new TestRemoteInputChannel( inputGate, index, partitionId, inputChannelDescriptor.getConnectionId(), connectionManager, partitionRequestInitialBackoff, partitionRequestMaxBackoff, metrics, networkBufferPool); } } /** * A {@link LocalInputChannel} which ignores the given subpartition index and uses channel index * instead when requesting subpartition. */ static class TestLocalInputChannel extends LocalInputChannel { private final ResultPartitionID newPartitionID = new ResultPartitionID(); public TestLocalInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartitionID partitionId, ResultPartitionManager partitionManager, TaskEventPublisher taskEventPublisher, int initialBackoff, int maxBackoff, InputChannelMetrics metrics) { super( inputGate, channelIndex, partitionId, partitionManager, taskEventPublisher, initialBackoff, maxBackoff, metrics); } @Override public void requestSubpartition(int subpartitionIndex) throws IOException { super.requestSubpartition(getChannelIndex()); } @Override public ResultPartitionID getPartitionId() { // the SingleInputGate assumes that all InputChannels are consuming different ResultPartition // so can be distinguished by ResultPartitionID. However, the micro benchmark breaks this and // all InputChannels in a SingleInputGate consume data from the same ResultPartition. To make // it transparent to SingleInputGate, a new and unique ResultPartitionID is returned here return newPartitionID; } } /** * A {@link RemoteInputChannel} which ignores the given subpartition index and uses channel index * instead when requesting subpartition. */ static class TestRemoteInputChannel extends RemoteInputChannel { private final ResultPartitionID newPartitionID = new ResultPartitionID(); public TestRemoteInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartitionID partitionId, ConnectionID connectionId, ConnectionManager connectionManager, int initialBackOff, int maxBackoff, InputChannelMetrics metrics, MemorySegmentProvider memorySegmentProvider) { super( inputGate, channelIndex, partitionId, connectionId, connectionManager, initialBackOff, maxBackoff, metrics, memorySegmentProvider); } @Override public void requestSubpartition(int subpartitionIndex) throws IOException, InterruptedException { super.requestSubpartition(getChannelIndex()); } @Override public ResultPartitionID getPartitionId() { // the SingleInputGate assumes that all InputChannels are consuming different ResultPartition // so can be distinguished by ResultPartitionID. However, the micro benchmark breaks this and // all InputChannels in a SingleInputGate consume data from the same ResultPartition. To make // it transparent to SingleInputGate, a new and unique ResultPartitionID is returned here return newPartitionID; } } }
apache-2.0
openegovplatform/OEPv2
oep-core-logging-portlet/docroot/WEB-INF/src/org/oep/core/logging/PortletKeys.java
1466
/** * Copyright (c) 2015 by Open eGovPlatform (http://http://openegovplatform.org/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.oep.core.logging; public class PortletKeys { public static final int PAGE = 1; public static final int DELTA = 10; public static final long LONG_DEFAULT = 0; public static final String STRING_DEFAULT = ""; public static final long SELECT_BOX = -1; public static final String TEXT_BOX = STRING_DEFAULT; public static final boolean CHECK_BOX = false; public static final long TREE_ROOT_ID = -1; public static final String SET_VIEW_PARAMETER = "jspPage"; public static final String REDIRECT_PAGE = "redirectPage"; public static final String ERROR_REDIRECT_PAGE = "errorRedirectPage"; public static final String SUCCESS_REDIRECT_PAGE = "successRedirectPage"; public class SearchContainer { public static final String CURRENT_PAGE = "cur"; public static final String DELTA = "delta"; } }
apache-2.0
rbraeunlich/formic
linear/shared/src/main/scala/de/tu_berlin/formic/datastructure/linear/client/FormicList.scala
2751
package de.tu_berlin.formic.datastructure.linear.client import akka.pattern._ import akka.util.Timeout import de.tu_berlin.formic.common.datastructure.FormicDataStructure.LocalOperationMessage import de.tu_berlin.formic.common.datastructure.client.{ClientDataStructureEvent, DataStructureInitiator} import de.tu_berlin.formic.common.datastructure.{DataStructureName, FormicDataStructure, OperationContext} import de.tu_berlin.formic.common.message.{OperationMessage, UpdateRequest, UpdateResponse} import de.tu_berlin.formic.common.{DataStructureInstanceId, OperationId} import de.tu_berlin.formic.datastructure.linear.{LinearDeleteOperation, LinearInsertOperation} import upickle.default._ import scala.collection.mutable.ArrayBuffer import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future} import scala.scalajs.js.annotation.{JSExport, JSExportDescendentClasses} /** * @author Ronny Bräunlich */ @JSExportDescendentClasses abstract class FormicList[T](_callback: (ClientDataStructureEvent) => Unit, initiator: DataStructureInitiator, dataTypeInstanceId: DataStructureInstanceId, dataTypeName: DataStructureName) (implicit val writer: Writer[T], val reader: Reader[T]) extends FormicDataStructure(_callback, dataTypeName, dataStructureInstanceId = dataTypeInstanceId, initiator = initiator ) { implicit val timeout: Timeout = 1.seconds @JSExport def add(index: Int, o: T) = { val operationId = OperationId() val op = LocalOperationMessage( OperationMessage(clientId, dataTypeInstanceId, dataTypeName, List(LinearInsertOperation(index, o, operationId, OperationContext(List.empty), clientId))) ) actor ! op operationId } @JSExport def remove(index: Int): OperationId = { val operationId = OperationId() val op = LocalOperationMessage( OperationMessage(clientId, dataTypeInstanceId, dataTypeName, List(LinearDeleteOperation(index, operationId, OperationContext(List.empty), clientId))) ) actor ! op operationId } @JSExport def get(index: Int)(implicit ec: ExecutionContext): Future[T] = { ask(actor, UpdateRequest(clientId, dataTypeInstanceId)). mapTo[UpdateResponse]. map(rep => { rep.data }). map(data => { read[ArrayBuffer[T]](data) }). map(buffer => buffer(index)) } @JSExport def getAll()(implicit ec: ExecutionContext): Future[ArrayBuffer[T]] = { val updateRequest = UpdateRequest(clientId, dataTypeInstanceId) ask(actor, updateRequest). mapTo[UpdateResponse]. map(rep => rep.data). map(data => read[ArrayBuffer[T]](data)) } }
apache-2.0
treenew/sofire
src/Core/Sofire.Extends/Excel/NPOI/HSSF/Model/LineShape.cs
5635
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Model { using System; using System.Text; using NPOI.HSSF.Record; using NPOI.DDF; using NPOI.HSSF.UserModel; /// <summary> /// Represents a line shape and Creates all the line specific low level records. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> internal class LineShape: AbstractShape { private EscherContainerRecord spContainer; private ObjRecord objRecord; /// <summary> /// Creates the line shape from the highlevel user shape. All low level /// records are Created at this point. /// </summary> /// <param name="hssfShape">The user model shape</param> /// <param name="shapeId">The identifier to use for this shape.</param> public LineShape(HSSFSimpleShape hssfShape, int shapeId) { spContainer = CreateSpContainer(hssfShape, shapeId); objRecord = CreateObjRecord(hssfShape, shapeId); } /// <summary> /// Creates the lowerlevel escher records for this shape. /// </summary> /// <param name="hssfShape">The HSSF shape.</param> /// <param name="shapeId">The shape id.</param> /// <returns></returns> private EscherContainerRecord CreateSpContainer(HSSFSimpleShape hssfShape, int shapeId) { HSSFShape shape = hssfShape; EscherContainerRecord spContainer = new EscherContainerRecord(); EscherSpRecord sp = new EscherSpRecord(); EscherOptRecord opt = new EscherOptRecord(); EscherRecord anchor = new EscherClientAnchorRecord(); EscherClientDataRecord clientData = new EscherClientDataRecord(); spContainer.RecordId=EscherContainerRecord.SP_CONTAINER; spContainer.Options=(short)0x000F; sp.RecordId=EscherSpRecord.RECORD_ID; sp.Options=(short)((EscherAggregate.ST_LINE << 4) | 0x2); sp.ShapeId=shapeId; sp.Flags=EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE; opt.RecordId=EscherOptRecord.RECORD_ID; opt.AddEscherProperty(new EscherShapePathProperty(EscherProperties.GEOMETRY__SHAPEPATH, EscherShapePathProperty.COMPLEX)); opt.AddEscherProperty(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 1048592)); AddStandardOptions(shape, opt); HSSFAnchor userAnchor = shape.Anchor; if (userAnchor.IsHorizontallyFlipped) sp.Flags=sp.Flags | EscherSpRecord.FLAG_FLIPHORIZ; if (userAnchor.IsVerticallyFlipped) sp.Flags=sp.Flags | EscherSpRecord.FLAG_FLIPVERT; anchor = CreateAnchor(userAnchor); clientData.RecordId=EscherClientDataRecord.RECORD_ID; clientData.Options=((short)0x0000); spContainer.AddChildRecord(sp); spContainer.AddChildRecord(opt); spContainer.AddChildRecord(anchor); spContainer.AddChildRecord(clientData); return spContainer; } /// <summary> /// Creates the low level OBJ record for this shape. /// </summary> /// <param name="hssfShape">The HSSF shape.</param> /// <param name="shapeId">The shape id.</param> /// <returns></returns> private ObjRecord CreateObjRecord(HSSFShape hssfShape, int shapeId) { HSSFShape shape = hssfShape; ObjRecord obj = new ObjRecord(); CommonObjectDataSubRecord c = new CommonObjectDataSubRecord(); c.ObjectType = (CommonObjectType)((HSSFSimpleShape)shape).ShapeType; c.ObjectId = GetCmoObjectId(shapeId); c.IsLocked = true; c.IsPrintable = true; c.IsAutoFill = true; c.IsAutoline = true; EndSubRecord e = new EndSubRecord(); obj.AddSubRecord(c); obj.AddSubRecord(e); return obj; } /// <summary> /// The shape container and it's children that can represent this /// shape. /// </summary> /// <value></value> public override EscherContainerRecord SpContainer { get{ return spContainer;} } /// <summary> /// The object record that is associated with this shape. /// </summary> /// <value></value> public override ObjRecord ObjRecord { get { return objRecord; } } } }
apache-2.0
kuujo/onos
web/api/src/main/java/org/onosproject/rest/resources/FlowsWebResource.java
15942
/* * Copyright 2015-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.rest.resources; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import org.onlab.util.ItemNotFoundException; import org.onosproject.app.ApplicationService; import org.onosproject.core.ApplicationId; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.FlowEntry; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.IndexTableId; import org.onosproject.rest.AbstractWebResource; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.stream.StreamSupport; import static org.onlab.util.Tools.nullIsIllegal; import static org.onlab.util.Tools.nullIsNotFound; import static org.onlab.util.Tools.readTreeFromStream; /** * Query and program flow rules. */ @Path("flows") public class FlowsWebResource extends AbstractWebResource { @Context private UriInfo uriInfo; private static final String DEVICE_NOT_FOUND = "Device is not found"; private static final String FLOW_NOT_FOUND = "Flow is not found"; private static final String APP_ID_NOT_FOUND = "Application Id is not found"; private static final String FLOW_ARRAY_REQUIRED = "Flows array was not specified"; private static final String FLOWS = "flows"; private static final String DEVICE_ID = "deviceId"; private static final String FLOW_ID = "flowId"; /** * Gets all flow entries. Returns array of all flow rules in the system. * * @return 200 OK with a collection of flows * @onos.rsModel FlowEntries */ @GET @Produces(MediaType.APPLICATION_JSON) public Response getFlows() { ObjectNode root = mapper().createObjectNode(); ArrayNode flowsNode = root.putArray(FLOWS); FlowRuleService service = get(FlowRuleService.class); Iterable<Device> devices = get(DeviceService.class).getDevices(); for (Device device : devices) { Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id()); if (flowEntries != null) { for (FlowEntry entry : flowEntries) { flowsNode.add(codec(FlowEntry.class).encode(entry, this)); } } } return ok(root).build(); } /** * Gets all pending flow entries. Returns array of all pending flow rules in the system. * * @return 200 OK with a collection of flows * @onos.rsModel FlowEntries */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("pending") public Response getPendingFlows() { ObjectNode root = mapper().createObjectNode(); ArrayNode flowsNode = root.putArray(FLOWS); FlowRuleService service = get(FlowRuleService.class); Iterable<Device> devices = get(DeviceService.class).getDevices(); for (Device device : devices) { Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id()); if (flowEntries != null) { for (FlowEntry entry : flowEntries) { if ((entry.state() == FlowEntry.FlowEntryState.PENDING_ADD) || (entry.state() == FlowEntry.FlowEntryState.PENDING_REMOVE)) { flowsNode.add(codec(FlowEntry.class).encode(entry, this)); } } } } return ok(root).build(); } /** * Gets all flow entries for a table. Returns array of all flow rules for a table. * @param tableId table identifier * @return 200 OK with a collection of flows * @onos.rsModel FlowEntries */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("table/{tableId}") public Response getTableFlows(@PathParam("tableId") int tableId) { ObjectNode root = mapper().createObjectNode(); ArrayNode flowsNode = root.putArray(FLOWS); FlowRuleService service = get(FlowRuleService.class); Iterable<Device> devices = get(DeviceService.class).getDevices(); for (Device device : devices) { Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id()); if (flowEntries != null) { for (FlowEntry entry : flowEntries) { if (((IndexTableId) entry.table()).id() == tableId) { flowsNode.add(codec(FlowEntry.class).encode(entry, this)); } } } } return ok(root).build(); } /** * Creates new flow rules. Creates and installs a new flow rules.<br> * Flow rule criteria and instruction description: * https://wiki.onosproject.org/display/ONOS/Flow+Rules * * @param appId application id * @param stream flow rules JSON * @return status of the request - CREATED if the JSON is correct, * BAD_REQUEST if the JSON is invalid * @onos.rsModel FlowsBatchPost */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createFlows(@QueryParam("appId") String appId, InputStream stream) { ObjectNode root = mapper().createObjectNode(); ArrayNode flowsNode = root.putArray(FLOWS); try { ObjectNode jsonTree = readTreeFromStream(mapper(), stream); ArrayNode flowsArray = nullIsIllegal((ArrayNode) jsonTree.get(FLOWS), FLOW_ARRAY_REQUIRED); if (appId != null) { flowsArray.forEach(flowJson -> ((ObjectNode) flowJson).put("appId", appId)); } List<FlowRule> rules = codec(FlowRule.class).decode(flowsArray, this); get(FlowRuleService.class).applyFlowRules(rules.toArray(new FlowRule[rules.size()])); rules.forEach(flowRule -> { ObjectNode flowNode = mapper().createObjectNode(); flowNode.put(DEVICE_ID, flowRule.deviceId().toString()) .put(FLOW_ID, Long.toString(flowRule.id().value())); flowsNode.add(flowNode); }); } catch (IOException ex) { throw new IllegalArgumentException(ex); } return Response.ok(root).build(); } /** * Gets flow entries of a device. Returns array of all flow rules for the * specified device. * * @param deviceId device identifier * @return 200 OK with a collection of flows of given device * @onos.rsModel FlowEntries */ @GET @Produces(MediaType.APPLICATION_JSON) // TODO: we need to add "/device" suffix to the path to differentiate with appId @Path("{deviceId}") public Response getFlowByDeviceId(@PathParam("deviceId") String deviceId) { ObjectNode root = mapper().createObjectNode(); ArrayNode flowsNode = root.putArray(FLOWS); Iterable<FlowEntry> flowEntries = get(FlowRuleService.class).getFlowEntries(DeviceId.deviceId(deviceId)); if (flowEntries == null || !flowEntries.iterator().hasNext()) { throw new ItemNotFoundException(DEVICE_NOT_FOUND); } for (FlowEntry entry : flowEntries) { flowsNode.add(codec(FlowEntry.class).encode(entry, this)); } return ok(root).build(); } /** * Gets flow rules. Returns the flow entry specified by the device id and * flow rule id. * * @param deviceId device identifier * @param flowId flow rule identifier * @return 200 OK with a collection of flows of given device and flow * @onos.rsModel FlowEntries */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("{deviceId}/{flowId}") public Response getFlowByDeviceIdAndFlowId(@PathParam("deviceId") String deviceId, @PathParam("flowId") long flowId) { ObjectNode root = mapper().createObjectNode(); ArrayNode flowsNode = root.putArray(FLOWS); Iterable<FlowEntry> flowEntries = get(FlowRuleService.class).getFlowEntries(DeviceId.deviceId(deviceId)); if (flowEntries == null || !flowEntries.iterator().hasNext()) { throw new ItemNotFoundException(DEVICE_NOT_FOUND); } for (FlowEntry entry : flowEntries) { if (entry.id().value() == flowId) { flowsNode.add(codec(FlowEntry.class).encode(entry, this)); } } return ok(root).build(); } /** * Gets flow rules generated by an application. * Returns the flow rule specified by the application id. * * @param appId application identifier * @return 200 OK with a collection of flows of given application id * @onos.rsModel FlowRules */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("application/{appId}") public Response getFlowByAppId(@PathParam("appId") String appId) { ObjectNode root = mapper().createObjectNode(); ArrayNode flowsNode = root.putArray(FLOWS); ApplicationService appService = get(ApplicationService.class); ApplicationId idInstant = nullIsNotFound(appService.getId(appId), APP_ID_NOT_FOUND); Iterable<FlowEntry> flowEntries = get(FlowRuleService.class).getFlowEntriesById(idInstant); flowEntries.forEach(flow -> flowsNode.add(codec(FlowEntry.class).encode(flow, this))); return ok(root).build(); } /** * Removes flow rules by application ID. * Removes a collection of flow rules generated by the given application. * * @param appId application identifier * @return 204 NO CONTENT */ @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("application/{appId}") public Response removeFlowByAppId(@PathParam("appId") String appId) { ApplicationService appService = get(ApplicationService.class); ApplicationId idInstant = nullIsNotFound(appService.getId(appId), APP_ID_NOT_FOUND); get(FlowRuleService.class).removeFlowRulesById(idInstant); return Response.noContent().build(); } /** * Creates new flow rule. Creates and installs a new flow rule for the * specified device. <br> * Flow rule criteria and instruction description: * https://wiki.onosproject.org/display/ONOS/Flow+Rules * * @param deviceId device identifier * @param appId application identifier * @param stream flow rule JSON * @return status of the request - CREATED if the JSON is correct, * BAD_REQUEST if the JSON is invalid * @onos.rsModel FlowsPost */ @POST @Path("{deviceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createFlow(@PathParam("deviceId") String deviceId, @QueryParam("appId") String appId, InputStream stream) { try { ObjectNode jsonTree = readTreeFromStream(mapper(), stream); JsonNode specifiedDeviceId = jsonTree.get("deviceId"); if (specifiedDeviceId != null && !specifiedDeviceId.asText().equals(deviceId)) { throw new IllegalArgumentException( "Invalid deviceId in flow creation request"); } jsonTree.put("deviceId", deviceId); if (appId != null) { jsonTree.put("appId", appId); } FlowRule rule = codec(FlowRule.class).decode(jsonTree, this); get(FlowRuleService.class).applyFlowRules(rule); UriBuilder locationBuilder = uriInfo.getBaseUriBuilder() .path("flows") .path(deviceId) .path(Long.toString(rule.id().value())); return Response .created(locationBuilder.build()) .build(); } catch (IOException ex) { throw new IllegalArgumentException(ex); } } /** * Removes flow rule. Removes the specified flow rule. * * @param deviceId device identifier * @param flowId flow rule identifier * @return 204 NO CONTENT */ @DELETE @Path("{deviceId}/{flowId}") public Response deleteFlowByDeviceIdAndFlowId(@PathParam("deviceId") String deviceId, @PathParam("flowId") long flowId) { FlowRuleService service = get(FlowRuleService.class); Iterable<FlowEntry> flowEntries = service.getFlowEntries(DeviceId.deviceId(deviceId)); if (!flowEntries.iterator().hasNext()) { throw new ItemNotFoundException(DEVICE_NOT_FOUND); } StreamSupport.stream(flowEntries.spliterator(), false) .filter(entry -> entry.id().value() == flowId) .forEach(service::removeFlowRules); return Response.noContent().build(); } /** * Removes a batch of flow rules. * * @param stream stream for posted JSON * @return 204 NO CONTENT */ @DELETE public Response deleteFlows(InputStream stream) { FlowRuleService service = get(FlowRuleService.class); ListMultimap<DeviceId, Long> deviceMap = ArrayListMultimap.create(); List<FlowEntry> rulesToRemove = new ArrayList<>(); try { ObjectNode jsonTree = readTreeFromStream(mapper(), stream); JsonNode jsonFlows = jsonTree.get("flows"); jsonFlows.forEach(node -> { DeviceId deviceId = DeviceId.deviceId( nullIsNotFound(node.get(DEVICE_ID), DEVICE_NOT_FOUND).asText()); long flowId = nullIsNotFound(node.get(FLOW_ID), FLOW_NOT_FOUND).asLong(); deviceMap.put(deviceId, flowId); }); } catch (IOException ex) { throw new IllegalArgumentException(ex); } deviceMap.keySet().forEach(deviceId -> { List<Long> flowIds = deviceMap.get(deviceId); Iterable<FlowEntry> entries = service.getFlowEntries(deviceId); flowIds.forEach(flowId -> { StreamSupport.stream(entries.spliterator(), false) .filter(entry -> flowId == entry.id().value()) .forEach(rulesToRemove::add); }); }); service.removeFlowRules(rulesToRemove.toArray(new FlowEntry[0])); return Response.noContent().build(); } }
apache-2.0
haozhun/presto
presto-hive/src/main/java/com/facebook/presto/hive/RecordFileWriter.java
8167
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.hive.HiveWriteUtils.FieldSetter; import com.facebook.presto.hive.metastore.StorageFormat; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import io.airlift.units.DataSize; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.Serializer; import org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe; import org.apache.hadoop.hive.serde2.columnar.OptimizedLazyBinaryColumnarSerde; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.mapred.JobConf; import org.openjdk.jol.info.ClassLayout; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import java.util.Properties; import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_CLOSE_ERROR; import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_DATA_ERROR; import static com.facebook.presto.hive.HiveType.toHiveTypes; import static com.facebook.presto.hive.HiveWriteUtils.createFieldSetter; import static com.facebook.presto.hive.HiveWriteUtils.createRecordWriter; import static com.facebook.presto.hive.HiveWriteUtils.getRowColumnInspectors; import static com.facebook.presto.hive.HiveWriteUtils.initializeSerializer; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS; import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMN_TYPES; import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardStructObjectInspector; public class RecordFileWriter implements HiveFileWriter { private static final int INSTANCE_SIZE = ClassLayout.parseClass(RecordFileWriter.class).instanceSize(); private final Path path; private final JobConf conf; private final int fieldCount; @SuppressWarnings("deprecation") private final Serializer serializer; private final RecordWriter recordWriter; private final SettableStructObjectInspector tableInspector; private final List<StructField> structFields; private final Object row; private final FieldSetter[] setters; private final long estimatedWriterSystemMemoryUsage; private boolean committed; public RecordFileWriter( Path path, List<String> inputColumnNames, StorageFormat storageFormat, Properties schema, DataSize estimatedWriterSystemMemoryUsage, JobConf conf, TypeManager typeManager) { this.path = requireNonNull(path, "path is null"); this.conf = requireNonNull(conf, "conf is null"); // existing tables may have columns in a different order List<String> fileColumnNames = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(schema.getProperty(META_TABLE_COLUMNS, "")); List<Type> fileColumnTypes = toHiveTypes(schema.getProperty(META_TABLE_COLUMN_TYPES, "")).stream() .map(hiveType -> hiveType.getType(typeManager)) .collect(toList()); fieldCount = fileColumnNames.size(); String serDe = storageFormat.getSerDe(); if (serDe.equals(LazyBinaryColumnarSerDe.class.getName())) { serDe = OptimizedLazyBinaryColumnarSerde.class.getName(); } serializer = initializeSerializer(conf, schema, serDe); recordWriter = createRecordWriter(path, conf, schema, storageFormat.getOutputFormat()); List<ObjectInspector> objectInspectors = getRowColumnInspectors(fileColumnTypes); tableInspector = getStandardStructObjectInspector(fileColumnNames, objectInspectors); // reorder (and possibly reduce) struct fields to match input structFields = ImmutableList.copyOf(inputColumnNames.stream() .map(tableInspector::getStructFieldRef) .collect(toList())); row = tableInspector.create(); setters = new FieldSetter[structFields.size()]; for (int i = 0; i < setters.length; i++) { setters[i] = createFieldSetter(tableInspector, row, structFields.get(i), fileColumnTypes.get(structFields.get(i).getFieldID())); } this.estimatedWriterSystemMemoryUsage = estimatedWriterSystemMemoryUsage.toBytes(); } @Override public long getWrittenBytes() { if (recordWriter instanceof ExtendedRecordWriter) { return ((ExtendedRecordWriter) recordWriter).getWrittenBytes(); } if (committed) { try { return path.getFileSystem(conf).getFileStatus(path).getLen(); } catch (IOException e) { throw new UncheckedIOException(e); } } // there is no good way to get this when RecordWriter is not yet committed return 0; } @Override public long getSystemMemoryUsage() { return INSTANCE_SIZE + estimatedWriterSystemMemoryUsage; } @Override public void appendRows(Page dataPage) { for (int position = 0; position < dataPage.getPositionCount(); position++) { appendRow(dataPage, position); } } public void appendRow(Page dataPage, int position) { for (int field = 0; field < fieldCount; field++) { Block block = dataPage.getBlock(field); if (block.isNull(position)) { tableInspector.setStructFieldData(row, structFields.get(field), null); } else { setters[field].setField(block, position); } } try { recordWriter.write(serializer.serialize(row, tableInspector)); } catch (SerDeException | IOException e) { throw new PrestoException(HIVE_WRITER_DATA_ERROR, e); } } @Override public void commit() { try { recordWriter.close(false); committed = true; } catch (IOException e) { throw new PrestoException(HIVE_WRITER_CLOSE_ERROR, "Error committing write to Hive", e); } } @Override public void rollback() { try { try { recordWriter.close(true); } finally { // perform explicit deletion here as implementations of RecordWriter.close() often ignore the abort flag. path.getFileSystem(conf).delete(path, false); } } catch (IOException e) { throw new PrestoException(HIVE_WRITER_CLOSE_ERROR, "Error rolling back write to Hive", e); } } @Override public String toString() { return toStringHelper(this) .add("path", path) .toString(); } public interface ExtendedRecordWriter extends RecordWriter { long getWrittenBytes(); } }
apache-2.0
data-integrations/github
src/test/java/io/cdap/plugin/github/source/common/DatasetTransformerTest.java
1414
package io.cdap.plugin.github.source.common; import io.cdap.cdap.api.data.format.StructuredRecord; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.plugin.github.source.common.model.impl.Commit; import io.github.benas.randombeans.api.EnhancedRandom; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static io.github.benas.randombeans.EnhancedRandomBuilder.aNewEnhancedRandom; @RunWith(Parameterized.class) public class DatasetTransformerTest { private static final EnhancedRandom random = aNewEnhancedRandom(); private Class<?> clazz; private Object model; public DatasetTransformerTest(Class<?> clazz) { this.clazz = clazz; this.model = random.nextObject(clazz); } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {Commit.class}, }); } @Test public void testTransformModel() throws NoSuchFieldException, IllegalAccessException { //given Schema schema = SchemaBuilder.buildSchema(clazz.getSimpleName(), clazz); //when StructuredRecord output = DatasetTransformer.transform(model, schema); //then Assert.assertNotNull(schema.getFields()); schema.getFields().forEach(field -> Assert.assertNotNull(output.get(field.getName()))); } }
apache-2.0
reynoldsm88/drools
drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/mvel/MVELDialect.java
31763
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.compiler.rule.builder.dialect.mvel; import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl; import org.drools.compiler.commons.jci.readers.MemoryResourceReader; import org.drools.compiler.compiler.AnalysisResult; import org.drools.compiler.compiler.BoundIdentifiers; import org.drools.compiler.compiler.DescrBuildError; import org.drools.compiler.compiler.Dialect; import org.drools.compiler.compiler.ImportError; import org.drools.compiler.compiler.PackageRegistry; import org.drools.compiler.lang.descr.AccumulateDescr; import org.drools.compiler.lang.descr.AndDescr; import org.drools.compiler.lang.descr.BaseDescr; import org.drools.compiler.lang.descr.CollectDescr; import org.drools.compiler.lang.descr.ConditionalBranchDescr; import org.drools.compiler.lang.descr.EntryPointDescr; import org.drools.compiler.lang.descr.EvalDescr; import org.drools.compiler.lang.descr.ExistsDescr; import org.drools.compiler.lang.descr.ForallDescr; import org.drools.compiler.lang.descr.FromDescr; import org.drools.compiler.lang.descr.FunctionDescr; import org.drools.compiler.lang.descr.ImportDescr; import org.drools.compiler.lang.descr.NamedConsequenceDescr; import org.drools.compiler.lang.descr.NotDescr; import org.drools.compiler.lang.descr.OrDescr; import org.drools.compiler.lang.descr.PatternDescr; import org.drools.compiler.lang.descr.ProcessDescr; import org.drools.compiler.lang.descr.QueryDescr; import org.drools.compiler.lang.descr.RuleDescr; import org.drools.compiler.lang.descr.WindowReferenceDescr; import org.drools.compiler.rule.builder.AccumulateBuilder; import org.drools.compiler.rule.builder.CollectBuilder; import org.drools.compiler.rule.builder.ConditionalBranchBuilder; import org.drools.compiler.rule.builder.ConsequenceBuilder; import org.drools.compiler.rule.builder.EnabledBuilder; import org.drools.compiler.rule.builder.EngineElementBuilder; import org.drools.compiler.rule.builder.EntryPointBuilder; import org.drools.compiler.rule.builder.ForallBuilder; import org.drools.compiler.rule.builder.FromBuilder; import org.drools.compiler.rule.builder.GroupElementBuilder; import org.drools.compiler.rule.builder.NamedConsequenceBuilder; import org.drools.compiler.rule.builder.PackageBuildContext; import org.drools.compiler.rule.builder.PatternBuilder; import org.drools.compiler.rule.builder.PredicateBuilder; import org.drools.compiler.rule.builder.QueryBuilder; import org.drools.compiler.rule.builder.ReturnValueBuilder; import org.drools.compiler.rule.builder.RuleBuildContext; import org.drools.compiler.rule.builder.RuleClassBuilder; import org.drools.compiler.rule.builder.RuleConditionBuilder; import org.drools.compiler.rule.builder.SalienceBuilder; import org.drools.compiler.rule.builder.WindowReferenceBuilder; import org.drools.compiler.rule.builder.dialect.DialectUtil; import org.drools.compiler.rule.builder.dialect.java.JavaFunctionBuilder; import org.drools.core.base.EvaluatorWrapper; import org.drools.core.base.mvel.MVELCompilationUnit; import org.drools.core.definitions.InternalKnowledgePackage; import org.drools.core.rule.Declaration; import org.drools.core.rule.LineMappings; import org.drools.core.rule.MVELDialectRuntimeData; import org.drools.core.spi.KnowledgeHelper; import org.drools.core.util.StringUtils; import org.kie.api.definition.rule.Rule; import org.kie.api.io.Resource; import org.kie.internal.builder.KnowledgeBuilderResult; import org.kie.soup.project.datamodel.commons.types.TypeResolver; import org.mvel2.MVEL; import org.mvel2.optimizers.OptimizerFactory; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class MVELDialect implements Dialect, Externalizable { private String id = "mvel"; private final static String EXPRESSION_DIALECT_NAME = "MVEL"; protected static final PatternBuilder PATTERN_BUILDER = new PatternBuilder(); protected static final QueryBuilder QUERY_BUILDER = new QueryBuilder(); protected static final MVELAccumulateBuilder ACCUMULATE_BUILDER = new MVELAccumulateBuilder(); protected static final SalienceBuilder SALIENCE_BUILDER = new MVELSalienceBuilder(); protected static final EnabledBuilder ENABLED_BUILDER = new MVELEnabledBuilder(); protected static final MVELEvalBuilder EVAL_BUILDER = new MVELEvalBuilder(); protected static final MVELReturnValueBuilder RETURN_VALUE_BUILDER = new MVELReturnValueBuilder(); protected static final MVELConsequenceBuilder CONSEQUENCE_BUILDER = new MVELConsequenceBuilder(); protected static final MVELFromBuilder FROM_BUILDER = new MVELFromBuilder(); protected static final JavaFunctionBuilder FUNCTION_BUILDER = new JavaFunctionBuilder(); protected static final CollectBuilder COLLECT_BUILDER = new CollectBuilder(); protected static final ForallBuilder FORALL_BUILDER = new ForallBuilder(); protected static final EntryPointBuilder ENTRY_POINT_BUILDER = new EntryPointBuilder(); protected static final WindowReferenceBuilder WINDOW_REFERENCE_BUILDER = new WindowReferenceBuilder(); protected static final GroupElementBuilder GE_BUILDER = new GroupElementBuilder(); protected static final NamedConsequenceBuilder NAMED_CONSEQUENCE_BUILDER = new NamedConsequenceBuilder(); protected static final ConditionalBranchBuilder CONDITIONAL_BRANCH_BUILDER = new ConditionalBranchBuilder(); // a map of registered builders private static Map<Class<?>, EngineElementBuilder> builders; static { initBuilder(); } private final Map interceptors = MVELCompilationUnit.INTERCEPTORS; protected List<KnowledgeBuilderResult> results; // private final JavaFunctionBuilder function = new JavaFunctionBuilder(); protected MemoryResourceReader src; protected InternalKnowledgePackage pkg; private MVELDialectConfiguration configuration; private PackageRegistry packageRegistry; private boolean strictMode; private int languageLevel; private MVELDialectRuntimeData data; private final ClassLoader rootClassLoader; static { // always use mvel reflective optimizer OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); } public MVELDialect(ClassLoader rootClassLoader, KnowledgeBuilderConfigurationImpl pkgConf, PackageRegistry pkgRegistry, InternalKnowledgePackage pkg) { this(rootClassLoader, pkgConf, pkgRegistry, pkg, "mvel"); } public MVELDialect(ClassLoader rootClassLoader, KnowledgeBuilderConfigurationImpl pkgConf, PackageRegistry pkgRegistry, InternalKnowledgePackage pkg, String id) { this.rootClassLoader = rootClassLoader; this.id = id; this.pkg = pkg; this.packageRegistry = pkgRegistry; this.configuration = (MVELDialectConfiguration) pkgConf.getDialectConfiguration("mvel"); setLanguageLevel(this.configuration.getLangLevel()); this.strictMode = this.configuration.isStrict(); // setting MVEL option directly MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true; this.results = new ArrayList<KnowledgeBuilderResult>(); // this.data = new MVELDialectRuntimeData( // this.pkg.getDialectRuntimeRegistry() ); // // this.pkg.getDialectRuntimeRegistry().setDialectData( ID, // this.data ); // initialise the dialect runtime data if it doesn't already exist if (pkg.getDialectRuntimeRegistry().getDialectData(getId()) == null) { data = new MVELDialectRuntimeData(); this.pkg.getDialectRuntimeRegistry().setDialectData(getId(), data); data.onAdd(this.pkg.getDialectRuntimeRegistry(), rootClassLoader); } else { data = (MVELDialectRuntimeData) this.pkg.getDialectRuntimeRegistry().getDialectData("mvel"); } this.results = new ArrayList<KnowledgeBuilderResult>(); this.src = new MemoryResourceReader(); if (this.pkg != null) { this.addImport(new ImportDescr(this.pkg.getName() + ".*")); } this.addImport(new ImportDescr("java.lang.*")); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { results = (List<KnowledgeBuilderResult>) in.readObject(); src = (MemoryResourceReader) in.readObject(); pkg = (InternalKnowledgePackage) in.readObject(); packageRegistry = (PackageRegistry) in.readObject(); configuration = (MVELDialectConfiguration) in.readObject(); strictMode = in.readBoolean(); data = (MVELDialectRuntimeData) this.pkg.getDialectRuntimeRegistry().getDialectData("mvel"); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(results); out.writeObject(src); out.writeObject(pkg); out.writeObject(packageRegistry); out.writeObject(configuration); out.writeBoolean(strictMode); out.writeObject(data); } public void setLanguageLevel(int languageLevel) { this.languageLevel = languageLevel; } // public static void setLanguageLevel(int level) { // synchronized ( lang ) { // // this synchronisation is needed as setLanguageLevel is not thread safe // // and we do not want to be calling this while something else is being // parsed. // // the flag ensures it is just called once and no more. // if ( languageSet.booleanValue() == false ) { // languageSet = new Boolean( true ); // AbstractParser.setLanguageLevel( level ); // } // } // } public static void initBuilder() { if (builders != null) { return; } reinitBuilder(); } public static void reinitBuilder() { // statically adding all builders to the map // but in the future we can move that to a configuration // if we want to builders = new HashMap<Class<?>, EngineElementBuilder>(); builders.put(AndDescr.class, GE_BUILDER); builders.put(OrDescr.class, GE_BUILDER); builders.put(NotDescr.class, GE_BUILDER); builders.put(ExistsDescr.class, GE_BUILDER); builders.put(PatternDescr.class, PATTERN_BUILDER); builders.put(FromDescr.class, FROM_BUILDER); builders.put(QueryDescr.class, QUERY_BUILDER); builders.put(AccumulateDescr.class, ACCUMULATE_BUILDER); builders.put(EvalDescr.class, EVAL_BUILDER); builders.put(CollectDescr.class, COLLECT_BUILDER); builders.put(ForallDescr.class, FORALL_BUILDER); builders.put(FunctionDescr.class, FUNCTION_BUILDER); builders.put(EntryPointDescr.class, ENTRY_POINT_BUILDER); builders.put(WindowReferenceDescr.class, WINDOW_REFERENCE_BUILDER); builders.put(NamedConsequenceDescr.class, NAMED_CONSEQUENCE_BUILDER); builders.put(ConditionalBranchDescr.class, CONDITIONAL_BRANCH_BUILDER); } public void init(RuleDescr ruleDescr) { // MVEL:test null to Fix failing test on // org.kie.rule.builder.dialect. // mvel.MVELConsequenceBuilderTest.testImperativeCodeError() // @todo: why is this here, MVEL doesn't compile anything? mdp String pkgName = this.pkg == null ? "" : this.pkg.getName(); final String ruleClassName = DialectUtil.getUniqueLegalName(pkgName, ruleDescr.getName(), ruleDescr.getConsequence().hashCode(), "mvel", "Rule", this.src); ruleDescr.setClassName(StringUtils.ucFirst(ruleClassName)); } public void init(final ProcessDescr processDescr) { final String processDescrClassName = DialectUtil.getUniqueLegalName(this.pkg.getName(), processDescr.getName(), processDescr.getProcessId().hashCode(), "mvel", "Process", this.src); processDescr.setClassName(StringUtils.ucFirst(processDescrClassName)); } public String getExpressionDialectName() { return EXPRESSION_DIALECT_NAME; } public void addRule(RuleBuildContext context) { // MVEL: Compiler change final RuleDescr ruleDescr = context.getRuleDescr(); // setup the line mappins for this rule final String name = this.pkg.getName() + "." + StringUtils.ucFirst(ruleDescr.getClassName()); final LineMappings mapping = new LineMappings(name); mapping.setStartLine(ruleDescr.getConsequenceLine()); mapping.setOffset(ruleDescr.getConsequenceOffset()); context.getPkg().getDialectRuntimeRegistry().getLineMappings().put(name, mapping); } public void addFunction(FunctionDescr functionDescr, TypeResolver typeResolver, Resource resource) { // Serializable s1 = compile( (String) functionDescr.getText(), // null, // null, // null, // null, // null ); // // final ParserContext parserContext = getParserContext( analysis, // outerDeclarations, // otherInputVariables, // context ); // return MVELCompilationUnit.compile( text, pkgBuilder.getRootClassLoader(), parserContext, languageLevel ); // // Map<String, org.mvel2.ast.Function> map = org.mvel2.util.CompilerTools.extractAllDeclaredFunctions( (org.mvel2.compiler.CompiledExpression) s1 ); // MVELDialectRuntimeData data = (MVELDialectRuntimeData) this.packageRegistry.getDialectRuntimeRegistry().getDialectData( getId() ); // for ( org.mvel2.ast.Function function : map.values() ) { // data.addFunction( function ); // } } public void preCompileAddFunction(FunctionDescr functionDescr, TypeResolver typeResolver) { } public void postCompileAddFunction(FunctionDescr functionDescr, TypeResolver typeResolver) { } public void addImport(ImportDescr importDescr) { String importEntry = importDescr.getTarget(); if (importEntry.endsWith(".*")) { importEntry = importEntry.substring(0, importEntry.length() - 2); data.addPackageImport(importEntry); } else { try { Class cls = this.packageRegistry.getTypeResolver().resolveType(importEntry); data.addImport(cls.getSimpleName(), cls); } catch (ClassNotFoundException e) { this.results.add(new ImportError(importDescr, 1)); } } } public void addStaticImport(ImportDescr importDescr) { String staticImportEntry = importDescr.getTarget(); if (staticImportEntry.endsWith("*")) { addStaticPackageImport(importDescr); return; } int index = staticImportEntry.lastIndexOf('.'); String className = staticImportEntry.substring(0, index); String methodName = staticImportEntry.substring(index + 1); try { Class cls = this.packageRegistry.getPackageClassLoader().loadClass(className); if (cls != null) { // First try and find a matching method for (Method method : cls.getDeclaredMethods()) { if (method.getName().equals(methodName)) { this.data.addImport(methodName, method); return; } } //no matching method, so now try and find a matching public property for (Field field : cls.getFields()) { if (field.isAccessible() && field.getName().equals(methodName)) { this.data.addImport(methodName, field); return; } } } } catch (ClassNotFoundException e) { } // we never managed to make the import, so log an error this.results.add(new ImportError(importDescr, -1)); } public void addStaticPackageImport(ImportDescr importDescr) { String staticImportEntry = importDescr.getTarget(); int index = staticImportEntry.lastIndexOf('.'); String className = staticImportEntry.substring(0, index); Class cls = null; try { cls = rootClassLoader.loadClass(className); } catch (ClassNotFoundException e) { } if (cls == null) { results.add(new ImportError(importDescr, -1)); return; } for (Method method : cls.getDeclaredMethods()) { if ((method.getModifiers() | Modifier.STATIC) > 0) { this.data.addImport(method.getName(), method); } } for (Field field : cls.getFields()) { if (field.isAccessible() && (field.getModifiers() | Modifier.STATIC) > 0) { this.data.addImport(field.getName(), field); return; } } } // private Map staticFieldImports = new HashMap(); // private Map staticMethodImports = new HashMap(); public boolean isStrictMode() { return strictMode; } public void setStrictMode(boolean strictMode) { this.strictMode = strictMode; } public void compileAll() { } public AnalysisResult analyzeExpression(final PackageBuildContext context, final BaseDescr descr, final Object content, final BoundIdentifiers availableIdentifiers) { return analyzeExpression(context, descr, content, availableIdentifiers, null); } public AnalysisResult analyzeExpression(final PackageBuildContext context, final BaseDescr descr, final Object content, final BoundIdentifiers availableIdentifiers, final Map<String, Class<?>> localTypes) { AnalysisResult result = null; // the following is required for proper error handling BaseDescr temp = context.getParentDescr(); context.setParentDescr(descr); try { result = MVELExprAnalyzer.analyzeExpression(context, (String) content, availableIdentifiers, localTypes, "drools", KnowledgeHelper.class); } catch (final Exception e) { DialectUtil.copyErrorLocation(e, descr); context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Unable to determine the used declarations.\n" + e.getMessage())); } finally { // setting it back to original parent descr context.setParentDescr(temp); } return result; } public AnalysisResult analyzeBlock(final PackageBuildContext context, final BaseDescr descr, final String text, final BoundIdentifiers availableIdentifiers) { return analyzeBlock(context, text, availableIdentifiers, null, "drools", KnowledgeHelper.class); } public AnalysisResult analyzeBlock(final PackageBuildContext context, final String text, final BoundIdentifiers availableIdentifiers, final Map<String, Class<?>> localTypes, String contextIndeifier, Class kcontextClass) { return MVELExprAnalyzer.analyzeExpression(context, text, availableIdentifiers, localTypes, contextIndeifier, kcontextClass); } public MVELCompilationUnit getMVELCompilationUnit(final String expression, final AnalysisResult analysis, Declaration[] previousDeclarations, Declaration[] localDeclarations, final Map<String, Class<?>> otherInputVariables, final PackageBuildContext context, String contextIndeifier, Class kcontextClass, boolean readLocalsFromTuple, MVELCompilationUnit.Scope scope) { Map<String, Class> resolvedInputs = new LinkedHashMap<String, Class>(); List<String> ids = new ArrayList<String>(); if (analysis.getBoundIdentifiers().getThisClass() != null || (localDeclarations != null && localDeclarations.length > 0)) { Class cls = analysis.getBoundIdentifiers().getThisClass(); ids.add("this"); resolvedInputs.put("this", (cls != null) ? cls : Object.class); // the only time cls is null is in accumumulate's acc/reverse } ids.add(contextIndeifier); resolvedInputs.put(contextIndeifier, kcontextClass); ids.add("kcontext"); resolvedInputs.put("kcontext", kcontextClass); if (scope.hasRule()) { ids.add("rule"); resolvedInputs.put("rule", Rule.class); } List<String> strList = new ArrayList<String>(); for (String identifier : analysis.getIdentifiers()) { Class<?> type = analysis.getBoundIdentifiers().resolveVarType(identifier); if (type != null) { strList.add(identifier); ids.add(identifier); resolvedInputs.put(identifier, type); } } String[] globalIdentifiers = strList.toArray(new String[strList.size()]); strList.clear(); for (String op : analysis.getBoundIdentifiers().getOperators().keySet()) { strList.add(op); ids.add(op); resolvedInputs.put(op, context.getConfiguration().getComponentFactory().getExpressionProcessor().getEvaluatorWrapperClass()); } EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()]; for (int i = 0; i < operators.length; i++) { operators[i] = analysis.getBoundIdentifiers().getOperators().get(strList.get(i)); } if (previousDeclarations != null) { for (Declaration decl : previousDeclarations) { if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) { ids.add(decl.getIdentifier()); resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass()); } } } if (localDeclarations != null) { for (Declaration decl : localDeclarations) { if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) { ids.add(decl.getIdentifier()); resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass()); } } } // "not bound" identifiers could be drools, kcontext and rule // but in the case of accumulate it could be vars from the "init" section. //String[] otherIdentifiers = otherInputVariables == null ? new String[]{} : new String[otherInputVariables.size()]; strList = new ArrayList<String>(); if (otherInputVariables != null) { MVELAnalysisResult mvelAnalysis = (MVELAnalysisResult) analysis; for (Entry<String, Class<?>> stringClassEntry : otherInputVariables.entrySet()) { if ((!analysis.getNotBoundedIdentifiers().contains(stringClassEntry.getKey()) && !mvelAnalysis.getMvelVariables().keySet().contains(stringClassEntry.getKey())) || "rule".equals(stringClassEntry.getKey())) { // no point including them if they aren't used // and rule was already included continue; } ids.add(stringClassEntry.getKey()); strList.add(stringClassEntry.getKey()); resolvedInputs.put(stringClassEntry.getKey(), stringClassEntry.getValue()); } } String[] otherIdentifiers = strList.toArray(new String[strList.size()]); String[] inputIdentifiers = new String[resolvedInputs.size()]; String[] inputTypes = new String[resolvedInputs.size()]; int i = 0; for (String id : ids) { inputIdentifiers[i] = id; inputTypes[i++] = resolvedInputs.get(id).getName(); } String name; if (context != null && context.getPkg() != null && context.getPkg().getName() != null) { if (context instanceof RuleBuildContext) { name = context.getPkg().getName() + "." + ((RuleBuildContext) context).getRuleDescr().getClassName(); } else { name = context.getPkg().getName() + ".Unknown"; } } else { name = "Unknown"; } return new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, ((MVELAnalysisResult) analysis).isTypesafe(), readLocalsFromTuple); } public EngineElementBuilder getBuilder(final Class clazz) { return builders.get(clazz); } public Map<Class<?>, EngineElementBuilder> getBuilders() { return builders; } public PatternBuilder getPatternBuilder() { return PATTERN_BUILDER; } public QueryBuilder getQueryBuilder() { return QUERY_BUILDER; } public AccumulateBuilder getAccumulateBuilder() { return ACCUMULATE_BUILDER; } public ConsequenceBuilder getConsequenceBuilder() { return CONSEQUENCE_BUILDER; } public RuleConditionBuilder getEvalBuilder() { return EVAL_BUILDER; } public FromBuilder getFromBuilder() { return FROM_BUILDER; } public EntryPointBuilder getEntryPointBuilder() { return ENTRY_POINT_BUILDER; } public PredicateBuilder getPredicateBuilder() { throw new RuntimeException("mvel PredicateBuilder is no longer in use"); } public SalienceBuilder getSalienceBuilder() { return SALIENCE_BUILDER; } public EnabledBuilder getEnabledBuilder() { return ENABLED_BUILDER; } public List<KnowledgeBuilderResult> getResults() { return results; } public void clearResults() { this.results.clear(); } public ReturnValueBuilder getReturnValueBuilder() { return RETURN_VALUE_BUILDER; } public RuleClassBuilder getRuleClassBuilder() { throw new UnsupportedOperationException("MVELDialect.getRuleClassBuilder is not supported"); } public TypeResolver getTypeResolver() { return this.packageRegistry.getTypeResolver(); } public Map getInterceptors() { return this.interceptors; } public String getId() { return this.id; } public PackageRegistry getPackageRegistry() { return this.packageRegistry; } }
apache-2.0
appshaper/appshaper
test/data/script2.js
19
var script2 = true;
apache-2.0
Traderlynk/Etherlynk
communicator/extension/jitsi-meet/interface_config.js
6209
/* eslint-disable no-unused-vars, no-var, max-len */ var interfaceConfig = { // TO FIX: this needs to be handled from SASS variables. There are some // methods allowing to use variables both in css and js. DEFAULT_BACKGROUND: '#474747', /** * In case the desktop sharing is disabled through the config the button * will not be hidden, but displayed as disabled with this text us as * a tooltip. */ DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP: null, INITIAL_TOOLBAR_TIMEOUT: 20000, TOOLBAR_TIMEOUT: 4000, TOOLBAR_ALWAYS_VISIBLE: false, DEFAULT_REMOTE_DISPLAY_NAME: 'Fellow Jitster', DEFAULT_LOCAL_DISPLAY_NAME: 'me', SHOW_JITSI_WATERMARK: true, JITSI_WATERMARK_LINK: 'https://jitsi.org', // if watermark is disabled by default, it can be shown only for guests SHOW_WATERMARK_FOR_GUESTS: true, SHOW_BRAND_WATERMARK: false, BRAND_WATERMARK_LINK: '', SHOW_POWERED_BY: false, SHOW_DEEP_LINKING_IMAGE: false, GENERATE_ROOMNAMES_ON_WELCOME_PAGE: true, DISPLAY_WELCOME_PAGE_CONTENT: true, APP_NAME: 'Jitsi Meet', NATIVE_APP_NAME: 'Jitsi Meet', LANG_DETECTION: false, // Allow i18n to detect the system language INVITATION_POWERED_BY: true, /** * If we should show authentication block in profile */ AUTHENTICATION_ENABLE: true, /** * The name of the toolbar buttons to display in the toolbar. If present, * the button will display. Exceptions are "livestreaming" and "recording" * which also require being a moderator and some values in config.js to be * enabled. Also, the "profile" button will not display for user's with a * jwt. */ TOOLBAR_BUTTONS: [ 'microphone', 'camera', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'info', 'chat', 'recording', 'livestreaming', 'etherpad', 'sharedvideo', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'invite', 'feedback', 'stats', 'shortcuts' ], SETTINGS_SECTIONS: [ 'language', 'devices', 'moderator' ], // Determines how the video would fit the screen. 'both' would fit the whole // screen, 'height' would fit the original video height to the height of the // screen, 'width' would fit the original video width to the width of the // screen respecting ratio. VIDEO_LAYOUT_FIT: 'both', /** * Whether to only show the filmstrip (and hide the toolbar). */ filmStripOnly: false, /** * Whether to show thumbnails in filmstrip as a column instead of as a row. */ VERTICAL_FILMSTRIP: true, // A html text to be shown to guests on the close page, false disables it CLOSE_PAGE_GUEST_HINT: false, RANDOM_AVATAR_URL_PREFIX: false, RANDOM_AVATAR_URL_SUFFIX: false, FILM_STRIP_MAX_HEIGHT: 120, // Enables feedback star animation. ENABLE_FEEDBACK_ANIMATION: false, DISABLE_FOCUS_INDICATOR: false, DISABLE_DOMINANT_SPEAKER_INDICATOR: false, /** * Whether the ringing sound in the call/ring overlay is disabled. If * {@code undefined}, defaults to {@code false}. * * @type {boolean} */ DISABLE_RINGING: false, AUDIO_LEVEL_PRIMARY_COLOR: 'rgba(255,255,255,0.4)', AUDIO_LEVEL_SECONDARY_COLOR: 'rgba(255,255,255,0.2)', POLICY_LOGO: null, LOCAL_THUMBNAIL_RATIO: 16 / 9, // 16:9 REMOTE_THUMBNAIL_RATIO: 1, // 1:1 // Documentation reference for the live streaming feature. LIVE_STREAMING_HELP_LINK: 'https://jitsi.org/live', /** * Whether the mobile app Jitsi Meet is to be promoted to participants * attempting to join a conference in a mobile Web browser. If * {@code undefined}, defaults to {@code true}. * * @type {boolean} */ MOBILE_APP_PROMO: true, /** * Maximum coeficient of the ratio of the large video to the visible area * after the large video is scaled to fit the window. * * @type {number} */ MAXIMUM_ZOOMING_COEFFICIENT: 1.3, /* * If indicated some of the error dialogs may point to the support URL for * help. */ SUPPORT_URL: 'https://github.com/jitsi/jitsi-meet/issues/new', /** * Whether the connection indicator icon should hide itself based on * connection strength. If true, the connection indicator will remain * displayed while the participant has a weak connection and will hide * itself after the CONNECTION_INDICATOR_HIDE_TIMEOUT when the connection is * strong. * * @type {boolean} */ CONNECTION_INDICATOR_AUTO_HIDE_ENABLED: true, /** * How long the connection indicator should remain displayed before hiding. * Used in conjunction with CONNECTION_INDICATOR_AUTOHIDE_ENABLED. * * @type {number} */ CONNECTION_INDICATOR_AUTO_HIDE_TIMEOUT: 5000, /** * The name of the application connected to the "Add people" search service. */ // ADD_PEOPLE_APP_NAME: "", /** * If true, hides the video quality label indicating the resolution status * of the current large video. * * @type {boolean} */ VIDEO_QUALITY_LABEL_DISABLED: false, /** * Temporary feature flag to debug performance with the large video * background blur. On initial implementation, blur was always enabled so a * falsy value here will be used to keep blur enabled, as will the value * "video", and will render the blur over a video element. The value * "canvas" will display the blur over a canvas element, while the value * "off" will prevent the background from rendering. */ _BACKGROUND_BLUR: 'off' /** * Specify custom URL for downloading android mobile app. */ // MOBILE_DOWNLOAD_LINK_ANDROID: 'https://play.google.com/store/apps/details?id=org.jitsi.meet', /** * Specify URL for downloading ios mobile app. */ // MOBILE_DOWNLOAD_LINK_IOS: 'https://itunes.apple.com/us/app/jitsi-meet/id1165103905', /** * Specify mobile app scheme for opening the app from the mobile browser. */ // APP_SCHEME: 'org.jitsi.meet' }; /* eslint-enable no-unused-vars, no-var, max-len */
apache-2.0
olgasm3011/ProgramTest
rest-sample/src/test/java/ru/stqa/pft/rest/Issue.java
1347
package ru.stqa.pft.rest; /** * Created by oasmir12 on 17.08.2017. */ public class Issue { private int id; private String subject; private String description; private String state_name; public int getId() { return id; } public Issue withId(int id) { this.id = id; return this; } public String getSubject() { return subject; } public Issue withSubject(String subject) { this.subject = subject; return this; } public String getDescription() { return description; } public String getStateName() { return state_name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Issue issue = (Issue) o; if (id != issue.id) return false; if (subject != null ? !subject.equals(issue.subject) : issue.subject != null) return false; return description != null ? description.equals(issue.description) : issue.description == null; } @Override public int hashCode() { int result = id; result = 31 * result + (subject != null ? subject.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); return result; } public Issue withDescription(String description) { this.description = description; return this; } }
apache-2.0
dturanski/spring-cloud-data
spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskPlatformController.java
3111
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.dataflow.server.controller; import org.springframework.cloud.dataflow.core.Launcher; import org.springframework.cloud.dataflow.rest.resource.LauncherResource; import org.springframework.cloud.dataflow.server.job.LauncherRepository; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.ExposesResourceFor; import org.springframework.hateoas.PagedResources; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * REST controller for task launching platform related operations. * * @author Ilayaperumal Gopinathan */ @RestController @RequestMapping("/tasks/platforms") @ExposesResourceFor(LauncherResource.class) public class TaskPlatformController { private final LauncherRepository launcherRepository; private final Assembler launcherAssembler = new Assembler(); public TaskPlatformController(LauncherRepository LauncherRepository) { this.launcherRepository = LauncherRepository; } /** * Returns the list of platform accounts available for launching tasks. * @param pageable the Pageable request * @param assembler the paged resource assembler for Launcher * @return the paged resources of type {@link LauncherResource} */ @RequestMapping(value = "", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public PagedResources<LauncherResource> list(Pageable pageable, PagedResourcesAssembler<Launcher> assembler) { return assembler.toResource(this.launcherRepository.findAll(pageable), this.launcherAssembler); } /** * {@link org.springframework.hateoas.ResourceAssembler} implementation that converts * {@link Launcher}s to {@link LauncherResource}s. */ private static class Assembler extends ResourceAssemblerSupport<Launcher, LauncherResource> { public Assembler() { super(TaskPlatformController.class, LauncherResource.class); } @Override public LauncherResource toResource(Launcher launcher) { return createResourceWithId(launcher.getId(), launcher); } @Override public LauncherResource instantiateResource(Launcher launcher) { return new LauncherResource(launcher); } } }
apache-2.0
everttigchelaar/camel-svn
tests/camel-itest/src/test/java/org/apache/camel/itest/ibatis/DummyTable.java
1106
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.itest.ibatis; import java.util.Collection; /** * @version */ public interface DummyTable extends Iterable<Integer> { void create(); void add(int value); void clear(); void drop(); Collection<Integer> values(); }
apache-2.0
cloudfoundry-incubator/switchboard
domain/domainfakes/fake_net_conn.go
9314
// This file was generated by counterfeiter package domainfakes import ( "net" "sync" "time" ) type FakeConn struct { ReadStub func(b []byte) (n int, err error) readMutex sync.RWMutex readArgsForCall []struct { b []byte } readReturns struct { result1 int result2 error } WriteStub func(b []byte) (n int, err error) writeMutex sync.RWMutex writeArgsForCall []struct { b []byte } writeReturns struct { result1 int result2 error } CloseStub func() error closeMutex sync.RWMutex closeArgsForCall []struct{} closeReturns struct { result1 error } LocalAddrStub func() net.Addr localAddrMutex sync.RWMutex localAddrArgsForCall []struct{} localAddrReturns struct { result1 net.Addr } RemoteAddrStub func() net.Addr remoteAddrMutex sync.RWMutex remoteAddrArgsForCall []struct{} remoteAddrReturns struct { result1 net.Addr } SetDeadlineStub func(t time.Time) error setDeadlineMutex sync.RWMutex setDeadlineArgsForCall []struct { t time.Time } setDeadlineReturns struct { result1 error } SetReadDeadlineStub func(t time.Time) error setReadDeadlineMutex sync.RWMutex setReadDeadlineArgsForCall []struct { t time.Time } setReadDeadlineReturns struct { result1 error } SetWriteDeadlineStub func(t time.Time) error setWriteDeadlineMutex sync.RWMutex setWriteDeadlineArgsForCall []struct { t time.Time } setWriteDeadlineReturns struct { result1 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeConn) Read(b []byte) (n int, err error) { var bCopy []byte if b != nil { bCopy = make([]byte, len(b)) copy(bCopy, b) } fake.readMutex.Lock() fake.readArgsForCall = append(fake.readArgsForCall, struct { b []byte }{bCopy}) fake.recordInvocation("Read", []interface{}{bCopy}) fake.readMutex.Unlock() if fake.ReadStub != nil { return fake.ReadStub(b) } else { return fake.readReturns.result1, fake.readReturns.result2 } } func (fake *FakeConn) ReadCallCount() int { fake.readMutex.RLock() defer fake.readMutex.RUnlock() return len(fake.readArgsForCall) } func (fake *FakeConn) ReadArgsForCall(i int) []byte { fake.readMutex.RLock() defer fake.readMutex.RUnlock() return fake.readArgsForCall[i].b } func (fake *FakeConn) ReadReturns(result1 int, result2 error) { fake.ReadStub = nil fake.readReturns = struct { result1 int result2 error }{result1, result2} } func (fake *FakeConn) Write(b []byte) (n int, err error) { var bCopy []byte if b != nil { bCopy = make([]byte, len(b)) copy(bCopy, b) } fake.writeMutex.Lock() fake.writeArgsForCall = append(fake.writeArgsForCall, struct { b []byte }{bCopy}) fake.recordInvocation("Write", []interface{}{bCopy}) fake.writeMutex.Unlock() if fake.WriteStub != nil { return fake.WriteStub(b) } else { return fake.writeReturns.result1, fake.writeReturns.result2 } } func (fake *FakeConn) WriteCallCount() int { fake.writeMutex.RLock() defer fake.writeMutex.RUnlock() return len(fake.writeArgsForCall) } func (fake *FakeConn) WriteArgsForCall(i int) []byte { fake.writeMutex.RLock() defer fake.writeMutex.RUnlock() return fake.writeArgsForCall[i].b } func (fake *FakeConn) WriteReturns(result1 int, result2 error) { fake.WriteStub = nil fake.writeReturns = struct { result1 int result2 error }{result1, result2} } func (fake *FakeConn) Close() error { fake.closeMutex.Lock() fake.closeArgsForCall = append(fake.closeArgsForCall, struct{}{}) fake.recordInvocation("Close", []interface{}{}) fake.closeMutex.Unlock() if fake.CloseStub != nil { return fake.CloseStub() } else { return fake.closeReturns.result1 } } func (fake *FakeConn) CloseCallCount() int { fake.closeMutex.RLock() defer fake.closeMutex.RUnlock() return len(fake.closeArgsForCall) } func (fake *FakeConn) CloseReturns(result1 error) { fake.CloseStub = nil fake.closeReturns = struct { result1 error }{result1} } func (fake *FakeConn) LocalAddr() net.Addr { fake.localAddrMutex.Lock() fake.localAddrArgsForCall = append(fake.localAddrArgsForCall, struct{}{}) fake.recordInvocation("LocalAddr", []interface{}{}) fake.localAddrMutex.Unlock() if fake.LocalAddrStub != nil { return fake.LocalAddrStub() } else { return fake.localAddrReturns.result1 } } func (fake *FakeConn) LocalAddrCallCount() int { fake.localAddrMutex.RLock() defer fake.localAddrMutex.RUnlock() return len(fake.localAddrArgsForCall) } func (fake *FakeConn) LocalAddrReturns(result1 net.Addr) { fake.LocalAddrStub = nil fake.localAddrReturns = struct { result1 net.Addr }{result1} } func (fake *FakeConn) RemoteAddr() net.Addr { fake.remoteAddrMutex.Lock() fake.remoteAddrArgsForCall = append(fake.remoteAddrArgsForCall, struct{}{}) fake.recordInvocation("RemoteAddr", []interface{}{}) fake.remoteAddrMutex.Unlock() if fake.RemoteAddrStub != nil { return fake.RemoteAddrStub() } else { return fake.remoteAddrReturns.result1 } } func (fake *FakeConn) RemoteAddrCallCount() int { fake.remoteAddrMutex.RLock() defer fake.remoteAddrMutex.RUnlock() return len(fake.remoteAddrArgsForCall) } func (fake *FakeConn) RemoteAddrReturns(result1 net.Addr) { fake.RemoteAddrStub = nil fake.remoteAddrReturns = struct { result1 net.Addr }{result1} } func (fake *FakeConn) SetDeadline(t time.Time) error { fake.setDeadlineMutex.Lock() fake.setDeadlineArgsForCall = append(fake.setDeadlineArgsForCall, struct { t time.Time }{t}) fake.recordInvocation("SetDeadline", []interface{}{t}) fake.setDeadlineMutex.Unlock() if fake.SetDeadlineStub != nil { return fake.SetDeadlineStub(t) } else { return fake.setDeadlineReturns.result1 } } func (fake *FakeConn) SetDeadlineCallCount() int { fake.setDeadlineMutex.RLock() defer fake.setDeadlineMutex.RUnlock() return len(fake.setDeadlineArgsForCall) } func (fake *FakeConn) SetDeadlineArgsForCall(i int) time.Time { fake.setDeadlineMutex.RLock() defer fake.setDeadlineMutex.RUnlock() return fake.setDeadlineArgsForCall[i].t } func (fake *FakeConn) SetDeadlineReturns(result1 error) { fake.SetDeadlineStub = nil fake.setDeadlineReturns = struct { result1 error }{result1} } func (fake *FakeConn) SetReadDeadline(t time.Time) error { fake.setReadDeadlineMutex.Lock() fake.setReadDeadlineArgsForCall = append(fake.setReadDeadlineArgsForCall, struct { t time.Time }{t}) fake.recordInvocation("SetReadDeadline", []interface{}{t}) fake.setReadDeadlineMutex.Unlock() if fake.SetReadDeadlineStub != nil { return fake.SetReadDeadlineStub(t) } else { return fake.setReadDeadlineReturns.result1 } } func (fake *FakeConn) SetReadDeadlineCallCount() int { fake.setReadDeadlineMutex.RLock() defer fake.setReadDeadlineMutex.RUnlock() return len(fake.setReadDeadlineArgsForCall) } func (fake *FakeConn) SetReadDeadlineArgsForCall(i int) time.Time { fake.setReadDeadlineMutex.RLock() defer fake.setReadDeadlineMutex.RUnlock() return fake.setReadDeadlineArgsForCall[i].t } func (fake *FakeConn) SetReadDeadlineReturns(result1 error) { fake.SetReadDeadlineStub = nil fake.setReadDeadlineReturns = struct { result1 error }{result1} } func (fake *FakeConn) SetWriteDeadline(t time.Time) error { fake.setWriteDeadlineMutex.Lock() fake.setWriteDeadlineArgsForCall = append(fake.setWriteDeadlineArgsForCall, struct { t time.Time }{t}) fake.recordInvocation("SetWriteDeadline", []interface{}{t}) fake.setWriteDeadlineMutex.Unlock() if fake.SetWriteDeadlineStub != nil { return fake.SetWriteDeadlineStub(t) } else { return fake.setWriteDeadlineReturns.result1 } } func (fake *FakeConn) SetWriteDeadlineCallCount() int { fake.setWriteDeadlineMutex.RLock() defer fake.setWriteDeadlineMutex.RUnlock() return len(fake.setWriteDeadlineArgsForCall) } func (fake *FakeConn) SetWriteDeadlineArgsForCall(i int) time.Time { fake.setWriteDeadlineMutex.RLock() defer fake.setWriteDeadlineMutex.RUnlock() return fake.setWriteDeadlineArgsForCall[i].t } func (fake *FakeConn) SetWriteDeadlineReturns(result1 error) { fake.SetWriteDeadlineStub = nil fake.setWriteDeadlineReturns = struct { result1 error }{result1} } func (fake *FakeConn) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.readMutex.RLock() defer fake.readMutex.RUnlock() fake.writeMutex.RLock() defer fake.writeMutex.RUnlock() fake.closeMutex.RLock() defer fake.closeMutex.RUnlock() fake.localAddrMutex.RLock() defer fake.localAddrMutex.RUnlock() fake.remoteAddrMutex.RLock() defer fake.remoteAddrMutex.RUnlock() fake.setDeadlineMutex.RLock() defer fake.setDeadlineMutex.RUnlock() fake.setReadDeadlineMutex.RLock() defer fake.setReadDeadlineMutex.RUnlock() fake.setWriteDeadlineMutex.RLock() defer fake.setWriteDeadlineMutex.RUnlock() return fake.invocations } func (fake *FakeConn) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ net.Conn = new(FakeConn)
apache-2.0
googleapis/nodejs-ai-platform
src/value-converter.ts
3386
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // TODO(): Remove this file once https://github.com/protobufjs/protobuf.js/pull/1495 is submitted. export interface ValueType { [index: string]: | null | boolean | string | number | ValueType | Array<string | number | ValueType>; } // INTERNAL ONLY. This function is not exposed to external callers. export function googleProtobufValueFromObject( object: ValueType, create: (result: object) => object ): object | null | ValueType | protobuf.common.IValue { if (object === null) { return create({ kind: 'nullValue', nullValue: 0, }); } if (typeof object === 'boolean') { return create({ kind: 'boolValue', boolValue: object, }); } if (typeof object === 'number') { return create({ kind: 'numberValue', numberValue: object, }); } if (typeof object === 'string') { return create({ kind: 'stringValue', stringValue: object, }); } if (Array.isArray(object)) { const array = object.map(element => { return googleProtobufValueFromObject(element, create); }); return create({ kind: 'listValue', listValue: { values: array, }, }); } if (typeof object === 'object') { // tslint:disable-next-line no-explicit-any const fields: any = {}, names: string[] = Object.keys(object); for (let i = 0; i < names.length; ++i) { const fieldName = names[i]; fields[fieldName] = googleProtobufValueFromObject( object[fieldName] as ValueType, create ); } return create({ kind: 'structValue', structValue: { fields: fields, }, }); } return null; } // INTERNAL ONLY. This function not exposed to external callers. // recursive google.protobuf.Value to plain JS object export function googleProtobufValueToObject( message: protobuf.common.IValue ): object | null | undefined | boolean | number | string { if (message.kind === 'boolValue') { return message.boolValue; } if (message.kind === 'nullValue') { return null; } if (message.kind === 'numberValue') { return message.numberValue; } if (message.kind === 'stringValue') { return message.stringValue; } if (message.kind === 'listValue') { return message.listValue?.values?.map(googleProtobufValueToObject); } if (message.kind === 'structValue') { if (!message.structValue?.fields) { return {}; } const names = Object.keys(message.structValue.fields), // tslint:disable-next-line no-explicit-any struct: any = {}; for (let i = 0; i < names.length; ++i) { struct[names[i]] = googleProtobufValueToObject( message.structValue['fields'][names[i]] ); } return struct; } return undefined; }
apache-2.0
ontop/ontop
core/model/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/db/impl/DefaultDBNonStrictNumericEqOperator.java
1545
package it.unibz.inf.ontop.model.term.functionsymbol.db.impl; import com.google.common.collect.ImmutableList; import it.unibz.inf.ontop.iq.node.VariableNullability; import it.unibz.inf.ontop.model.term.DBConstant; import it.unibz.inf.ontop.model.term.ImmutableTerm; import it.unibz.inf.ontop.model.term.TermFactory; import it.unibz.inf.ontop.model.type.DBTermType; import java.math.BigDecimal; public class DefaultDBNonStrictNumericEqOperator extends AbstractDBNonStrictEqOperator { /** * TODO: type the input */ protected DefaultDBNonStrictNumericEqOperator(DBTermType rootDBTermType, DBTermType dbBoolean) { super("NUM_NON_STRICT_EQ", rootDBTermType, dbBoolean); } @Override public boolean canBePostProcessed(ImmutableList<? extends ImmutableTerm> arguments) { return true; } @Override protected ImmutableTerm buildTermAfterEvaluation(ImmutableList<ImmutableTerm> newTerms, TermFactory termFactory, VariableNullability variableNullability) { if (newTerms.stream().allMatch(t -> t instanceof DBConstant)) { BigDecimal n1 = new BigDecimal(((DBConstant) newTerms.get(0)).getValue()); BigDecimal n2 = new BigDecimal(((DBConstant) newTerms.get(1)).getValue()); return termFactory.getDBBooleanConstant(n1.compareTo(n2) == 0); } return super.buildTermAfterEvaluation(newTerms, termFactory, variableNullability); } }
apache-2.0
Distrotech/fop
src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
18129
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.render.afp; import java.awt.Color; import java.awt.Dimension; import java.awt.geom.AffineTransform; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.fop.afp.AFPDitheredRectanglePainter; import org.apache.fop.afp.AFPPaintingState; import org.apache.fop.afp.AFPRectanglePainter; import org.apache.fop.afp.AFPResourceLevelDefaults; import org.apache.fop.afp.AFPResourceManager; import org.apache.fop.afp.AFPUnitConverter; import org.apache.fop.afp.AbstractAFPPainter; import org.apache.fop.afp.DataStream; import org.apache.fop.afp.fonts.AFPFontCollection; import org.apache.fop.afp.fonts.AFPPageFonts; import org.apache.fop.afp.modca.ResourceObject; import org.apache.fop.afp.util.DefaultFOPResourceAccessor; import org.apache.fop.afp.util.ResourceAccessor; import org.apache.fop.apps.MimeConstants; import org.apache.fop.fonts.FontCollection; import org.apache.fop.fonts.FontEventAdapter; import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontManager; import org.apache.fop.render.afp.extensions.AFPElementMapping; import org.apache.fop.render.afp.extensions.AFPIncludeFormMap; import org.apache.fop.render.afp.extensions.AFPInvokeMediumMap; import org.apache.fop.render.afp.extensions.AFPPageOverlay; import org.apache.fop.render.afp.extensions.AFPPageSegmentElement; import org.apache.fop.render.afp.extensions.AFPPageSetup; import org.apache.fop.render.afp.extensions.ExtensionPlacement; import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.intermediate.IFException; import org.apache.fop.render.intermediate.IFPainter; /** * {@link org.apache.fop.render.intermediate.IFDocumentHandler} implementation that * produces AFP (MO:DCA). */ public class AFPDocumentHandler extends AbstractBinaryWritingIFDocumentHandler implements AFPCustomizable { //** logging instance */ //private static Log log = LogFactory.getLog(AFPDocumentHandler.class); /** the resource manager */ private AFPResourceManager resourceManager; /** the painting state */ private final AFPPaintingState paintingState; /** unit converter */ private final AFPUnitConverter unitConv; /** the AFP datastream */ private DataStream dataStream; /** the map of page segments */ private Map<String, PageSegmentDescriptor> pageSegmentMap = new java.util.HashMap<String, PageSegmentDescriptor>(); private static enum Location { ELSEWHERE, IN_DOCUMENT_HEADER, FOLLOWING_PAGE_SEQUENCE, IN_PAGE_HEADER } private Location location = Location.ELSEWHERE; /** temporary holds extensions that have to be deferred until the end of the page-sequence */ private List<AFPPageSetup> deferredPageSequenceExtensions = new java.util.LinkedList<AFPPageSetup>(); /** the shading mode for filled rectangles */ private AFPShadingMode shadingMode = AFPShadingMode.COLOR; /** * Default constructor. */ public AFPDocumentHandler() { this.resourceManager = new AFPResourceManager(); this.paintingState = new AFPPaintingState(); this.unitConv = paintingState.getUnitConverter(); } /** {@inheritDoc} */ public boolean supportsPagesOutOfOrder() { return false; } /** {@inheritDoc} */ public String getMimeType() { return MimeConstants.MIME_AFP; } /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { return new AFPRendererConfigurator(getUserAgent()); } /** {@inheritDoc} */ @Override public void setDefaultFontInfo(FontInfo fontInfo) { FontManager fontManager = getUserAgent().getFactory().getFontManager(); FontCollection[] fontCollections = new FontCollection[] { new AFPFontCollection(getUserAgent().getEventBroadcaster(), null) }; FontInfo fi = (fontInfo != null ? fontInfo : new FontInfo()); fi.setEventListener(new FontEventAdapter(getUserAgent().getEventBroadcaster())); fontManager.setup(fi, fontCollections); setFontInfo(fi); } AFPPaintingState getPaintingState() { return this.paintingState; } DataStream getDataStream() { return this.dataStream; } AFPResourceManager getResourceManager() { return this.resourceManager; } AbstractAFPPainter createRectanglePainter() { if (AFPShadingMode.DITHERED.equals(this.shadingMode)) { return new AFPDitheredRectanglePainter( getPaintingState(), getDataStream(), getResourceManager()); } else { return new AFPRectanglePainter( getPaintingState(), getDataStream()); } } /** {@inheritDoc} */ @Override public void startDocument() throws IFException { super.startDocument(); try { paintingState.setColor(Color.WHITE); this.dataStream = resourceManager.createDataStream(paintingState, outputStream); this.dataStream.startDocument(); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } } /** {@inheritDoc} */ @Override public void startDocumentHeader() throws IFException { super.startDocumentHeader(); this.location = Location.IN_DOCUMENT_HEADER; } /** {@inheritDoc} */ @Override public void endDocumentHeader() throws IFException { super.endDocumentHeader(); this.location = Location.ELSEWHERE; } /** {@inheritDoc} */ @Override public void endDocument() throws IFException { try { this.dataStream.endDocument(); this.dataStream = null; this.resourceManager.writeToStream(); this.resourceManager = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); } /** {@inheritDoc} */ public void startPageSequence(String id) throws IFException { try { dataStream.startPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); } this.location = Location.FOLLOWING_PAGE_SEQUENCE; } /** {@inheritDoc} */ public void endPageSequence() throws IFException { try { //Process deferred page-sequence-level extensions Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator(); while (iter.hasNext()) { AFPPageSetup aps = iter.next(); iter.remove(); if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) { handleNOP(aps); } else { throw new UnsupportedOperationException("Don't know how to handle " + aps); } } //End page sequence dataStream.endPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); } this.location = Location.ELSEWHERE; } /** * Returns the base AFP transform * * @return the base AFP transform */ private AffineTransform getBaseTransform() { AffineTransform baseTransform = new AffineTransform(); double scale = unitConv.mpt2units(1); baseTransform.scale(scale, scale); return baseTransform; } /** {@inheritDoc} */ public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.location = Location.ELSEWHERE; paintingState.clear(); AffineTransform baseTransform = getBaseTransform(); paintingState.concatenate(baseTransform); int pageWidth = Math.round(unitConv.mpt2units(size.width)); paintingState.setPageWidth(pageWidth); int pageHeight = Math.round(unitConv.mpt2units(size.height)); paintingState.setPageHeight(pageHeight); int pageRotation = paintingState.getPageRotation(); int resolution = paintingState.getResolution(); dataStream.startPage(pageWidth, pageHeight, pageRotation, resolution, resolution); } /** {@inheritDoc} */ @Override public void startPageHeader() throws IFException { super.startPageHeader(); this.location = Location.IN_PAGE_HEADER; } /** {@inheritDoc} */ @Override public void endPageHeader() throws IFException { this.location = Location.ELSEWHERE; super.endPageHeader(); } /** {@inheritDoc} */ public IFPainter startPageContent() throws IFException { return new AFPPainter(this); } /** {@inheritDoc} */ public void endPageContent() throws IFException { } /** {@inheritDoc} */ public void endPage() throws IFException { try { AFPPageFonts pageFonts = paintingState.getPageFonts(); if (pageFonts != null && !pageFonts.isEmpty()) { dataStream.addFontsToCurrentPage(pageFonts); } dataStream.endPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } } /** {@inheritDoc} */ public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof AFPPageSetup) { AFPPageSetup aps = (AFPPageSetup)extension; String element = aps.getElementName(); if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: case IN_PAGE_HEADER: String name = aps.getName(); String value = aps.getValue(); dataStream.createTagLogicalElement(name, value); break; default: throw new IFException( "TLE extension must be in the page header or between page-sequence" + " and the first page: " + aps, null); } } else if (AFPElementMapping.NO_OPERATION.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: if (aps.getPlacement() == ExtensionPlacement.BEFORE_END) { this.deferredPageSequenceExtensions.add(aps); break; } case IN_DOCUMENT_HEADER: case IN_PAGE_HEADER: handleNOP(aps); break; default: throw new IFException( "NOP extension must be in the document header, the page header" + " or between page-sequence" + " and the first page: " + aps, null); } } else { if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page setup extension encountered outside the page header: " + aps, null); } if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(element)) { AFPPageSegmentElement.AFPPageSegmentSetup apse = (AFPPageSegmentElement.AFPPageSegmentSetup)aps; String name = apse.getName(); String source = apse.getValue(); String uri = apse.getResourceSrc(); pageSegmentMap.put(source, new PageSegmentDescriptor(name, uri)); } } } else if (extension instanceof AFPPageOverlay) { AFPPageOverlay ipo = (AFPPageOverlay)extension; if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page overlay extension encountered outside the page header: " + ipo, null); } String overlay = ipo.getName(); if (overlay != null) { dataStream.createIncludePageOverlay(overlay, ipo.getX(), ipo.getY()); } } else if (extension instanceof AFPInvokeMediumMap) { if (this.location != Location.FOLLOWING_PAGE_SEQUENCE && this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP IMM extension must be between page-sequence" + " and the first page or child of page-header: " + extension, null); } AFPInvokeMediumMap imm = (AFPInvokeMediumMap)extension; String mediumMap = imm.getName(); if (mediumMap != null) { dataStream.createInvokeMediumMap(mediumMap); } } else if (extension instanceof AFPIncludeFormMap) { AFPIncludeFormMap formMap = (AFPIncludeFormMap)extension; ResourceAccessor accessor = new DefaultFOPResourceAccessor( getUserAgent(), null, null); try { getResourceManager().createIncludedResource(formMap.getName(), formMap.getSrc(), accessor, ResourceObject.TYPE_FORMDEF); } catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); } } } private void handleNOP(AFPPageSetup nop) { String content = nop.getContent(); if (content != null) { dataStream.createNoOperation(content); } } // ---=== AFPCustomizable ===--- /** {@inheritDoc} */ public void setBitsPerPixel(int bitsPerPixel) { paintingState.setBitsPerPixel(bitsPerPixel); } /** {@inheritDoc} */ public void setColorImages(boolean colorImages) { paintingState.setColorImages(colorImages); } /** {@inheritDoc} */ public void setNativeImagesSupported(boolean nativeImages) { paintingState.setNativeImagesSupported(nativeImages); } /** {@inheritDoc} */ public void setCMYKImagesSupported(boolean value) { paintingState.setCMYKImagesSupported(value); } /** {@inheritDoc} */ public void setDitheringQuality(float quality) { this.paintingState.setDitheringQuality(quality); } /** {@inheritDoc} */ public void setBitmapEncodingQuality(float quality) { this.paintingState.setBitmapEncodingQuality(quality); } /** {@inheritDoc} */ public void setShadingMode(AFPShadingMode shadingMode) { this.shadingMode = shadingMode; } /** {@inheritDoc} */ public void setResolution(int resolution) { paintingState.setResolution(resolution); } /** {@inheritDoc} */ public void setLineWidthCorrection(float correction) { paintingState.setLineWidthCorrection(correction); } /** {@inheritDoc} */ public int getResolution() { return paintingState.getResolution(); } /** {@inheritDoc} */ public void setGOCAEnabled(boolean enabled) { this.paintingState.setGOCAEnabled(enabled); } /** {@inheritDoc} */ public boolean isGOCAEnabled() { return this.paintingState.isGOCAEnabled(); } /** {@inheritDoc} */ public void setStrokeGOCAText(boolean stroke) { this.paintingState.setStrokeGOCAText(stroke); } /** {@inheritDoc} */ public boolean isStrokeGOCAText() { return this.paintingState.isStrokeGOCAText(); } /** {@inheritDoc} */ public void setWrapPSeg(boolean pSeg) { paintingState.setWrapPSeg(pSeg); } /** {@inheritDoc} */ public void setFS45(boolean fs45) { paintingState.setFS45(fs45); } /** {@inheritDoc} */ public boolean getWrapPSeg() { return paintingState.getWrapPSeg(); } /** {@inheritDoc} */ public boolean getFS45() { return paintingState.getFS45(); } /** {@inheritDoc} */ public void setDefaultResourceGroupFilePath(String filePath) { resourceManager.setDefaultResourceGroupFilePath(filePath); } /** {@inheritDoc} */ public void setResourceLevelDefaults(AFPResourceLevelDefaults defaults) { resourceManager.setResourceLevelDefaults(defaults); } /** * Returns the page segment descriptor for a given URI if it actually represents a page segment. * Otherwise, it just returns null. * @param uri the URI that identifies the page segment * @return the page segment descriptor or null if there's no page segment for the given URI */ PageSegmentDescriptor getPageSegmentNameFor(String uri) { return pageSegmentMap.get(uri); } /** {@inheritDoc} */ public void canEmbedJpeg(boolean canEmbed) { paintingState.setCanEmbedJpeg(canEmbed); } }
apache-2.0
GunoH/intellij-community
platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java
28143
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.application.impl; import com.intellij.ReviseWhenPortedToJDK; import com.intellij.diagnostic.Activity; import com.intellij.diagnostic.ActivityCategory; import com.intellij.diagnostic.StartUpMeasurer; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.IdeUrlTrackingParametersProvider; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.ex.ProgressSlide; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.util.BuildNumber; import com.intellij.openapi.util.NlsSafe; import com.intellij.serviceContainer.NonInjectable; import com.intellij.util.XmlElement; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.text.MessageFormat; import java.util.*; /** * Provides access to content of *ApplicationInfo.xml file. Scheme for *ApplicationInfo.xml files is defined * in platform/platform-resources/src/idea/ApplicationInfo.xsd, * so you need to update it when adding or removing support for some XML elements in this class. */ public final class ApplicationInfoImpl extends ApplicationInfoEx { public static final String DEFAULT_PLUGINS_HOST = "https://plugins.jetbrains.com"; static final String IDEA_PLUGINS_HOST_PROPERTY = "idea.plugins.host"; private static volatile ApplicationInfoImpl instance; private String myCodeName; private String myMajorVersion; private String myMinorVersion; private String myMicroVersion; private String myPatchVersion; private String myFullVersionFormat; private String myBuildNumber; private String myApiVersion; private String myVersionSuffix; private String myCompanyName = "JetBrains s.r.o."; private String myCopyrightStart = "2000"; private String myShortCompanyName; private String myCompanyUrl = "https://www.jetbrains.com/"; private long myProgressColor = -1; private long myCopyrightForeground = -1; private long myAboutForeground = -1; private long myAboutLinkColor = -1; private int[] myAboutLogoRect; // don't use Rectangle to avoid dependency on AWT private String myProgressTailIconName; private int myProgressHeight = 2; private int myProgressY = 350; private String mySplashImageUrl; private String myAboutImageUrl; private String myIconUrl = "/icon.png"; private String mySmallIconUrl = "/icon_small.png"; private String myBigIconUrl; private String mySvgIconUrl; private String mySvgEapIconUrl; private String mySmallSvgIconUrl; private String mySmallSvgEapIconUrl; private String myToolWindowIconUrl = "/toolwindows/toolWindowProject.svg"; private String myWelcomeScreenLogoUrl; private Calendar myBuildDate; private Calendar myMajorReleaseBuildDate; private boolean myShowLicensee = true; private String myWelcomeScreenDialog; private UpdateUrls myUpdateUrls; private String myDocumentationUrl; private String mySupportUrl; private String myYoutrackUrl; private String myFeedbackUrl; private String myPluginManagerUrl; private String myPluginsListUrl; private String myChannelsListUrl; private String myPluginsDownloadUrl; private String myBuiltinPluginsUrl; private String myWhatsNewUrl; private int myWhatsNewEligibility; private String myWinKeymapUrl; private String myMacKeymapUrl; private boolean myEAP; private boolean myHasHelp = true; private boolean myHasContextHelp = true; private String myWebHelpUrl = "https://www.jetbrains.com/idea/webhelp/"; private final List<PluginId> essentialPluginsIds = new ArrayList<>(); private String myEventLogSettingsUrl = "https://resources.jetbrains.com/storage/fus/config/v4/%s/%s.json"; private String myJetBrainsTvUrl; private String myKeyConversionUrl = "https://www.jetbrains.com/shop/eform/keys-exchange"; private String mySubscriptionFormId; private String mySubscriptionNewsKey; private String mySubscriptionNewsValue; private String mySubscriptionTipsKey; private boolean mySubscriptionTipsAvailable; private String mySubscriptionAdditionalFormData; private List<ProgressSlide> progressSlides = Collections.emptyList(); private ZenDeskForm myFeedbackForm; private String myDefaultLightLaf; private String myDefaultDarkLaf; // if application loader was not used @SuppressWarnings("unused") private ApplicationInfoImpl() { this(ApplicationNamesInfo.initAndGetRawData()); } @NonInjectable ApplicationInfoImpl(@NotNull XmlElement element) { // behavior of this method must be consistent with idea/ApplicationInfo.xsd schema. for (XmlElement child : element.children) { switch (child.name) { case "version": { myMajorVersion = child.getAttributeValue("major"); myMinorVersion = child.getAttributeValue("minor"); myMicroVersion = child.getAttributeValue("micro"); myPatchVersion = child.getAttributeValue("patch"); myFullVersionFormat = child.getAttributeValue("full"); myCodeName = child.getAttributeValue("codename"); myEAP = Boolean.parseBoolean(child.getAttributeValue("eap")); myVersionSuffix = child.getAttributeValue("suffix"); if (myVersionSuffix == null && myEAP) { myVersionSuffix = "EAP"; } } break; case "company": { myCompanyName = child.getAttributeValue("name", myCompanyName); myShortCompanyName = child.getAttributeValue("shortName", myCompanyName == null ? null : shortenCompanyName(myCompanyName)); myCompanyUrl = child.getAttributeValue("url", myCompanyUrl); myCopyrightStart = child.getAttributeValue("copyrightStart", myCopyrightStart); } break; case "build": { readBuildInfo(child); } break; case "logo": { readLogoInfo(child); } break; case "about": { myAboutImageUrl = child.getAttributeValue("url"); String v = child.getAttributeValue("foreground"); if (v != null) { myAboutForeground = parseColor(v); } v = child.getAttributeValue("copyrightForeground"); if (v != null) { myCopyrightForeground = parseColor(v); } String c = child.getAttributeValue("linkColor"); if (c != null) { myAboutLinkColor = parseColor(c); } String logoX = child.getAttributeValue("logoX"); String logoY = child.getAttributeValue("logoY"); String logoW = child.getAttributeValue("logoW"); String logoH = child.getAttributeValue("logoH"); if (logoX != null && logoY != null && logoW != null && logoH != null) { try { myAboutLogoRect = new int[]{Integer.parseInt(logoX), Integer.parseInt(logoY), Integer.parseInt(logoW), Integer.parseInt(logoH)}; } catch (NumberFormatException ignored) { } } } break; case "icon": { myIconUrl = child.getAttributeValue("size32"); mySmallIconUrl = child.getAttributeValue("size16", mySmallIconUrl); myBigIconUrl = getAttributeValue(child, "size128"); String toolWindowIcon = getAttributeValue(child, "size12"); if (toolWindowIcon != null) { myToolWindowIconUrl = toolWindowIcon; } mySvgIconUrl = child.getAttributeValue("svg"); mySmallSvgIconUrl = child.getAttributeValue("svg-small"); } break; case "icon-eap": { mySvgEapIconUrl = child.getAttributeValue("svg"); mySmallSvgEapIconUrl = child.getAttributeValue("svg-small"); } break; case "licensee": { myShowLicensee = Boolean.parseBoolean(child.getAttributeValue("show")); } break; case "welcome-screen": { myWelcomeScreenLogoUrl = child.getAttributeValue("logo-url"); } break; case "welcome-wizard": { myWelcomeScreenDialog = getAttributeValue(child, "dialog"); } break; case "help": { String webHelpUrl = getAttributeValue(child, "webhelp-url"); if (webHelpUrl != null) { myWebHelpUrl = webHelpUrl; } String attValue = child.getAttributeValue("has-help"); myHasHelp = attValue == null || Boolean.parseBoolean(attValue); // Default is true attValue = child.getAttributeValue("has-context-help"); myHasContextHelp = attValue == null || Boolean.parseBoolean(attValue); // Default is true } break; case "update-urls": { myUpdateUrls = new UpdateUrlsImpl(child); } break; case "documentation": { myDocumentationUrl = child.getAttributeValue("url"); } break; case "support": { mySupportUrl = child.getAttributeValue("url"); } break; case "youtrack": { myYoutrackUrl = child.getAttributeValue("url"); } break; case "feedback": { myFeedbackUrl = child.getAttributeValue("url"); if (child.getAttributeValue("zendesk-form-id") != null) { myFeedbackForm = ZenDeskForm.parse(child); } } break; //noinspection SpellCheckingInspection case "whatsnew": { myWhatsNewUrl = child.getAttributeValue("url"); String eligibility = child.getAttributeValue("eligibility"); if ("embed".equals(eligibility)) { myWhatsNewEligibility = WHATS_NEW_EMBED; } else if ("auto".equals(eligibility)) { myWhatsNewEligibility = WHATS_NEW_AUTO; } } break; case "plugins": { readPluginInfo(child); } break; case "keymap": { myWinKeymapUrl = child.getAttributeValue("win"); myMacKeymapUrl = child.getAttributeValue("mac"); } break; case "essential-plugin": { String id = child.content; if (id != null && !id.isEmpty()) { essentialPluginsIds.add(PluginId.getId(id)); } } break; case "statistics": { myEventLogSettingsUrl = child.getAttributeValue("event-log-settings"); } break; case "jetbrains-tv": { myJetBrainsTvUrl = child.getAttributeValue("url"); } break; case "licensing": { String url = getAttributeValue(child, "key-conversion-url"); if (url != null) { myKeyConversionUrl = url.trim(); } } break; case "subscriptions": { //noinspection SpellCheckingInspection mySubscriptionFormId = child.getAttributeValue("formid"); mySubscriptionNewsKey = child.getAttributeValue("news-key"); mySubscriptionNewsValue = child.getAttributeValue("news-value", "yes"); mySubscriptionTipsKey = child.getAttributeValue("tips-key"); mySubscriptionTipsAvailable = Boolean.parseBoolean(child.getAttributeValue("tips-available")); mySubscriptionAdditionalFormData = child.getAttributeValue("additional-form-data"); } break; case "default-laf": { String laf = getAttributeValue(child, "light"); if (laf != null) { myDefaultLightLaf = laf.trim(); } laf = getAttributeValue(child, "dark"); if (laf != null) { myDefaultDarkLaf = laf.trim(); } } break; } } essentialPluginsIds.sort(null); } private void readLogoInfo(@NotNull XmlElement element) { mySplashImageUrl = getAttributeValue(element, "url"); String v = element.getAttributeValue("progressColor"); if (v != null && !v.isEmpty()) { myProgressColor = parseColor(v); } v = element.getAttributeValue("progressTailIcon"); if (v != null && !v.isEmpty()) { myProgressTailIconName = v; } v = element.getAttributeValue("progressHeight"); if (v != null && !v.isEmpty()) { myProgressHeight = Integer.parseInt(v); } v = element.getAttributeValue("progressY"); if (v != null && !v.isEmpty()) { myProgressY = Integer.parseInt(v); } if (!element.children.isEmpty()) { progressSlides = new ArrayList<>(element.children.size()); for (XmlElement child : element.children) { if (!child.name.equals("progressSlide")) { continue; } String slideUrl = Objects.requireNonNull(child.getAttributeValue("url")); String progressPercent = Objects.requireNonNull(child.getAttributeValue("progressPercent")); int progressPercentInt = Integer.parseInt(progressPercent); if (progressPercentInt < 0 || progressPercentInt > 100) { throw new IllegalArgumentException("Expected [0, 100], got " + progressPercent); } float progressPercentFloat = (float)progressPercentInt / 100; progressSlides.add(new ProgressSlide(slideUrl, progressPercentFloat)); } } } public static @NotNull ApplicationInfoEx getShadowInstance() { return getShadowInstanceImpl(); } @ApiStatus.Internal public static @NotNull ApplicationInfoImpl getShadowInstanceImpl() { ApplicationInfoImpl result = instance; if (result != null) { return result; } //noinspection SynchronizeOnThis synchronized (ApplicationInfoImpl.class) { result = instance; if (result == null) { Activity activity = StartUpMeasurer.startActivity("app info loading", ActivityCategory.DEFAULT); try { result = new ApplicationInfoImpl(ApplicationNamesInfo.initAndGetRawData()); instance = result; } finally { activity.end(); } } } return result; } public static @NotNull String orFromPluginsCompatibleBuild(@Nullable BuildNumber buildNumber) { BuildNumber number = buildNumber != null ? buildNumber : getShadowInstanceImpl().getPluginsCompatibleBuildAsNumber(); return number.asString(); } @Override public Calendar getBuildDate() { if (myBuildDate == null) { myBuildDate = Calendar.getInstance(); } return myBuildDate; } @Override public Calendar getMajorReleaseBuildDate() { return myMajorReleaseBuildDate != null ? myMajorReleaseBuildDate : myBuildDate; } @Override public @NotNull BuildNumber getBuild() { return Objects.requireNonNull(BuildNumber.fromString(myBuildNumber)); } @Override public @NotNull String getApiVersion() { return getApiVersionAsNumber().asString(); } @Override public @NotNull BuildNumber getApiVersionAsNumber() { BuildNumber build = getBuild(); if (myApiVersion != null) { BuildNumber api = fromStringWithProductCode(myApiVersion, build); if (api != null) { return api; } } return build; } @Override public String getMajorVersion() { return myMajorVersion; } @Override public String getMinorVersion() { return myMinorVersion; } @Override public String getMicroVersion() { return myMicroVersion; } @Override public String getPatchVersion() { return myPatchVersion; } @Override public @NotNull String getFullVersion() { String result; if (myFullVersionFormat != null) { result = MessageFormat.format(myFullVersionFormat, myMajorVersion, myMinorVersion, myMicroVersion, myPatchVersion); } else { result = requireNonNullElse(myMajorVersion) + '.' + requireNonNullElse(myMinorVersion); } if (myVersionSuffix != null && !myVersionSuffix.isEmpty()) { result += " " + myVersionSuffix; } return result; } @Override public @NotNull String getStrictVersion() { return myMajorVersion + "." + myMinorVersion + "." + requireNonNullElse(myMicroVersion) + "." + requireNonNullElse(myPatchVersion); } @Override public String getVersionName() { String fullName = ApplicationNamesInfo.getInstance().getFullProductName(); if (myEAP && myCodeName != null && !myCodeName.isEmpty()) { fullName += " (" + myCodeName + ")"; } return fullName; } @Override public String getShortCompanyName() { return myShortCompanyName; } @Override public String getCompanyName() { return myCompanyName; } @Override public String getCompanyURL() { return IdeUrlTrackingParametersProvider.getInstance().augmentUrl(myCompanyUrl); } @Override public String getSplashImageUrl() { return mySplashImageUrl; } @Override public String getAboutImageUrl() { return myAboutImageUrl; } @Override public long getProgressColor() { return myProgressColor; } @Override public long getCopyrightForeground() { return myCopyrightForeground; } @Override public int getProgressHeight() { return myProgressHeight; } @Override public int getProgressY() { return myProgressY; } @Override public @Nullable String getProgressTailIcon() { return myProgressTailIconName; } @Override public String getIconUrl() { return myIconUrl; } @Override public @NotNull String getSmallIconUrl() { return mySmallIconUrl; } @Override public @Nullable String getBigIconUrl() { return myBigIconUrl; } @Override public @Nullable String getApplicationSvgIconUrl() { return isEAP() && mySvgEapIconUrl != null ? mySvgEapIconUrl : mySvgIconUrl; } @Override public @Nullable String getSmallApplicationSvgIconUrl() { return getSmallApplicationSvgIconUrl(isEAP()); } public @Nullable String getSmallApplicationSvgIconUrl(boolean isEap) { return isEap && mySmallSvgEapIconUrl != null ? mySmallSvgEapIconUrl : mySmallSvgIconUrl; } @Override public String getToolWindowIconUrl() { return myToolWindowIconUrl; } @Override public @Nullable String getWelcomeScreenLogoUrl() { return myWelcomeScreenLogoUrl; } @Override public @Nullable String getWelcomeWizardDialog() { return myWelcomeScreenDialog; } @Override public String getPackageCode() { return null; } @Override public boolean isEAP() { return myEAP; } @Override public boolean isMajorEAP() { return myEAP && (myMinorVersion == null || myMinorVersion.indexOf('.') < 0); } @Override public @Nullable UpdateUrls getUpdateUrls() { return myUpdateUrls; } @Override public String getDocumentationUrl() { return myDocumentationUrl; } @Override public String getSupportUrl() { return mySupportUrl; } @Override public String getYoutrackUrl() { return myYoutrackUrl; } @Override public String getFeedbackUrl() { return myFeedbackUrl; } @Override public String getPluginManagerUrl() { return myPluginManagerUrl; } @Override public boolean usesJetBrainsPluginRepository() { return DEFAULT_PLUGINS_HOST.equalsIgnoreCase(myPluginManagerUrl); } @Override public String getPluginsListUrl() { return myPluginsListUrl; } @Override public String getChannelsListUrl() { return myChannelsListUrl; } @Override public String getPluginsDownloadUrl() { return myPluginsDownloadUrl; } @Override public String getBuiltinPluginsUrl() { return myBuiltinPluginsUrl; } @Override public String getWebHelpUrl() { return myWebHelpUrl; } @Override public boolean hasHelp() { return myHasHelp; } @Override public boolean hasContextHelp() { return myHasContextHelp; } @Override public String getWhatsNewUrl() { return myWhatsNewUrl; } @Override public boolean isWhatsNewEligibleFor(int role) { return myWhatsNewEligibility >= role; } @Override public String getWinKeymapUrl() { return myWinKeymapUrl; } @Override public String getMacKeymapUrl() { return myMacKeymapUrl; } @Override public long getAboutForeground() { return myAboutForeground; } @Override public long getAboutLinkColor() { return myAboutLinkColor; } @Override public String getFullApplicationName() { return getVersionName() + " " + getFullVersion(); } @Override public boolean showLicenseeInfo() { return myShowLicensee; } @Override public String getCopyrightStart() { return myCopyrightStart; } public String getEventLogSettingsUrl() { return myEventLogSettingsUrl; } @Override public String getJetBrainsTvUrl() { return myJetBrainsTvUrl; } @Override public String getKeyConversionUrl() { return myKeyConversionUrl; } @Override public int @Nullable [] getAboutLogoRect() { return myAboutLogoRect; } @Override public String getSubscriptionFormId() { return mySubscriptionFormId; } @Override public String getSubscriptionNewsKey() { return mySubscriptionNewsKey; } @Override public String getSubscriptionNewsValue() { return mySubscriptionNewsValue; } @Override public String getSubscriptionTipsKey() { return mySubscriptionTipsKey; } @Override public boolean areSubscriptionTipsAvailable() { return mySubscriptionTipsAvailable; } @Override public @Nullable String getSubscriptionAdditionalFormData() { return mySubscriptionAdditionalFormData; } @Override public @NotNull List<ProgressSlide> getProgressSlides() { return progressSlides; } public @NotNull @NlsSafe String getPluginsCompatibleBuild() { return getPluginsCompatibleBuildAsNumber().asString(); } public @NotNull BuildNumber getPluginsCompatibleBuildAsNumber() { @Nullable BuildNumber compatibleBuild = BuildNumber.fromPluginsCompatibleBuild(); BuildNumber version = compatibleBuild != null ? compatibleBuild : getApiVersionAsNumber(); BuildNumber buildNumber = fromStringWithProductCode(version.asString(), getBuild()); return Objects.requireNonNull(buildNumber); } private static @Nullable BuildNumber fromStringWithProductCode(@NotNull String version, @NotNull BuildNumber buildNumber) { return BuildNumber.fromStringWithProductCode(version, buildNumber.getProductCode()); } private static @Nullable String getAttributeValue(@NotNull XmlElement element, @NotNull String name) { String value = element.getAttributeValue(name); return (value == null || value.isEmpty()) ? null : value; } private void readBuildInfo(@NotNull XmlElement element) { myBuildNumber = getAttributeValue(element, "number"); myApiVersion = getAttributeValue(element, "apiVersion"); String dateString = element.getAttributeValue("date"); if (dateString != null && !dateString.equals("__BUILD_DATE__")) { myBuildDate = parseDate(dateString); } String majorReleaseDateString = element.getAttributeValue("majorReleaseDate"); if (majorReleaseDateString != null) { myMajorReleaseBuildDate = parseDate(majorReleaseDateString); } } private void readPluginInfo(@Nullable XmlElement element) { String pluginManagerUrl = DEFAULT_PLUGINS_HOST; String pluginsListUrl = null; myChannelsListUrl = null; myPluginsDownloadUrl = null; if (element != null) { String url = element.getAttributeValue("url"); if (url != null) { pluginManagerUrl = url.endsWith("/") ? url.substring(0, url.length() - 1) : url; } String listUrl = element.getAttributeValue("list-url"); if (listUrl != null) { pluginsListUrl = listUrl; } String channelListUrl = element.getAttributeValue("channel-list-url"); if (channelListUrl != null) { myChannelsListUrl = channelListUrl; } String downloadUrl = element.getAttributeValue("download-url"); if (downloadUrl != null) { myPluginsDownloadUrl = downloadUrl; } String builtinPluginsUrl = element.getAttributeValue("builtin-url"); if (builtinPluginsUrl != null && !builtinPluginsUrl.isEmpty()) { myBuiltinPluginsUrl = builtinPluginsUrl; } } String pluginsHost = System.getProperty(IDEA_PLUGINS_HOST_PROPERTY); if (pluginsHost != null) { pluginManagerUrl = pluginsHost.endsWith("/") ? pluginsHost.substring(0, pluginsHost.length() - 1) : pluginsHost; pluginsListUrl = myChannelsListUrl = myPluginsDownloadUrl = null; } myPluginManagerUrl = pluginManagerUrl; myPluginsListUrl = pluginsListUrl == null ? (pluginManagerUrl + "/plugins/list/") : pluginsListUrl; if (myChannelsListUrl == null) { myChannelsListUrl = pluginManagerUrl + "/channels/list/"; } if (myPluginsDownloadUrl == null) { myPluginsDownloadUrl = pluginManagerUrl + "/pluginManager/"; } } // copy of ApplicationInfoProperties.shortenCompanyName private static String shortenCompanyName(@NotNull String name) { if (name.endsWith(" s.r.o.")) { name = name.substring(0, name.length() - " s.r.o.".length()); } if (name.endsWith(" Inc.")) { name = name.substring(0, name.length() - " Inc.".length()); } return name; } private static @NotNull GregorianCalendar parseDate(@NotNull String dateString) { GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); try { calendar.set(Calendar.YEAR, Integer.parseInt(dateString.substring(0, 4))); calendar.set(Calendar.MONTH, Integer.parseInt(dateString.substring(4, 6)) - 1); calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateString.substring(6, 8))); if (dateString.length() > 8) { calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(dateString.substring(8, 10))); calendar.set(Calendar.MINUTE, Integer.parseInt(dateString.substring(10, 12))); } else { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); } } catch (Exception ignore) { } return calendar; } private static long parseColor(@NotNull String colorString) { return Long.parseLong(colorString, 16); } @ReviseWhenPortedToJDK("9") private static String requireNonNullElse(String s) { return s != null ? s : "0"; } @Override public boolean isEssentialPlugin(@NotNull String pluginId) { return PluginManagerCore.CORE_PLUGIN_ID.equals(pluginId) || isEssentialPlugin(PluginId.getId(pluginId)); } @Override public boolean isEssentialPlugin(@NotNull PluginId pluginId) { return PluginManagerCore.CORE_ID.equals(pluginId) || Collections.binarySearch(essentialPluginsIds, pluginId) >= 0; } @Override public @NotNull List<PluginId> getEssentialPluginsIds() { return essentialPluginsIds; } @Override public @Nullable String getDefaultLightLaf() { return myDefaultLightLaf; } @Override public @Nullable String getDefaultDarkLaf() { return myDefaultDarkLaf; } @Nullable public ZenDeskForm getFeedbackForm() { return myFeedbackForm; } private static final class UpdateUrlsImpl implements UpdateUrls { private final String myCheckingUrl; private final String myPatchesUrl; private UpdateUrlsImpl(@NotNull XmlElement element) { myCheckingUrl = element.getAttributeValue("check"); myPatchesUrl = element.getAttributeValue("patches"); } @Override public String getCheckingUrl() { return myCheckingUrl; } @Override public String getPatchesUrl() { return myPatchesUrl; } } /** @deprecated Use {@link ApplicationManagerEx#isInStressTest} */ @Deprecated public static boolean isInStressTest() { return ApplicationManagerEx.isInStressTest(); } }
apache-2.0
gAmUssA/hazelcast-simulator
simulator/src/main/java/com/hazelcast/simulator/protocol/connector/AgentConnector.java
2220
package com.hazelcast.simulator.protocol.connector; import com.hazelcast.simulator.protocol.configuration.AgentServerConfiguration; import com.hazelcast.simulator.protocol.core.SimulatorAddress; import com.hazelcast.simulator.protocol.processors.AgentOperationProcessor; import static com.hazelcast.simulator.protocol.core.AddressLevel.AGENT; /** * Connector which listens for incoming Simulator Coordinator connections and connects to remote Simulator Worker instances. */ public class AgentConnector { private final AgentServerConfiguration configuration; private final ServerConnector server; /** * Creates an {@link AgentConnector}. * * @param addressIndex the index of this Simulator Agent * @param port the port for incoming connections */ public AgentConnector(int addressIndex, int port) { SimulatorAddress localAddress = new SimulatorAddress(AGENT, addressIndex, 0, 0); AgentOperationProcessor processor = new AgentOperationProcessor(); this.configuration = new AgentServerConfiguration(localAddress, addressIndex, port, processor); this.server = new ServerConnector(configuration); } /** * Starts to listen on the incoming port. */ public void start() { server.start(); } /** * Stops to listen on the incoming port. */ public void shutdown() { server.shutdown(); } /** * Adds a Simulator Worker and connects to it. * * @param workerIndex the index of the Simulator Worker * @param remoteHost the host of the Simulator Worker * @param remotePort the port of the Simulator Worker */ public void addWorker(int workerIndex, String remoteHost, int remotePort) { // TODO: spawn Simulator Worker instance ClientConnector client = new ClientConnector(workerIndex, remoteHost, remotePort); client.start(); configuration.addWorker(workerIndex, client); } /** * Removes a Simulator Worker. * * @param workerIndex the index of the remote Simulator Worker */ public void removeWorker(int workerIndex) { configuration.removeWorker(workerIndex); } }
apache-2.0
ajaxx/tsql2pgsql
src/grammar/TSQLVisitor.cs
54887
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // ANTLR Version: 4.3 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generated from C:\src\tsql2pgsql\grammar\TSQL.g4 by ANTLR 4.3 // Unreachable code detected #pragma warning disable 0162 // The variable '...' is assigned but its value is never used #pragma warning disable 0219 // Missing XML comment for publicly visible type or member '...' #pragma warning disable 1591 namespace tsql2pgsql.grammar { using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using IToken = Antlr4.Runtime.IToken; /// <summary> /// This interface defines a complete generic visitor for a parse tree produced /// by <see cref="TSQLParser"/>. /// </summary> /// <typeparam name="Result">The return type of the visit operation.</typeparam> [System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.3")] [System.CLSCompliant(false)] public interface ITSQLVisitor<Result> : IParseTreeVisitor<Result> { /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.dml"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDml([NotNull] TSQLParser.DmlContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.xmlWithOption"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitXmlWithOption([NotNull] TSQLParser.XmlWithOptionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterTableDropConstraint"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterTableDropConstraint([NotNull] TSQLParser.AlterTableDropConstraintContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.convertExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitConvertExpression([NotNull] TSQLParser.ConvertExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.selectVariableAssignment"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSelectVariableAssignment([NotNull] TSQLParser.SelectVariableAssignmentContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.integerType"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitIntegerType([NotNull] TSQLParser.IntegerTypeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.rollbackTransaction"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitRollbackTransaction([NotNull] TSQLParser.RollbackTransactionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.propertyOrField"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitPropertyOrField([NotNull] TSQLParser.PropertyOrFieldContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.columnDefinition"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitColumnDefinition([NotNull] TSQLParser.ColumnDefinitionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.type"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitType([NotNull] TSQLParser.TypeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.cursorFetch"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCursorFetch([NotNull] TSQLParser.CursorFetchContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterIndex"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterIndex([NotNull] TSQLParser.AlterIndexContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.cursorDeallocate"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCursorDeallocate([NotNull] TSQLParser.CursorDeallocateContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.obscureCommands"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitObscureCommands([NotNull] TSQLParser.ObscureCommandsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.columnAlias"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitColumnAlias([NotNull] TSQLParser.ColumnAliasContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.dropIndex"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDropIndex([NotNull] TSQLParser.DropIndexContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.insertPreamble"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitInsertPreamble([NotNull] TSQLParser.InsertPreambleContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.transactionIsolationLevel"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTransactionIsolationLevel([NotNull] TSQLParser.TransactionIsolationLevelContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.argumentList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitArgumentList([NotNull] TSQLParser.ArgumentListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.createStatistics"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCreateStatistics([NotNull] TSQLParser.CreateStatisticsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.stringExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitStringExpression([NotNull] TSQLParser.StringExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.setVariableAssignment"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSetVariableAssignment([NotNull] TSQLParser.SetVariableAssignmentContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.dropProcedure"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDropProcedure([NotNull] TSQLParser.DropProcedureContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.unaryExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitUnaryExpression([NotNull] TSQLParser.UnaryExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.orderByClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitOrderByClause([NotNull] TSQLParser.OrderByClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.updateTop"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitUpdateTop([NotNull] TSQLParser.UpdateTopContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.escapedKeyword"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitEscapedKeyword([NotNull] TSQLParser.EscapedKeywordContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.selectListElement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSelectListElement([NotNull] TSQLParser.SelectListElementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.procedureOptions"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitProcedureOptions([NotNull] TSQLParser.ProcedureOptionsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.qualifiedColumnName"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitQualifiedColumnName([NotNull] TSQLParser.QualifiedColumnNameContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.procedureParameter"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitProcedureParameter([NotNull] TSQLParser.ProcedureParameterContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.minSelectElement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitMinSelectElement([NotNull] TSQLParser.MinSelectElementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.executeArgumentList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExecuteArgumentList([NotNull] TSQLParser.ExecuteArgumentListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.orderedIndexColumn"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitOrderedIndexColumn([NotNull] TSQLParser.OrderedIndexColumnContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.insertDataSource"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitInsertDataSource([NotNull] TSQLParser.InsertDataSourceContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.xmlDefinition"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitXmlDefinition([NotNull] TSQLParser.XmlDefinitionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.columnIndexOrName"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitColumnIndexOrName([NotNull] TSQLParser.ColumnIndexOrNameContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.likeTestExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitLikeTestExpression([NotNull] TSQLParser.LikeTestExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.embeddedParameter"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitEmbeddedParameter([NotNull] TSQLParser.EmbeddedParameterContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.insertStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitInsertStatement([NotNull] TSQLParser.InsertStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.deleteTop"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDeleteTop([NotNull] TSQLParser.DeleteTopContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.qualifiedNamePart"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitQualifiedNamePart([NotNull] TSQLParser.QualifiedNamePartContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.commitTransaction"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCommitTransaction([NotNull] TSQLParser.CommitTransactionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.compileUnit"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCompileUnit([NotNull] TSQLParser.CompileUnitContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.updateStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitUpdateStatement([NotNull] TSQLParser.UpdateStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.functionCall"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitFunctionCall([NotNull] TSQLParser.FunctionCallContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.equalityExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitEqualityExpression([NotNull] TSQLParser.EqualityExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.intoClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitIntoClause([NotNull] TSQLParser.IntoClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.procedureParameters"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitProcedureParameters([NotNull] TSQLParser.ProcedureParametersContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.forXmlClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitForXmlClause([NotNull] TSQLParser.ForXmlClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterTableAddConstraint"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterTableAddConstraint([NotNull] TSQLParser.AlterTableAddConstraintContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.primary"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitPrimary([NotNull] TSQLParser.PrimaryContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.qualifiedColumnNameList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitQualifiedColumnNameList([NotNull] TSQLParser.QualifiedColumnNameListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.additiveExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAdditiveExpression([NotNull] TSQLParser.AdditiveExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.relationalExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitRelationalExpression([NotNull] TSQLParser.RelationalExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableTargetOptions"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableTargetOptions([NotNull] TSQLParser.TableTargetOptionsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.procedureParameterInitialValue"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitProcedureParameterInitialValue([NotNull] TSQLParser.ProcedureParameterInitialValueContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.characterStringType"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCharacterStringType([NotNull] TSQLParser.CharacterStringTypeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.mergeNotMatched"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitMergeNotMatched([NotNull] TSQLParser.MergeNotMatchedContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tryBlock"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTryBlock([NotNull] TSQLParser.TryBlockContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.cursorId"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCursorId([NotNull] TSQLParser.CursorIdContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableTargetWithOptions"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableTargetWithOptions([NotNull] TSQLParser.TableTargetWithOptionsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.deleteStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDeleteStatement([NotNull] TSQLParser.DeleteStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.createProcedure"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCreateProcedure([NotNull] TSQLParser.CreateProcedureContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.identitySpec"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitIdentitySpec([NotNull] TSQLParser.IdentitySpecContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.setStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSetStatement([NotNull] TSQLParser.SetStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.existsExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExistsExpression([NotNull] TSQLParser.ExistsExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.overClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitOverClause([NotNull] TSQLParser.OverClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.moreInnerJoin"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitMoreInnerJoin([NotNull] TSQLParser.MoreInnerJoinContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.basicOptionList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitBasicOptionList([NotNull] TSQLParser.BasicOptionListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.postfixExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitPostfixExpression([NotNull] TSQLParser.PostfixExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.deleteOutput"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDeleteOutput([NotNull] TSQLParser.DeleteOutputContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.havingClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitHavingClause([NotNull] TSQLParser.HavingClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.expression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExpression([NotNull] TSQLParser.ExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.expressionSet"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExpressionSet([NotNull] TSQLParser.ExpressionSetContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.fromClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitFromClause([NotNull] TSQLParser.FromClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.insertOutputClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitInsertOutputClause([NotNull] TSQLParser.InsertOutputClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.printExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitPrintExpression([NotNull] TSQLParser.PrintExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.qualifiedNameList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitQualifiedNameList([NotNull] TSQLParser.QualifiedNameListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.subSelectExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSubSelectExpression([NotNull] TSQLParser.SubSelectExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tempIndex"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTempIndex([NotNull] TSQLParser.TempIndexContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.columnList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitColumnList([NotNull] TSQLParser.ColumnListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.insertValue"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitInsertValue([NotNull] TSQLParser.InsertValueContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.conditionalAndExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitConditionalAndExpression([NotNull] TSQLParser.ConditionalAndExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.multiplicativeExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitMultiplicativeExpression([NotNull] TSQLParser.MultiplicativeExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterTableSwitchPartition"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterTableSwitchPartition([NotNull] TSQLParser.AlterTableSwitchPartitionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.createIndex"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCreateIndex([NotNull] TSQLParser.CreateIndexContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.columnDefinitionList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitColumnDefinitionList([NotNull] TSQLParser.ColumnDefinitionListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.variableDeclaration"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitVariableDeclaration([NotNull] TSQLParser.VariableDeclarationContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.procedureBody"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitProcedureBody([NotNull] TSQLParser.ProcedureBodyContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.partitionName"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitPartitionName([NotNull] TSQLParser.PartitionNameContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.mergeStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitMergeStatement([NotNull] TSQLParser.MergeStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.variableDeclarationAssignment"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitVariableDeclarationAssignment([NotNull] TSQLParser.VariableDeclarationAssignmentContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.updateStatementSetClauseRest"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitUpdateStatementSetClauseRest([NotNull] TSQLParser.UpdateStatementSetClauseRestContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.joinOrApply"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitJoinOrApply([NotNull] TSQLParser.JoinOrApplyContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.orderedIndexColumnList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitOrderedIndexColumnList([NotNull] TSQLParser.OrderedIndexColumnListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.columnName"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitColumnName([NotNull] TSQLParser.ColumnNameContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.executeArgument"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExecuteArgument([NotNull] TSQLParser.ExecuteArgumentContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.argument"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitArgument([NotNull] TSQLParser.ArgumentContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.whereClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitWhereClause([NotNull] TSQLParser.WhereClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.mergeMatched"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitMergeMatched([NotNull] TSQLParser.MergeMatchedContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.partitionIdent"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitPartitionIdent([NotNull] TSQLParser.PartitionIdentContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.assignmentOperator"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAssignmentOperator([NotNull] TSQLParser.AssignmentOperatorContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.dmlOptions"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDmlOptions([NotNull] TSQLParser.DmlOptionsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableSourceWithOptions"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableSourceWithOptions([NotNull] TSQLParser.TableSourceWithOptionsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableAlias"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableAlias([NotNull] TSQLParser.TableAliasContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterPartitionScheme"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterPartitionScheme([NotNull] TSQLParser.AlterPartitionSchemeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.castExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCastExpression([NotNull] TSQLParser.CastExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.stringValue"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitStringValue([NotNull] TSQLParser.StringValueContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.conditionalOrExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitConditionalOrExpression([NotNull] TSQLParser.ConditionalOrExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.characterStringTypeLength"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCharacterStringTypeLength([NotNull] TSQLParser.CharacterStringTypeLengthContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.predicateList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitPredicateList([NotNull] TSQLParser.PredicateListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tempTable"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTempTable([NotNull] TSQLParser.TempTableContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.statementList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitStatementList([NotNull] TSQLParser.StatementListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.groupByClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitGroupByClause([NotNull] TSQLParser.GroupByClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.groupByElement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitGroupByElement([NotNull] TSQLParser.GroupByElementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.createIndexPartition"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCreateIndexPartition([NotNull] TSQLParser.CreateIndexPartitionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.integerValue"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitIntegerValue([NotNull] TSQLParser.IntegerValueContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.selectStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSelectStatement([NotNull] TSQLParser.SelectStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.selectTopLimit"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSelectTopLimit([NotNull] TSQLParser.SelectTopLimitContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.keyword"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitKeyword([NotNull] TSQLParser.KeywordContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.waitFor"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitWaitFor([NotNull] TSQLParser.WaitForContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableTarget"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableTarget([NotNull] TSQLParser.TableTargetContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.deleteFromClauseLoose"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDeleteFromClauseLoose([NotNull] TSQLParser.DeleteFromClauseLooseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.clusterType"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitClusterType([NotNull] TSQLParser.ClusterTypeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.cursorClose"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCursorClose([NotNull] TSQLParser.CursorCloseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.typeInBracket"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTypeInBracket([NotNull] TSQLParser.TypeInBracketContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.inclusiveOrExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitInclusiveOrExpression([NotNull] TSQLParser.InclusiveOrExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.qualifiedName"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitQualifiedName([NotNull] TSQLParser.QualifiedNameContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.xmlDefinitionList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitXmlDefinitionList([NotNull] TSQLParser.XmlDefinitionListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.countExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCountExpression([NotNull] TSQLParser.CountExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.expressionInRest"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExpressionInRest([NotNull] TSQLParser.ExpressionInRestContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.commonTableExpressionAtom"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCommonTableExpressionAtom([NotNull] TSQLParser.CommonTableExpressionAtomContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.collate"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCollate([NotNull] TSQLParser.CollateContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.dmlOption"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDmlOption([NotNull] TSQLParser.DmlOptionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.exclusiveOrExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExclusiveOrExpression([NotNull] TSQLParser.ExclusiveOrExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.caseElse"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCaseElse([NotNull] TSQLParser.CaseElseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.procedureParameterName"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitProcedureParameterName([NotNull] TSQLParser.ProcedureParameterNameContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.raiseError"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitRaiseError([NotNull] TSQLParser.RaiseErrorContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.computeStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitComputeStatement([NotNull] TSQLParser.ComputeStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterTableTrigger"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterTableTrigger([NotNull] TSQLParser.AlterTableTriggerContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableDeclarationOptions"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableDeclarationOptions([NotNull] TSQLParser.TableDeclarationOptionsContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterTable"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterTable([NotNull] TSQLParser.AlterTableContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.literalValue"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitLiteralValue([NotNull] TSQLParser.LiteralValueContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.createTable"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCreateTable([NotNull] TSQLParser.CreateTableContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.declareStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDeclareStatement([NotNull] TSQLParser.DeclareStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.caseWhen"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCaseWhen([NotNull] TSQLParser.CaseWhenContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.insertValueList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitInsertValueList([NotNull] TSQLParser.InsertValueListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.unaryExpressionNotPlusMinus"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitUnaryExpressionNotPlusMinus([NotNull] TSQLParser.UnaryExpressionNotPlusMinusContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.andExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAndExpression([NotNull] TSQLParser.AndExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.identityType"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitIdentityType([NotNull] TSQLParser.IdentityTypeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.alterPartitionFunction"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitAlterPartitionFunction([NotNull] TSQLParser.AlterPartitionFunctionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.caseExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCaseExpression([NotNull] TSQLParser.CaseExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.statement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitStatement([NotNull] TSQLParser.StatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.truncateTable"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTruncateTable([NotNull] TSQLParser.TruncateTableContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.setSessionParameter"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSetSessionParameter([NotNull] TSQLParser.SetSessionParameterContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.cursorStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCursorStatement([NotNull] TSQLParser.CursorStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.dropTable"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDropTable([NotNull] TSQLParser.DropTableContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.commonTableExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCommonTableExpression([NotNull] TSQLParser.CommonTableExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.selectStatementPart"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSelectStatementPart([NotNull] TSQLParser.SelectStatementPartContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.functionName"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitFunctionName([NotNull] TSQLParser.FunctionNameContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.conditionalExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitConditionalExpression([NotNull] TSQLParser.ConditionalExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableDeclarationOption"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableDeclarationOption([NotNull] TSQLParser.TableDeclarationOptionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.ifStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitIfStatement([NotNull] TSQLParser.IfStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.ddl"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDdl([NotNull] TSQLParser.DdlContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.setSessionOther"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSetSessionOther([NotNull] TSQLParser.SetSessionOtherContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.whileStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitWhileStatement([NotNull] TSQLParser.WhileStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.deleteFromClause"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitDeleteFromClause([NotNull] TSQLParser.DeleteFromClauseContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.setVariableToCursor"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSetVariableToCursor([NotNull] TSQLParser.SetVariableToCursorContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.basicOption"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitBasicOption([NotNull] TSQLParser.BasicOptionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.createIndexIncludeList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCreateIndexIncludeList([NotNull] TSQLParser.CreateIndexIncludeListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.selectList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitSelectList([NotNull] TSQLParser.SelectListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.orderByElement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitOrderByElement([NotNull] TSQLParser.OrderByElementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.embeddedParameterList"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitEmbeddedParameterList([NotNull] TSQLParser.EmbeddedParameterListContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.transactionBlock"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTransactionBlock([NotNull] TSQLParser.TransactionBlockContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.cursorOpen"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitCursorOpen([NotNull] TSQLParser.CursorOpenContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.joinType"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitJoinType([NotNull] TSQLParser.JoinTypeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.variable"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitVariable([NotNull] TSQLParser.VariableContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableSource"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableSource([NotNull] TSQLParser.TableSourceContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.numericType"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitNumericType([NotNull] TSQLParser.NumericTypeContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.returnExpression"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitReturnExpression([NotNull] TSQLParser.ReturnExpressionContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.executeStatement"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitExecuteStatement([NotNull] TSQLParser.ExecuteStatementContext context); /// <summary> /// Visit a parse tree produced by <see cref="TSQLParser.tableSourceOptions"/>. /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> Result VisitTableSourceOptions([NotNull] TSQLParser.TableSourceOptionsContext context); } } // namespace tsql2pgsql.grammar
apache-2.0
Owldream/Ginseng
include/ginseng/3rd-party/boost/beast/core/file_stdio.hpp
3718
// // Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_CORE_FILE_STDIO_HPP #define BOOST_BEAST_CORE_FILE_STDIO_HPP #include <boost/beast/core/detail/config.hpp> #include <boost/beast/core/error.hpp> #include <boost/beast/core/file_base.hpp> #include <cstdio> #include <cstdint> namespace boost { namespace beast { /** An implementation of File which uses cstdio. This class implements a file using the interfaces present in the C++ Standard Library, in `<stdio>`. */ class file_stdio { FILE* f_ = nullptr; public: /** The type of the underlying file handle. This is platform-specific. */ using native_handle_type = FILE*; /** Destructor If the file is open it is first closed. */ ~file_stdio(); /** Constructor There is no open file initially. */ file_stdio() = default; /** Constructor The moved-from object behaves as if default constructed. */ file_stdio(file_stdio&& other); /** Assignment The moved-from object behaves as if default constructed. */ file_stdio& operator=(file_stdio&& other); /// Returns the native handle associated with the file. FILE* native_handle() const { return f_; } /** Set the native handle associated with the file. If the file is open it is first closed. @param f The native file handle to assign. */ void native_handle(FILE* f); /// Returns `true` if the file is open bool is_open() const { return f_ != nullptr; } /** Close the file if open @param ec Set to the error, if any occurred. */ void close(error_code& ec); /** Open a file at the given path with the specified mode @param path The utf-8 encoded path to the file @param mode The file mode to use @param ec Set to the error, if any occurred */ void open(char const* path, file_mode mode, error_code& ec); /** Return the size of the open file @param ec Set to the error, if any occurred @return The size in bytes */ std::uint64_t size(error_code& ec) const; /** Return the current position in the open file @param ec Set to the error, if any occurred @return The offset in bytes from the beginning of the file */ std::uint64_t pos(error_code& ec) const; /** Adjust the current position in the open file @param offset The offset in bytes from the beginning of the file @param ec Set to the error, if any occurred */ void seek(std::uint64_t offset, error_code& ec); /** Read from the open file @param buffer The buffer for storing the result of the read @param n The number of bytes to read @param ec Set to the error, if any occurred */ std::size_t read(void* buffer, std::size_t n, error_code& ec) const; /** Write to the open file @param buffer The buffer holding the data to write @param n The number of bytes to write @param ec Set to the error, if any occurred */ std::size_t write(void const* buffer, std::size_t n, error_code& ec); }; } // beast } // boost #include <boost/beast/core/impl/file_stdio.ipp> #endif
apache-2.0
tanvirshuvo/spring-social-samples
spring-social-showcase-implicit/src/main/java/org/springframework/social/showcase/config/Application.java
566
package org.springframework.social.showcase.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages="org.springframework.social.showcase") @EnableConfigurationProperties @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
apache-2.0
smallyear/linuxLearn
salt/salt/modules/dracr.py
43541
# -*- coding: utf-8 -*- ''' Manage Dell DRAC. .. versionadded:: 2015.8.2 ''' # pylint: disable=W0141 # Import python libs from __future__ import absolute_import import logging import os import re # Import Salt libs from salt.exceptions import CommandExecutionError import salt.utils # Import 3rd-party libs import salt.ext.six as six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext.six.moves import map log = logging.getLogger(__name__) __proxyenabled__ = ['fx2'] try: run_all = __salt__['cmd.run_all'] except NameError: import salt.modules.cmdmod __salt__ = { 'cmd.run_all': salt.modules.cmdmod._run_all_quiet } def __virtual__(): if salt.utils.which('racadm'): return True return False def __parse_drac(output): ''' Parse Dell DRAC output ''' drac = {} section = '' for i in output.splitlines(): if i.strip().endswith(':') and '=' not in i: section = i[0:-1] drac[section] = {} if len(i.rstrip()) > 0 and '=' in i: if section in drac: drac[section].update(dict( [[prop.strip() for prop in i.split('=')]] )) else: section = i.strip() if section not in drac and section: drac[section] = {} return drac def __execute_cmd(command, host=None, admin_username=None, admin_password=None, module=None): ''' Execute rac commands ''' if module: # -a takes 'server' or 'switch' to represent all servers # or all switches in a chassis. Allow # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH' if module.startswith('ALL_'): modswitch = '-a '\ + module[module.index('_') + 1:len(module)].lower() else: modswitch = '-m {0}'.format(module) else: modswitch = '' if not host: # This is a local call cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command, modswitch)) else: cmd = __salt__['cmd.run_all']( 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host, admin_username, admin_password, command, modswitch), output_loglevel='quiet') if cmd['retcode'] != 0: log.warning('racadm return an exit code \'{0}\'.' .format(cmd['retcode'])) return False return True def __execute_ret(command, host=None, admin_username=None, admin_password=None, module=None): ''' Execute rac commands ''' if module: if module == 'ALL': modswitch = '-a ' else: modswitch = '-m {0}'.format(module) else: modswitch = '' if not host: # This is a local call cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command, modswitch)) else: cmd = __salt__['cmd.run_all']( 'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host, admin_username, admin_password, command, modswitch), output_loglevel='quiet') if cmd['retcode'] != 0: log.warning('racadm return an exit code \'{0}\'.' .format(cmd['retcode'])) else: fmtlines = [] for l in cmd['stdout'].splitlines(): if l.startswith('Security Alert'): continue if l.startswith('RAC1168:'): break if l.startswith('RAC1169:'): break if l.startswith('Continuing execution'): continue if len(l.strip()) == 0: continue fmtlines.append(l) if '=' in l: continue cmd['stdout'] = '\n'.join(fmtlines) return cmd def get_dns_dracname(host=None, admin_username=None, admin_password=None): ret = __execute_ret('get iDRAC.NIC.DNSRacName', host=host, admin_username=admin_username, admin_password=admin_password) parsed = __parse_drac(ret['stdout']) return parsed def set_dns_dracname(name, host=None, admin_username=None, admin_password=None): ret = __execute_ret('set iDRAC.NIC.DNSRacName {0}'.format(name), host=host, admin_username=admin_username, admin_password=admin_password) return ret def system_info(host=None, admin_username=None, admin_password=None, module=None): ''' Return System information CLI Example: .. code-block:: bash salt dell dracr.system_info ''' cmd = __execute_ret('getsysinfo', host=host, admin_username=admin_username, admin_password=admin_password, module=module) if cmd['retcode'] != 0: log.warning('racadm return an exit code \'{0}\'.' .format(cmd['retcode'])) return cmd return __parse_drac(cmd['stdout']) def set_niccfg(ip=None, netmask=None, gateway=None, dhcp=False, host=None, admin_username=None, admin_password=None, module=None): cmdstr = 'setniccfg ' if dhcp: cmdstr += '-d ' else: cmdstr += '-s ' + ip + ' ' + netmask + ' ' + gateway return __execute_cmd(cmdstr, host=host, admin_username=admin_username, admin_password=admin_password, module=module) def set_nicvlan(vlan=None, host=None, admin_username=None, admin_password=None, module=None): cmdstr = 'setniccfg -v ' if vlan: cmdstr += vlan ret = __execute_cmd(cmdstr, host=host, admin_username=admin_username, admin_password=admin_password, module=module) return ret def network_info(host=None, admin_username=None, admin_password=None, module=None): ''' Return Network Configuration CLI Example: .. code-block:: bash salt dell dracr.network_info ''' inv = inventory(host=host, admin_username=admin_username, admin_password=admin_password) if inv is None: cmd = {} cmd['retcode'] = -1 cmd['stdout'] = 'Problem getting switch inventory' return cmd if module not in inv.get('switch') and module not in inv.get('server'): cmd = {} cmd['retcode'] = -1 cmd['stdout'] = 'No module {0} found.'.format(module) return cmd cmd = __execute_ret('getniccfg', host=host, admin_username=admin_username, admin_password=admin_password, module=module) if cmd['retcode'] != 0: log.warning('racadm return an exit code \'{0}\'.' .format(cmd['retcode'])) cmd['stdout'] = 'Network:\n' + 'Device = ' + module + '\n' + \ cmd['stdout'] return __parse_drac(cmd['stdout']) def nameservers(ns, host=None, admin_username=None, admin_password=None, module=None): ''' Configure the nameservers on the DRAC CLI Example: .. code-block:: bash salt dell dracr.nameservers [NAMESERVERS] salt dell dracr.nameservers ns1.example.com ns2.example.com admin_username=root admin_password=calvin module=server-1 host=192.168.1.1 ''' if len(ns) > 2: log.warning('racadm only supports two nameservers') return False for i in range(1, len(ns) + 1): if not __execute_cmd('config -g cfgLanNetworking -o ' 'cfgDNSServer{0} {1}'.format(i, ns[i - 1]), host=host, admin_username=admin_username, admin_password=admin_password, module=module): return False return True def syslog(server, enable=True, host=None, admin_username=None, admin_password=None, module=None): ''' Configure syslog remote logging, by default syslog will automatically be enabled if a server is specified. However, if you want to disable syslog you will need to specify a server followed by False CLI Example: .. code-block:: bash salt dell dracr.syslog [SYSLOG IP] [ENABLE/DISABLE] salt dell dracr.syslog 0.0.0.0 False ''' if enable and __execute_cmd('config -g cfgRemoteHosts -o ' 'cfgRhostsSyslogEnable 1', host=host, admin_username=admin_username, admin_password=admin_password, module=None): return __execute_cmd('config -g cfgRemoteHosts -o ' 'cfgRhostsSyslogServer1 {0}'.format(server), host=host, admin_username=admin_username, admin_password=admin_password, module=module) return __execute_cmd('config -g cfgRemoteHosts -o cfgRhostsSyslogEnable 0', host=host, admin_username=admin_username, admin_password=admin_password, module=module) def email_alerts(action, host=None, admin_username=None, admin_password=None): ''' Enable/Disable email alerts CLI Example: .. code-block:: bash salt dell dracr.email_alerts True salt dell dracr.email_alerts False ''' if action: return __execute_cmd('config -g cfgEmailAlert -o ' 'cfgEmailAlertEnable -i 1 1', host=host, admin_username=admin_username, admin_password=admin_password) else: return __execute_cmd('config -g cfgEmailAlert -o ' 'cfgEmailAlertEnable -i 1 0') def list_users(host=None, admin_username=None, admin_password=None, module=None): ''' List all DRAC users CLI Example: .. code-block:: bash salt dell dracr.list_users ''' users = {} _username = '' for idx in range(1, 17): cmd = __execute_ret('getconfig -g ' 'cfgUserAdmin -i {0}'.format(idx), host=host, admin_username=admin_username, admin_password=admin_password) if cmd['retcode'] != 0: log.warning('racadm return an exit code \'{0}\'.' .format(cmd['retcode'])) for user in cmd['stdout'].splitlines(): if not user.startswith('cfg'): continue (key, val) = user.split('=') if key.startswith('cfgUserAdminUserName'): _username = val.strip() if val: users[_username] = {'index': idx} else: break else: if len(_username) > 0: users[_username].update({key: val}) return users def delete_user(username, uid=None, host=None, admin_username=None, admin_password=None): ''' Delete a user CLI Example: .. code-block:: bash salt dell dracr.delete_user [USERNAME] [UID - optional] salt dell dracr.delete_user diana 4 ''' if uid is None: user = list_users() uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o ' 'cfgUserAdminUserName -i {0} ""'.format(uid), host=host, admin_username=admin_username, admin_password=admin_password) else: log.warning('\'{0}\' does not exist'.format(username)) return False def change_password(username, password, uid=None, host=None, admin_username=None, admin_password=None, module=None): ''' Change user's password CLI Example: .. code-block:: bash salt dell dracr.change_password [USERNAME] [PASSWORD] uid=[OPTIONAL] host=<remote DRAC> admin_username=<DRAC user> admin_password=<DRAC PW> salt dell dracr.change_password diana secret Note that if only a username is specified then this module will look up details for all 16 possible DRAC users. This is time consuming, but might be necessary if one is not sure which user slot contains the one you want. Many late-model Dell chassis have 'root' as UID 1, so if you can depend on that then setting the password is much quicker. Raises an error if the supplied password is greater than 20 chars. ''' if len(password) > 20: raise CommandExecutionError('Supplied password should be 20 characters or less') if uid is None: user = list_users(host=host, admin_username=admin_username, admin_password=admin_password, module=module) uid = user[username]['index'] if uid: return __execute_cmd('config -g cfgUserAdmin -o ' 'cfgUserAdminPassword -i {0} {1}' .format(uid, password), host=host, admin_username=admin_username, admin_password=admin_password, module=module) else: log.warning('\'{0}\' does not exist'.format(username)) return False def deploy_password(username, password, host=None, admin_username=None, admin_password=None, module=None): ''' Change the QuickDeploy password, used for switches as well CLI Example: .. code-block:: bash salt dell dracr.deploy_password [USERNAME] [PASSWORD] host=<remote DRAC> admin_username=<DRAC user> admin_password=<DRAC PW> salt dell dracr.change_password diana secret Note that if only a username is specified then this module will look up details for all 16 possible DRAC users. This is time consuming, but might be necessary if one is not sure which user slot contains the one you want. Many late-model Dell chassis have 'root' as UID 1, so if you can depend on that then setting the password is much quicker. ''' return __execute_cmd('deploy -u {0} -p {1}'.format( username, password), host=host, admin_username=admin_username, admin_password=admin_password, module=module ) def deploy_snmp(snmp, host=None, admin_username=None, admin_password=None, module=None): ''' Change the QuickDeploy SNMP community string, used for switches as well CLI Example: .. code-block:: bash salt dell dracr.deploy_snmp SNMP_STRING host=<remote DRAC or CMC> admin_username=<DRAC user> admin_password=<DRAC PW> salt dell dracr.deploy_password diana secret ''' return __execute_cmd('deploy -v SNMPv2 {0} ro'.format(snmp), host=host, admin_username=admin_username, admin_password=admin_password, module=module) def create_user(username, password, permissions, users=None, host=None, admin_username=None, admin_password=None): ''' Create user accounts CLI Example: .. code-block:: bash salt dell dracr.create_user [USERNAME] [PASSWORD] [PRIVELEGES] salt dell dracr.create_user diana secret login,test_alerts,clear_logs DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands ''' _uids = set() if users is None: users = list_users() if username in users: log.warning('\'{0}\' already exists'.format(username)) return False for idx in six.iterkeys(users): _uids.add(users[idx]['index']) uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop() # Create user account first if not __execute_cmd('config -g cfgUserAdmin -o ' 'cfgUserAdminUserName -i {0} {1}' .format(uid, username), host=host, admin_username=admin_username, admin_password=admin_password): delete_user(username, uid) return False # Configure users permissions if not set_permissions(username, permissions, uid): log.warning('unable to set user permissions') delete_user(username, uid) return False # Configure users password if not change_password(username, password, uid): log.warning('unable to set user password') delete_user(username, uid) return False # Enable users admin if not __execute_cmd('config -g cfgUserAdmin -o ' 'cfgUserAdminEnable -i {0} 1'.format(uid)): delete_user(username, uid) return False return True def set_permissions(username, permissions, uid=None, host=None, admin_username=None, admin_password=None): ''' Configure users permissions CLI Example: .. code-block:: bash salt dell dracr.set_permissions [USERNAME] [PRIVELEGES] [USER INDEX - optional] salt dell dracr.set_permissions diana login,test_alerts,clear_logs 4 DRAC Privileges * login : Login to iDRAC * drac : Configure iDRAC * user_management : Configure Users * clear_logs : Clear Logs * server_control_commands : Execute Server Control Commands * console_redirection : Access Console Redirection * virtual_media : Access Virtual Media * test_alerts : Test Alerts * debug_commands : Execute Debug Commands ''' privileges = {'login': '0x0000001', 'drac': '0x0000002', 'user_management': '0x0000004', 'clear_logs': '0x0000008', 'server_control_commands': '0x0000010', 'console_redirection': '0x0000020', 'virtual_media': '0x0000040', 'test_alerts': '0x0000080', 'debug_commands': '0x0000100'} permission = 0 # When users don't provide a user ID we need to search for this if uid is None: user = list_users() uid = user[username]['index'] # Generate privilege bit mask for i in permissions.split(','): perm = i.strip() if perm in privileges: permission += int(privileges[perm], 16) return __execute_cmd('config -g cfgUserAdmin -o ' 'cfgUserAdminPrivilege -i {0} 0x{1:08X}' .format(uid, permission), host=host, admin_username=admin_username, admin_password=admin_password) def set_snmp(community, host=None, admin_username=None, admin_password=None): ''' Configure CMC or individual iDRAC SNMP community string. Use ``deploy_snmp`` for configuring chassis switch SNMP. CLI Example: .. code-block:: bash salt dell dracr.set_snmp [COMMUNITY] salt dell dracr.set_snmp public ''' return __execute_cmd('config -g cfgOobSnmp -o ' 'cfgOobSnmpAgentCommunity {0}'.format(community), host=host, admin_username=admin_username, admin_password=admin_password) def set_network(ip, netmask, gateway, host=None, admin_username=None, admin_password=None): ''' Configure Network on the CMC or individual iDRAC. Use ``set_niccfg`` for blade and switch addresses. CLI Example: .. code-block:: bash salt dell dracr.set_network [DRAC IP] [NETMASK] [GATEWAY] salt dell dracr.set_network 192.168.0.2 255.255.255.0 192.168.0.1 admin_username=root admin_password=calvin host=192.168.1.1 ''' return __execute_cmd('setniccfg -s {0} {1} {2}'.format( ip, netmask, gateway, host=host, admin_username=admin_username, admin_password=admin_password )) def server_power(status, host=None, admin_username=None, admin_password=None, module=None): ''' status One of 'powerup', 'powerdown', 'powercycle', 'hardreset', 'graceshutdown' host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to reboot on the chassis such as a blade. If not provided, the chassis will be rebooted. CLI Example: .. code-block:: bash salt dell dracr.server_reboot salt dell dracr.server_reboot module=server-1 ''' return __execute_cmd('serveraction {0}'.format(status), host=host, admin_username=admin_username, admin_password=admin_password, module=module) def server_reboot(host=None, admin_username=None, admin_password=None, module=None): ''' Issues a power-cycle operation on the managed server. This action is similar to pressing the power button on the system's front panel to power down and then power up the system. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to reboot on the chassis such as a blade. If not provided, the chassis will be rebooted. CLI Example: .. code-block:: bash salt dell dracr.server_reboot salt dell dracr.server_reboot module=server-1 ''' return __execute_cmd('serveraction powercycle', host=host, admin_username=admin_username, admin_password=admin_password, module=module) def server_poweroff(host=None, admin_username=None, admin_password=None, module=None): ''' Powers down the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to power off on the chassis such as a blade. If not provided, the chassis will be powered off. CLI Example: .. code-block:: bash salt dell dracr.server_poweroff salt dell dracr.server_poweroff module=server-1 ''' return __execute_cmd('serveraction powerdown', host=host, admin_username=admin_username, admin_password=admin_password, module=module) def server_poweron(host=None, admin_username=None, admin_password=None, module=None): ''' Powers up the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to power on located on the chassis such as a blade. If not provided, the chassis will be powered on. CLI Example: .. code-block:: bash salt dell dracr.server_poweron salt dell dracr.server_poweron module=server-1 ''' return __execute_cmd('serveraction powerup', host=host, admin_username=admin_username, admin_password=admin_password, module=module) def server_hardreset(host=None, admin_username=None, admin_password=None, module=None): ''' Performs a reset (reboot) operation on the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. module The element to hard reset on the chassis such as a blade. If not provided, the chassis will be reset. CLI Example: .. code-block:: bash salt dell dracr.server_hardreset salt dell dracr.server_hardreset module=server-1 ''' return __execute_cmd('serveraction hardreset', host=host, admin_username=admin_username, admin_password=admin_password, module=module) def server_powerstatus(host=None, admin_username=None, admin_password=None, module=None): ''' return the power status for the passed module CLI Example: .. code-block:: bash salt dell drac.server_powerstatus ''' ret = __execute_ret('serveraction powerstatus', host=host, admin_username=admin_username, admin_password=admin_password, module=module) result = {'retcode': 0} if ret['stdout'] == 'ON': result['status'] = True result['comment'] = 'Power is on' if ret['stdout'] == 'OFF': result['status'] = False result['comment'] = 'Power is on' if ret['stdout'].startswith('ERROR'): result['status'] = False result['comment'] = ret['stdout'] return result def server_pxe(host=None, admin_username=None, admin_password=None): ''' Configure server to PXE perform a one off PXE boot CLI Example: .. code-block:: bash salt dell dracr.server_pxe ''' if __execute_cmd('config -g cfgServerInfo -o cfgServerFirstBootDevice PXE', host=host, admin_username=admin_username, admin_password=admin_password): if __execute_cmd('config -g cfgServerInfo -o cfgServerBootOnce 1', host=host, admin_username=admin_username, admin_password=admin_password): return server_reboot else: log.warning('failed to set boot order') return False log.warning('failed to to configure PXE boot') return False def list_slotnames(host=None, admin_username=None, admin_password=None): ''' List the names of all slots in the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt-call --local dracr.list_slotnames host=111.222.333.444 admin_username=root admin_password=secret ''' slotraw = __execute_ret('getslotname', host=host, admin_username=admin_username, admin_password=admin_password) if slotraw['retcode'] != 0: return slotraw slots = {} stripheader = True for l in slotraw['stdout'].splitlines(): if l.startswith('<'): stripheader = False continue if stripheader: continue fields = l.split() slots[fields[0]] = {} slots[fields[0]]['slot'] = fields[0] if len(fields) > 1: slots[fields[0]]['slotname'] = fields[1] else: slots[fields[0]]['slotname'] = '' if len(fields) > 2: slots[fields[0]]['hostname'] = fields[2] else: slots[fields[0]]['hostname'] = '' return slots def get_slotname(slot, host=None, admin_username=None, admin_password=None): ''' Get the name of a slot number in the chassis. slot The number of the slot for which to obtain the name. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt-call --local dracr.get_slotname 0 host=111.222.333.444 admin_username=root admin_password=secret ''' slots = list_slotnames(host=host, admin_username=admin_username, admin_password=admin_password) # The keys for this dictionary are strings, not integers, so convert the # argument to a string slot = str(slot) return slots[slot]['slotname'] def set_slotname(slot, name, host=None, admin_username=None, admin_password=None): ''' Set the name of a slot in a chassis. slot The slot number to change. name The name to set. Can only be 15 characters long. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_slotname 2 my-slotname host=111.222.333.444 admin_username=root admin_password=secret ''' return __execute_cmd('config -g cfgServerInfo -o cfgServerName -i {0} {1}'.format(slot, name), host=host, admin_username=admin_username, admin_password=admin_password) def set_chassis_name(name, host=None, admin_username=None, admin_password=None): ''' Set the name of the chassis. name The name to be set on the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_name my-chassis host=111.222.333.444 admin_username=root admin_password=secret ''' return __execute_cmd('setsysinfo -c chassisname {0}'.format(name), host=host, admin_username=admin_username, admin_password=admin_password) def get_chassis_name(host=None, admin_username=None, admin_password=None): ''' Get the name of a chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.get_chassis_name host=111.222.333.444 admin_username=root admin_password=secret ''' return bare_rac_cmd('getchassisname', host=host, admin_username=admin_username, admin_password=admin_password) def inventory(host=None, admin_username=None, admin_password=None): def mapit(x, y): return {x: y} fields = {} fields['server'] = ['name', 'idrac_version', 'blade_type', 'gen', 'updateable'] fields['switch'] = ['name', 'model_name', 'hw_version', 'fw_version'] fields['cmc'] = ['name', 'cmc_version', 'updateable'] fields['chassis'] = ['name', 'fw_version', 'fqdd'] rawinv = __execute_ret('getversion', host=host, admin_username=admin_username, admin_password=admin_password) if rawinv['retcode'] != 0: return rawinv in_server = False in_switch = False in_cmc = False in_chassis = False ret = {} ret['server'] = {} ret['switch'] = {} ret['cmc'] = {} ret['chassis'] = {} for l in rawinv['stdout'].splitlines(): if l.startswith('<Server>'): in_server = True in_switch = False in_cmc = False in_chassis = False continue if l.startswith('<Switch>'): in_server = False in_switch = True in_cmc = False in_chassis = False continue if l.startswith('<CMC>'): in_server = False in_switch = False in_cmc = True in_chassis = False continue if l.startswith('<Chassis Infrastructure>'): in_server = False in_switch = False in_cmc = False in_chassis = True continue if len(l) < 1: continue line = re.split(' +', l.strip()) if in_server: ret['server'][line[0]] = dict( (k, v) for d in map(mapit, fields['server'], line) for (k, v) in d.items()) if in_switch: ret['switch'][line[0]] = dict( (k, v) for d in map(mapit, fields['switch'], line) for (k, v) in d.items()) if in_cmc: ret['cmc'][line[0]] = dict( (k, v) for d in map(mapit, fields['cmc'], line) for (k, v) in d.items()) if in_chassis: ret['chassis'][line[0]] = dict( (k, v) for d in map(mapit, fields['chassis'], line) for k, v in d.items()) return ret def set_chassis_location(location, host=None, admin_username=None, admin_password=None): ''' Set the location of the chassis. location The name of the location to be set on the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_location location-name host=111.222.333.444 admin_username=root admin_password=secret ''' return __execute_cmd('setsysinfo -c chassislocation {0}'.format(location), host=host, admin_username=admin_username, admin_password=admin_password) def get_chassis_location(host=None, admin_username=None, admin_password=None): ''' Get the location of the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_location host=111.222.333.444 admin_username=root admin_password=secret ''' return system_info(host=host, admin_username=admin_username, admin_password=admin_password)['Chassis Information']['Chassis Location'] def set_chassis_datacenter(location, host=None, admin_username=None, admin_password=None): ''' Set the location of the chassis. location The name of the datacenter to be set on the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_datacenter datacenter-name host=111.222.333.444 admin_username=root admin_password=secret ''' return set_general('cfgLocation', 'cfgLocationDatacenter', location, host=host, admin_username=admin_username, admin_password=admin_password) def get_chassis_datacenter(host=None, admin_username=None, admin_password=None): ''' Get the datacenter of the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block:: bash salt '*' dracr.set_chassis_location host=111.222.333.444 admin_username=root admin_password=secret ''' return get_general('cfgLocation', 'cfgLocationDatacenter', host=host, admin_username=admin_username, admin_password=admin_password) def set_general(cfg_sec, cfg_var, val, host=None, admin_username=None, admin_password=None): return __execute_cmd('config -g {0} -o {1} {2}'.format(cfg_sec, cfg_var, val), host=host, admin_username=admin_username, admin_password=admin_password) def get_general(cfg_sec, cfg_var, host=None, admin_username=None, admin_password=None): ret = __execute_ret('getconfig -g {0} -o {1}'.format(cfg_sec, cfg_var), host=host, admin_username=admin_username, admin_password=admin_password) if ret['retcode'] == 0: return ret['stdout'] else: return ret def idrac_general(blade_name, command, idrac_password=None, host=None, admin_username=None, admin_password=None): ''' Run a generic racadm command against a particular blade in a chassis. Blades are usually named things like 'server-1', 'server-2', etc. If the iDRAC has a different password than the CMC, then you can pass it with the idrac_password kwarg. :param blade_name: Name of the blade to run the command on :param command: Command like to pass to racadm :param idrac_password: Password for the iDRAC if different from the CMC :param host: Chassis hostname :param admin_username: CMC username :param admin_password: CMC password :return: stdout if the retcode is 0, otherwise a standard cmd.run_all dictionary CLI Example: .. code-block:: bash salt fx2 chassis.cmd idrac_general server-1 'get BIOS.SysProfileSettings' ''' module_network = network_info(host, admin_username, admin_password, blade_name) if idrac_password is not None: password = idrac_password else: password = admin_password idrac_ip = module_network['Network']['IP Address'] ret = __execute_ret(command, host=idrac_ip, admin_username='root', admin_password=password) if ret['retcode'] == 0: return ret['stdout'] else: return ret def bare_rac_cmd(cmd, host=None, admin_username=None, admin_password=None): ret = __execute_ret('{0}'.format(cmd), host=host, admin_username=admin_username, admin_password=admin_password) if ret['retcode'] == 0: return ret['stdout'] else: return ret def _update_firmware(cmd, host=None, admin_username=None, admin_password=None): if not admin_username: admin_username = __pillar__['proxy']['admin_username'] if not admin_username: admin_password = __pillar__['proxy']['admin_password'] ret = __execute_ret(cmd, host=host, admin_username=admin_username, admin_password=admin_password) if ret['retcode'] == 0: return ret['stdout'] else: return ret def update_firmware(filename, host=None, admin_username=None, admin_password=None): ''' Updates firmware using local firmware file .. code-block:: bash salt dell dracr.update_firmware firmware.exe This executes the following command on your FX2 (using username and password stored in the pillar data) .. code-block:: bash racadm update –f firmware.exe -u user –p pass ''' if os.path.exists(filename): return _update_firmware('update -f {0}'.format(filename), host=None, admin_username=None, admin_password=None) else: raise CommandExecutionError('Unable to find firmware file {0}' .format(filename)) def update_firmware_nfs_or_cifs(filename, share, host=None, admin_username=None, admin_password=None): ''' Executes the following for CIFS (using username and password stored in the pillar data) .. code-block:: bash racadm update -f <updatefile> -u user –p pass -l //IP-Address/share Or for NFS (using username and password stored in the pillar data) .. code-block:: bash racadm update -f <updatefile> -u user –p pass -l IP-address:/share Salt command for CIFS: .. code-block:: bash salt dell dracr.update_firmware_nfs_or_cifs \ firmware.exe //IP-Address/share Salt command for NFS: .. code-block:: bash salt dell dracr.update_firmware_nfs_or_cifs \ firmware.exe IP-address:/share ''' if os.path.exists(filename): return _update_firmware('update -f {0} -l {1}'.format(filename, share), host=None, admin_username=None, admin_password=None) else: raise CommandExecutionError('Unable to find firmware file {0}' .format(filename)) # def get_idrac_nic()
apache-2.0
langlan/sqldsl
src/main/java/langlan/sql/weaver/c/AbstractSingleValueTestingCriteria.java
1163
package langlan.sql.weaver.c; import langlan.sql.weaver.i.Criteria; /** * For : <br> * =, >, <, >=, <=, <>, <br> * LIKE, IN, BETWEEN, IS NULL, <br> * NOT LIKE, NOT IN, NOT BETWEEN, IS NOT NULL */ public abstract class AbstractSingleValueTestingCriteria extends AbstractCriteria { private String testing; private boolean negative; AbstractSingleValueTestingCriteria(String testing){ this(testing, true); } AbstractSingleValueTestingCriteria(String testing, boolean calcImmediate) { this.testing = testing; if(calcImmediate){ calcExpression(); } } /** Testing part expression */ public String getTesting() { return testing; } /** * flip the flag of "using 'Not' keyword". * @throws IllegalArgumentException if this criteria represents '=, >, <, >=, <=, <>' */ public Criteria negative() throws IllegalArgumentException{ this.negative = !negative; calcExpression(); return this; } abstract protected void calcExpression(); /** * Test if using 'Not' keyword, always <code>false</code> if this criteria represents '=, >, <, >=, <=, <>' * @see #negative */ public boolean isNegative() { return negative; } }
apache-2.0
humbletrader/katechaki
src/test/java/net/sf/reportengine/samples/FirstReportWithGroups.java
3823
/** * Copyright (C) 2006 Dragos Balan (dragos.balan@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package net.sf.reportengine.samples; import java.io.FileWriter; import java.io.IOException; import net.sf.reportengine.ReportBuilder; import net.sf.reportengine.components.FlatTable; import net.sf.reportengine.components.FlatTableBuilder; import net.sf.reportengine.components.ReportTitle; import net.sf.reportengine.config.DefaultDataColumn; import net.sf.reportengine.config.DefaultGroupColumn; import net.sf.reportengine.config.HorizAlign; import net.sf.reportengine.core.calc.GroupCalculators; import net.sf.reportengine.in.TextTableInput; import net.sf.reportengine.out.HtmlReportOutput; /** * The first report containing a group column. The month column is declared as a * group column so after each change of a month a total will be displayed on the * Amount column where the calculator has been added */ public class FirstReportWithGroups { public static void main(String[] args) throws IOException { // constructing a flat table with 3 columns: first is declared as a // group column // the third contains the group calculator (in this case an SUM) FlatTable flatTable = new FlatTableBuilder(new TextTableInput("./input/expenses.csv", ",")).addGroupColumn(new DefaultGroupColumn.Builder(0).header("Month") .horizAlign(HorizAlign.LEFT) .build()) .addDataColumn(new DefaultDataColumn.Builder(1).header("On What?") .build()) .addDataColumn(new DefaultDataColumn.Builder(2).header("Amount") .useCalculator(GroupCalculators.SUM) .horizAlign(HorizAlign.RIGHT) .build()) .build(); // building and executing the report new ReportBuilder(new HtmlReportOutput(new FileWriter("./target/MonthlyExpensesUsingGroups.html"))).add(new ReportTitle("Monthly Expenses")) .add(flatTable) .build() .execute(); } }
apache-2.0
peterbanda/coel
source/Web/src/main/java/edu/tlab/rbnpg/domain/ac/EventsLogger.java
3337
/* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://jersey.dev.java.net/CDDL+GPL.html * or jersey/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at jersey/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package edu.banda.coel.domain.ac; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.atmosphere.cpr.AtmosphereResourceEvent; import org.atmosphere.cpr.AtmosphereResourceEventListener; public class EventsLogger implements AtmosphereResourceEventListener { public EventsLogger() { } public void onSuspend(final AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event){ System.out.println("onSuspend: " + event.getResource().getRequest().getRemoteAddr() + event.getResource().getRequest().getRemotePort()); } public void onResume(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) { System.out.println("onResume: " + event.getResource().getRequest().getRemoteAddr()); } public void onDisconnect(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) { System.out.println("onDisconnect: " + event.getResource().getRequest().getRemoteAddr() + event.getResource().getRequest().getRemotePort()); } public void onBroadcast(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) { System.out.println("onBroadcast: " + event.getMessage()); } public void onThrowable(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) { event.throwable().printStackTrace(System.err); } }
apache-2.0
lessthanoptimal/BoofCV
main/boofcv-ip/src/test/java/boofcv/alg/filter/convolve/normalized/TestConvolveNormalized_JustBorder_IL.java
4471
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.filter.convolve.normalized; import boofcv.core.image.FactoryGImageMultiBand; import boofcv.core.image.GImageMultiBand; import boofcv.struct.image.ImageMultiBand; import boofcv.testing.BoofStandardJUnit; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Peter Abeles */ public class TestConvolveNormalized_JustBorder_IL extends BoofStandardJUnit { @Test void compareToNaive() { CompareToNaive test = new CompareToNaive(); int numFunctions = 20; for( int i = 0; i < 2; i++ ) { test.setImageDimension(15+i,20+i); // convolve with different kernel sizes relative to the skip amount test.setKernelRadius(1,1); test.performTests(numFunctions); test.setKernelRadius(2,2); test.performTests(numFunctions); test.setKernelRadius(3,3); test.performTests(numFunctions); // non symmetric test.setKernelRadius(3,1); test.performTests(numFunctions); test.setKernelRadius(3,4); test.performTests(numFunctions); // NOTE it intentionally can't handle this special case // now try a pathological case where the kernel is larger than the image // test.setKernelRadius(10); // test.performTests(9); } } public static class CompareToNaive extends CompareToStandardConvolutionNormalized { public CompareToNaive() { super(ConvolveNormalized_JustBorder_IL.class); } /** * Just compares the image border against each other. */ @Override protected void compareResults(Object targetResult, Object[] targetParam, Object validationResult, Object[] validationParam) { GImageMultiBand t,v; int borderX0=0,borderX1=0; int borderY0=0,borderY1=0; if( methodTest.getName().contentEquals("convolve")) { t = FactoryGImageMultiBand.wrap((ImageMultiBand) targetParam[2]); v = FactoryGImageMultiBand.wrap((ImageMultiBand) validationParam[2]); borderX0=borderY0 = offset; borderX1=borderY1 = kernelRadius*2-offset; } else if( methodTest.getName().contentEquals("horizontal") ) { t = FactoryGImageMultiBand.wrap((ImageMultiBand) targetParam[2]); v = FactoryGImageMultiBand.wrap((ImageMultiBand) validationParam[2]); borderX0 = offset; borderX1 = kernelRadius*2-offset; } else if( methodTest.getName().contentEquals("vertical")) { if( methodTest.getParameterTypes().length == 3 ) { t = FactoryGImageMultiBand.wrap((ImageMultiBand) targetParam[2]); v = FactoryGImageMultiBand.wrap((ImageMultiBand) validationParam[2]); borderY0 = offset; borderY1 = kernelRadius * 2 - offset; } else { t = FactoryGImageMultiBand.wrap((ImageMultiBand) targetParam[3]); v = FactoryGImageMultiBand.wrap((ImageMultiBand) validationParam[3]); borderX0=borderY0 = offset; borderX1=borderY1 = kernelRadius*2-offset; } } else { throw new RuntimeException("Unknown"); } final int width = t.getWidth(); final int height = t.getHeight(); final float pixelT[] = new float[ t.getNumberOfBands() ]; final float pixelV[] = new float[ t.getNumberOfBands() ]; // System.out.println(" t"); // System.out.println(t.getImage()); // System.out.println(" v"); // System.out.println(v.getImage()); for( int y = 0; y < height; y++ ) { for( int x = 0; x < width; x++ ) { if( x < borderX0 || y < borderY0 || x >= width - borderX1 || y >= height - borderY1 ) { t.get(x,y,pixelT); v.get(x,y,pixelV); for (int band = 0; band < t.getNumberOfBands(); band++) { assertEquals(pixelV[band] , pixelT[band] , 1e-4 , x+" "+y); } } else { t.get(x,y,pixelT); for (int band = 0; band < t.getNumberOfBands(); band++) { assertEquals( 0 , pixelT[band] , 1e-4 , x+" "+y); } } } } } } }
apache-2.0
0pq76r/blog
anemic-vs-rich-domain-model/src/test/java/com/link_intersystems/publications/blog/model/rich/OrderTest.java
1462
package com.link_intersystems.publications.blog.model.rich; import static junit.framework.Assert.assertEquals; import java.math.BigDecimal; import java.util.List; import org.junit.Test; import com.link_intersystems.publications.blog.model.rich.Order; import com.link_intersystems.publications.blog.model.rich.OrderItem; public class OrderTest { /** * This test shows that a rich model gurantees that it is in a legal state * at any time. */ @Test public void anAnemicModelCanBeInconsistent() { Order order = new Order(); BigDecimal total = order.getTotal(); /* * A new order has no items and therefore the total must be zero. */ assertEquals(BigDecimal.ZERO, total); OrderItem aGoodBook = new OrderItem(new BigDecimal("30"), 5, "Domain-Driven"); List<OrderItem> items = order.getItems(); try { items.add(aGoodBook); } catch (UnsupportedOperationException e) { /* * We CAN NOT BREAK ENCAPSULATION, because the order object will not * expose it's internal state to clients. It takes care about it's * state and ensures that it is in a legal state at any time. */ } /* * We have to use the object's mutator method */ order.addItem(aGoodBook); /* * After we added an OrderItem. The object is still in a legal state. */ BigDecimal totalAfterItemAdd = order.getTotal(); BigDecimal expectedTotal = new BigDecimal("150"); assertEquals(expectedTotal, totalAfterItemAdd); } }
apache-2.0
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/DeployConfig.java
10367
package nl.jpoint.vertx.deploy.agent; import io.vertx.core.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; public class DeployConfig { private static final Logger LOG = LoggerFactory.getLogger(AwsDeployApplication.class); private static final String MAVEN_CENTRAL = "https://repo1.maven.org/maven/"; private static final String DEFAULT_SERVICE_CONFIG_LOCATION = "/etc/default/"; private static final String VERTX_HOME = "vertx.home"; private static final String RUN_DIR = "vertx.run"; private static final String ARTIFACT_REPO = "artifact.storage"; private static final String AWS_ENABLED = "aws.enable"; private static final String AWS_REGION = "aws.region"; private static final String AWS_DEFAULT_REGION = "eu-west-1"; private static final String AWS_REGISTER_MAX_DURATION = "aws.as.register.maxduration"; private static final String CONFIG_LOCATION = "config.location"; private static final String SERVICE_CONFIG_LOCATION = "service.config.location"; private static final String HTTP_AUTH_USER = "http.authUser"; private static final String HTTP_PORT = "http.port"; private static final String HTTP_AUTH_PASS = "http.authPass"; private static final String MAVEN_REPO_URI = "maven.repo.uri"; private static final String MAVEN_SNAPSHOT_POLICY = "maven.repo.snapshot.policy"; private static final String CLUSTER = "vertx.clustering"; private static final String DEFAULT_JAVA_OPTS = "vertx.default.java.opts"; private static final String AWS_AS_AUTODISCOVER = "aws.as.autodiscover"; private static final String TYPED_DEPLOY = "typed.deploy"; private static final String POLL_INTERVAL = "aws.poll.interval"; private static final String AUTH_TOKEN = "auth.token"; private static final String AWS_INSTANCE_ID = "aws.elb.instanceid"; private static final String STAT_FILE = ".initial"; private final Path vertxHome; private final Path artifactRepo; private final URI nexusUrl; private String configLocation; private String awsRegion; private Integer httpPort; private String httpAuthUser; private String httpAuthPassword; private boolean awsEnabled = false; private boolean httpAuthentication = false; private boolean mavenRemote = true; private String awsLoadbalancerId; private int awsMaxRegistrationDuration; private String authToken; private boolean asCluster = true; private String remoteRepoPolicy; private String defaultJavaOpts; private String runDir; private String statFile; private boolean typedDeploy = false; private boolean awsAutoDiscover = false; private String serviceConfigLocation; private long pollInterval; private DeployConfig(String vertxHome, String artifactRepo, String nexusUrl) { this.vertxHome = Paths.get(vertxHome); this.artifactRepo = Paths.get(artifactRepo); if (nexusUrl == null || nexusUrl.isEmpty()) { this.mavenRemote = false; this.nexusUrl = null; } else { this.mavenRemote = true; this.nexusUrl = URI.create(nexusUrl); } } private static String validateRequiredField(String field, JsonObject config) { if (!config.containsKey(field) || config.getString(field).isEmpty()) { LOG.error("config missing config value for field {} ", field); throw new IllegalStateException("config missing config value for field " + field); } return (String) config.remove(field); } private static <T> T validateField(String field, JsonObject config) { return validateField(field, config, null); } private static <T> T validateField(String field, JsonObject config, T defaultValue) { if (config.containsKey(field) && config.getValue(field) != null) { return (T) config.remove(field); } return defaultValue; } static DeployConfig fromJsonObject(JsonObject config) { if (config == null) { LOG.error("Unable to read config file"); throw new IllegalStateException("Unable to read config file"); } String vertxHome = validateRequiredField(VERTX_HOME, config); String artifactRepo = validateRequiredField(ARTIFACT_REPO, config); String mavenRepo = validateField(MAVEN_REPO_URI, config, ""); if (mavenRepo.isEmpty()) { LOG.warn("'maven.repo.uri', using maven central"); mavenRepo = MAVEN_CENTRAL; } DeployConfig deployconfig = new DeployConfig(vertxHome, artifactRepo, mavenRepo) .withConfigLocation(config) .withServiceConfigLocation(config) .withHttpPort(config) .withAwsConfig(config) .withHttpAuth(config) .withAuthToken(config) .withCluster(config) .withRunDir(config) .withLoggerFactoryName(config) .withTypedDeploy(config) .withPollInterval(config) .withRemoteRepoUpdatePolicy(config); if (!config.isEmpty()) { config.fieldNames().forEach(s -> LOG.info("Unused variable in config '{}',", s)); } return deployconfig; } private DeployConfig withAuthToken(JsonObject config) { this.authToken = validateField(AUTH_TOKEN, config); return this; } private DeployConfig withTypedDeploy(JsonObject config) { this.typedDeploy = config.getBoolean(TYPED_DEPLOY, false); return this; } private DeployConfig withConfigLocation(JsonObject config) { this.configLocation = config.getString(CONFIG_LOCATION, ""); config.remove(CONFIG_LOCATION); return this; } private DeployConfig withPollInterval(JsonObject config) { this.pollInterval = config.getLong(POLL_INTERVAL, 3000L); config.remove(POLL_INTERVAL); return this; } private DeployConfig withServiceConfigLocation(JsonObject config) { this.serviceConfigLocation = config.getString(SERVICE_CONFIG_LOCATION, DEFAULT_SERVICE_CONFIG_LOCATION); config.remove(CONFIG_LOCATION); return this; } private DeployConfig withRunDir(JsonObject config) { this.runDir = config.getString(RUN_DIR, getVertxHome() + "/run/"); if (!runDir.endsWith("/")) { runDir = runDir + "/"; } this.statFile = runDir + STAT_FILE; config.remove(RUN_DIR); return this; } private DeployConfig withRemoteRepoUpdatePolicy(JsonObject config) { this.remoteRepoPolicy = config.getString(MAVEN_SNAPSHOT_POLICY, "always"); config.remove(MAVEN_SNAPSHOT_POLICY); return this; } private DeployConfig withCluster(JsonObject config) { this.asCluster = config.getBoolean(CLUSTER, true); config.remove(CLUSTER); return this; } private DeployConfig withLoggerFactoryName(JsonObject config) { this.defaultJavaOpts = config.getString(DEFAULT_JAVA_OPTS, ""); config.remove(DEFAULT_JAVA_OPTS); return this; } private DeployConfig withAwsConfig(JsonObject config) { this.awsRegion = validateField(AWS_REGION, config, AWS_DEFAULT_REGION); this.awsLoadbalancerId = validateField(AWS_INSTANCE_ID, config); this.awsEnabled = validateField(AWS_ENABLED, config, false); this.awsAutoDiscover = validateField(AWS_AS_AUTODISCOVER, config, false); this.awsMaxRegistrationDuration = config.getInteger(AWS_REGISTER_MAX_DURATION, 4); config.remove(AWS_REGISTER_MAX_DURATION); if (awsEnabled) { LOG.info("Enabled AWS support."); } else { LOG.info("Disabled AWS support."); } return this; } private DeployConfig withHttpAuth(JsonObject config) { this.httpAuthUser = validateField(HTTP_AUTH_USER, config, ""); this.httpAuthPassword = validateField(HTTP_AUTH_PASS, config, ""); if (!httpAuthUser.isEmpty() && !httpAuthPassword.isEmpty()) { LOG.info("Enabled http authentication."); this.httpAuthentication = true; } else { LOG.info("Disabled http authentication."); } return this; } private DeployConfig withHttpPort(JsonObject config) { this.httpPort = Integer.valueOf(validateField(HTTP_PORT, config, "6789")); return this; } public Path getVertxHome() { return vertxHome; } public Path getArtifactRepo() { return artifactRepo; } public URI getNexusUrl() { return nexusUrl; } public String getConfigLocation() { return configLocation; } public String getAwsRegion() { return awsRegion; } public String getAwsLoadbalancerId() { return awsLoadbalancerId; } public int getAwsMaxRegistrationDuration() { return awsMaxRegistrationDuration; } public String getHttpAuthUser() { return httpAuthUser; } public String getHttpAuthPassword() { return httpAuthPassword; } public boolean isAwsEnabled() { return awsEnabled; } public boolean isHttpAuthentication() { return httpAuthentication; } public boolean isMavenRemote() { return mavenRemote; } public String getAuthToken() { return authToken; } public boolean asCluster() { return asCluster; } public String getRemoteRepoPolicy() { return remoteRepoPolicy; } public String getDefaultJavaOpts() { return defaultJavaOpts; } public Integer getHttpPort() { return this.httpPort; } public String getRunDir() { return runDir; } public String getStatFile() { return statFile; } public boolean isAwsAutoDiscover() { return awsAutoDiscover; } public String getServiceConfigLocation() { return serviceConfigLocation; } public boolean isTypedDeploy() { return this.typedDeploy; } public long getPollIntervall() { return pollInterval; } }
apache-2.0
usc/dubbo-demo
src/main/java/com/alibaba/dubbo/remoting/transport/netty5/Netty5Transporter.java
764
package com.alibaba.dubbo.remoting.transport.netty5; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Client; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.Server; import com.alibaba.dubbo.remoting.Transporter; /** * @author Shunli */ public class Netty5Transporter implements Transporter { public static final String NAME = "netty5"; @Override public Server bind(URL url, ChannelHandler handler) throws RemotingException { return new Netty5Server(url, handler); } @Override public Client connect(URL url, ChannelHandler handler) throws RemotingException { return new Netty5Client(url, handler); } }
apache-2.0
sdnwiselab/onos
drivers/huawei/driver/src/main/java/org/onosproject/drivers/huawei/HuaweiDeviceDescription.java
7002
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.drivers.huawei; import com.google.common.collect.ImmutableList; import org.apache.commons.lang.StringUtils; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DefaultDeviceDescription; import org.onosproject.net.device.DeviceDescription; import org.onosproject.net.device.DeviceService; import org.onosproject.net.device.PortDescription; import org.onosproject.net.device.PortStatistics; import org.onosproject.net.device.PortStatisticsDiscovery; import org.onosproject.net.driver.AbstractHandlerBehaviour; import org.onosproject.netconf.NetconfController; import org.onosproject.netconf.NetconfException; import org.onosproject.netconf.NetconfSession; import org.slf4j.Logger; import java.io.IOException; import java.util.Collection; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.drivers.huawei.DriverUtil.DEV_INFO_FAILURE; import static org.onosproject.drivers.huawei.DriverUtil.RPC_CLOSE; import static org.onosproject.drivers.huawei.DriverUtil.RPC_CLOSE_FILTER; import static org.onosproject.drivers.huawei.DriverUtil.RPC_CLOSE_GET; import static org.onosproject.drivers.huawei.DriverUtil.RPC_CLOSE_IFM; import static org.onosproject.drivers.huawei.DriverUtil.RPC_FILTER; import static org.onosproject.drivers.huawei.DriverUtil.RPC_GET; import static org.onosproject.drivers.huawei.DriverUtil.RPC_IFM; import static org.onosproject.drivers.huawei.DriverUtil.RPC_IFS; import static org.onosproject.drivers.huawei.DriverUtil.RPC_MSG; import static org.onosproject.drivers.huawei.DriverUtil.RPC_SYS; import static org.onosproject.net.Device.Type.ROUTER; import static org.slf4j.LoggerFactory.getLogger; /** * Representation of device information and ports via NETCONF for huawei * routers. */ public class HuaweiDeviceDescription extends AbstractHandlerBehaviour implements PortStatisticsDiscovery { private final Logger log = getLogger(getClass()); /** * Constructs huawei device description. */ public HuaweiDeviceDescription() { } /** * Discovers device details, for huawei device by getting the system * information. * * @return device description */ @Override public DeviceDescription discoverDeviceDetails() { NetconfSession session = getNetconfSession(); String sysInfo; try { sysInfo = session.get(getVersionReq()); } catch (IOException e) { throw new IllegalArgumentException( new NetconfException(DEV_INFO_FAILURE)); } String[] details = parseSysInfoXml(sysInfo); DeviceService devSvc = checkNotNull(handler().get(DeviceService.class)); DeviceId devId = handler().data().deviceId(); Device dev = devSvc.getDevice(devId); return new DefaultDeviceDescription(dev.id().uri(), ROUTER, details[0], details[1], details[2], details[3], dev.chassisId()); } /** * Discovers interface details, for huawei device. * * @return port list */ @Override public List<PortDescription> discoverPortDetails() { return ImmutableList.copyOf(parseInterfaceXml(getInterfaces())); } /** * Returns the NETCONF session of the device. * * @return session */ private NetconfSession getNetconfSession() { NetconfController controller = checkNotNull( handler().get(NetconfController.class)); return controller.getDevicesMap().get(handler().data().deviceId()) .getSession(); } /** * Returns the rpc request message for fetching system details in huawei * device. * * @return rpc request message */ private String getVersionReq() { StringBuilder rpc = new StringBuilder(RPC_MSG); rpc.append(RPC_GET); rpc.append(RPC_FILTER); rpc.append(RPC_SYS); rpc.append(RPC_CLOSE_FILTER); rpc.append(RPC_CLOSE_GET); rpc.append(RPC_CLOSE); return rpc.toString(); } /** * Parses system info received from huawei device. * * @param sysInfo system info * @return parsed values */ private String[] parseSysInfoXml(String sysInfo) { HuaweiXmlParser parser = new HuaweiXmlParser(sysInfo); parser.parseSysInfo(); return parser.getInfo(); } /** * Returns the rpc request message for fetching interface details in * huawei device. * * @return rpc request message */ private String getInterfacesReq() { StringBuilder rpc = new StringBuilder(RPC_MSG); rpc.append(RPC_GET); rpc.append(RPC_FILTER); rpc.append(RPC_IFM); rpc.append(RPC_IFS); rpc.append(RPC_CLOSE_IFM); rpc.append(RPC_CLOSE_FILTER); rpc.append(RPC_CLOSE_GET); rpc.append(RPC_CLOSE); return rpc.toString(); } /** * Parses interfaces received from huawei device. * * @param interfaces interfaces * @return port list */ private List<PortDescription> parseInterfaceXml(String interfaces) { HuaweiXmlParser parser = new HuaweiXmlParser(interfaces); parser.parseInterfaces(); return parser.getPorts(); } @Override public Collection<PortStatistics> discoverPortStatistics() { String interfaces = getInterfaces(); if (StringUtils.isNotBlank(interfaces)) { Collection<PortStatistics> portStats = getPortStatistics(interfaces); return ImmutableList.copyOf(portStats); } return null; } private String getInterfaces() { NetconfSession session = getNetconfSession(); String interfaces = null; try { interfaces = session.get(getInterfacesReq()); } catch (IOException e) { log.info("Failed to retrive interface {} ", e.getMessage()); } return interfaces; } private Collection<PortStatistics> getPortStatistics(String ifs) { HuaweiXmlParser parser = new HuaweiXmlParser(ifs); return parser.parsePortsStatistics(handler().data().deviceId()); } }
apache-2.0
wangqi/gameserver
bootstrap/src/test/java/com/xinqihd/sns/gameserver/util/IOUtilTest.java
1043
package com.xinqihd.sns.gameserver.util; import static org.junit.Assert.*; import java.io.File; import java.io.FileOutputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; public class IOUtilTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testCompressString() throws Exception { String content = "您好, Hello!"; byte[] bytes = IOUtil.compressString("entry", content); FileOutputStream fos = new FileOutputStream(new File("compress.zip")); fos.write(bytes); fos.close(); String result = IOUtil.uncompressString(bytes); assertEquals(content, result); } @Test public void testCompressStringZlib() throws Exception { String content = "您好, Hello!"; byte[] bytes = IOUtil.compressStringZlib(content); FileOutputStream fos = new FileOutputStream(new File("compress.gz")); fos.write(bytes); fos.close(); String result = IOUtil.uncompressStringZlib(bytes); assertEquals(content, result); } }
apache-2.0
mourinho1908/vueshop
application/admin/controller/Index.php
3090
<?php namespace app\admin\controller; use app\common\controller\Backend; use think\Validate; /** * 后台首页 * @internal */ class Index extends Backend { protected $noNeedLogin = ['login']; protected $noNeedRight = ['index', 'logout']; protected $layout = ''; public function _initialize() { parent::_initialize(); } /** * 后台首页 */ public function index() { // $menulist = $this->auth->getSidebar([ 'dashboard' => 'hot', //'addon' => ['new', 'red', 'badge'], //'auth/rule' => 'side', //'general' => ['18', 'purple'], ], $this->view->site['fixedpage']); $this->view->assign('menulist', $menulist); $this->view->assign('title', __('Home')); return $this->view->fetch(); } /** * 管理员登录 */ public function login() { $url = $this->request->get('url', 'index/index'); if ($this->auth->isLogin()) { $this->error(__("You've logged in, do not login again"), $url); } if ($this->request->isPost()) { $username = $this->request->post('username'); $password = $this->request->post('password'); $keeplogin = $this->request->post('keeplogin'); $token = $this->request->post('__token__'); $rule = [ 'username' => 'require|length:3,30', 'password' => 'require|length:3,30', '__token__' => 'token', ]; $data = [ 'username' => $username, 'password' => $password, '__token__' => $token, ]; $validate = new Validate($rule); $result = $validate->check($data); if (!$result) { $this->error($validate->getError(), $url, ['token' => $this->request->token()]); } \app\admin\model\AdminLog::setTitle(__('Login')); $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0); if ($result === true) { $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]); } else { $this->error(__('Username or password is incorrect'), $url, ['token' => $this->request->token()]); } } // 根据客户端的cookie,判断是否可以自动登录 if ($this->auth->autologin()) { $this->redirect($url); } $background = cdnurl("/assets/img/loginbg.jpg"); $this->view->assign('background', $background); \think\Hook::listen("login_init", $this->request); return $this->view->fetch(); } /** * 注销登录 */ public function logout() { $this->auth->logout(); $this->success(__('Logout successful'), 'index/login'); } }
apache-2.0
froko/SimpleDomain
src/SimpleDomain/IEventSourcedAggregateRoot.cs
1855
//------------------------------------------------------------------------------- // <copyright file="IEventSourcedAggregateRoot.cs" company="frokonet.ch"> // Copyright (C) frokonet.ch, 2014-2020 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //------------------------------------------------------------------------------- namespace SimpleDomain { using System; /// <summary> /// Interface for all event sourced aggregate roots /// </summary> public interface IEventSourcedAggregateRoot : IAggregateRoot, INeedVersion { /// <summary> /// Gets the id of this Aggregate Root /// </summary> Guid Id { get; } /// <summary> /// Creates a snapshot of this Aggregate Root /// </summary> /// <returns>A snapshot</returns> ISnapshot CreateSnapshot(); /// <summary> /// Builds up the Aggregate Root from a snapshot /// </summary> /// <param name="snapshot">The snapshot</param> void LoadFromSnapshot(ISnapshot snapshot); /// <summary> /// Builds up the Aggregate Root from a list of events /// </summary> /// <param name="eventHistory">The history as list of events</param> void LoadFromEventHistory(EventHistory eventHistory); } }
apache-2.0
Ariah-Group/Continuity
src/main/java/org/kuali/continuity/plan/domain/Server.java
4747
// // Copyright 2011 Kuali Foundation, Inc. Licensed under the // Educational Community License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. You may // obtain a copy of the License at // // http://www.opensource.org/licenses/ecl2.php // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing // permissions and limitations under the License. // package org.kuali.continuity.plan.domain; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Table; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.TypeDef; import org.kuali.continuity.domain.BaseDomainObject; import org.kuali.continuity.domain.ext.StringValuedEnum; import org.kuali.continuity.domain.ext.StringValuedEnumType; @Entity @Table(name="it_servers") @TypeDef( name="stringValueEnum", typeClass=StringValuedEnumType.class) @NamedQuery(name="Server.list", query="select dObj from Server dObj where plan.id = :ownerId and disabled != 'Y'") @SuppressWarnings("serial") public class Server extends BaseDomainObject { private ContinuityPlan plan; private Type type; private String explanation; private String applicationsImpacted; private String serverSoftware; private BackupMedia backupMedia; private RecoveryProcedure recoveryProcedure; public Server() { } @Id @Column(name="it_server_id") @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return super.getId(); } public String getName() { return super.getName(); } public void setName(String name) { super.setName(name); } @ManyToOne(fetch=FetchType.LAZY, optional=false) @JoinColumn(name="pid", nullable=false) public ContinuityPlan getPlan() { return this.plan; } public void setPlan(ContinuityPlan plan) { this.plan = plan; } @Column(name="type_server") @org.hibernate.annotations.Type( type="stringValueEnum", parameters={ @Parameter( name="enum", value="org.kuali.continuity.plan.domain.Server$Type" )} ) public Type getType() { return this.type; } public void setType(Type type) { this.type = type; } public String getExplanation() { return this.explanation; } public void setExplanation(String explanation) { this.explanation = explanation; } @Column(name="apps_impacted", insertable=false) public String getApplicationsImpacted() { return this.applicationsImpacted; } public void setApplicationsImpacted(String applicationsImpacted) { this.applicationsImpacted = applicationsImpacted; } @Column(name="server_software", insertable=false) public String getServerSoftware() { return this.serverSoftware; } public void setServerSoftware(String serverSoftware) { this.serverSoftware = serverSoftware; } @Column(name="backup_media", insertable=false) @org.hibernate.annotations.Type( type="stringValueEnum", parameters={ @Parameter( name="enum", value="org.kuali.continuity.plan.domain.Server$BackupMedia" )} ) public BackupMedia getBackupMedia() { return this.backupMedia; } public void setBackupMedia(BackupMedia backupMedia) { this.backupMedia = backupMedia; } @Embedded public RecoveryProcedure getRecoveryProcedure() { return this.recoveryProcedure; } public void setRecoveryProcedure(RecoveryProcedure recoveryProcedure) { this.recoveryProcedure = recoveryProcedure; } public enum Type implements StringValuedEnum { FILE("File server"), APPLICATION("Application server"), DATABASE("Database server"), WEB("Web server"), BACKUP("Backup server"), MAINFRAME("Mainframe"), OTHER("Other (please explain)"); private final String refValue; Type(final String refValue) { this.refValue = refValue; } public String getValue() { return this.refValue; } } public enum BackupMedia implements StringValuedEnum { LOCAL_TAPE("Local Tape"), LOCAL_SERVER("Local Backup Server"), REMOTE_TAPE("Remote Tape"), REMOTE_SERVER("Remote Backup Server"), OTHER("Other (describe)"); private final String refValue; BackupMedia(final String refValue) { this.refValue = refValue; } public String getValue() { return this.refValue; } } }
apache-2.0
qwerty4030/elasticsearch
server/src/main/java/org/elasticsearch/action/support/broadcast/BroadcastResponse.java
5944
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.support.broadcast; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.support.DefaultShardOperationFailedException; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ConstructingObjectParser; import org.elasticsearch.common.xcontent.ToXContentFragment; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.action.RestActions; import java.io.IOException; import java.util.List; import static org.elasticsearch.action.support.DefaultShardOperationFailedException.readShardOperationFailed; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; /** * Base class for all broadcast operation based responses. */ public class BroadcastResponse extends ActionResponse implements ToXContentFragment { public static final DefaultShardOperationFailedException[] EMPTY = new DefaultShardOperationFailedException[0]; private static final ParseField _SHARDS_FIELD = new ParseField("_shards"); private static final ParseField TOTAL_FIELD = new ParseField("total"); private static final ParseField SUCCESSFUL_FIELD = new ParseField("successful"); private static final ParseField FAILED_FIELD = new ParseField("failed"); private static final ParseField FAILURES_FIELD = new ParseField("failures"); private int totalShards; private int successfulShards; private int failedShards; private DefaultShardOperationFailedException[] shardFailures = EMPTY; protected static <T extends BroadcastResponse> void declareBroadcastFields(ConstructingObjectParser<T, Void> PARSER) { ConstructingObjectParser<BroadcastResponse, Void> shardsParser = new ConstructingObjectParser<>("_shards", true, arg -> new BroadcastResponse((int) arg[0], (int) arg[1], (int) arg[2], (List<DefaultShardOperationFailedException>) arg[3])); shardsParser.declareInt(constructorArg(), TOTAL_FIELD); shardsParser.declareInt(constructorArg(), SUCCESSFUL_FIELD); shardsParser.declareInt(constructorArg(), FAILED_FIELD); shardsParser.declareObjectArray(optionalConstructorArg(), (p, c) -> DefaultShardOperationFailedException.fromXContent(p), FAILURES_FIELD); PARSER.declareObject(constructorArg(), shardsParser, _SHARDS_FIELD); } public BroadcastResponse() { } public BroadcastResponse(int totalShards, int successfulShards, int failedShards, List<DefaultShardOperationFailedException> shardFailures) { this.totalShards = totalShards; this.successfulShards = successfulShards; this.failedShards = failedShards; if (shardFailures == null) { this.shardFailures = EMPTY; } else { this.shardFailures = shardFailures.toArray(new DefaultShardOperationFailedException[shardFailures.size()]); } } /** * The total shards this request ran against. */ public int getTotalShards() { return totalShards; } /** * The successful shards this request was executed on. */ public int getSuccessfulShards() { return successfulShards; } /** * The failed shards this request was executed on. */ public int getFailedShards() { return failedShards; } /** * The REST status that should be used for the response */ public RestStatus getStatus() { if (failedShards > 0) { return shardFailures[0].status(); } else { return RestStatus.OK; } } /** * The list of shard failures exception. */ public DefaultShardOperationFailedException[] getShardFailures() { return shardFailures; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); totalShards = in.readVInt(); successfulShards = in.readVInt(); failedShards = in.readVInt(); int size = in.readVInt(); if (size > 0) { shardFailures = new DefaultShardOperationFailedException[size]; for (int i = 0; i < size; i++) { shardFailures[i] = readShardOperationFailed(in); } } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(totalShards); out.writeVInt(successfulShards); out.writeVInt(failedShards); out.writeVInt(shardFailures.length); for (DefaultShardOperationFailedException exp : shardFailures) { exp.writeTo(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { RestActions.buildBroadcastShardsHeader(builder, params, this); return builder; } }
apache-2.0
dqminh/runc
libcontainer/cgroups/fs/net_prio.go
655
package fs import ( "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/configs" ) type NetPrioGroup struct{} func (s *NetPrioGroup) Name() string { return "net_prio" } func (s *NetPrioGroup) Apply(path string, d *cgroupData) error { return join(path, d.pid) } func (s *NetPrioGroup) Set(path string, r *configs.Resources) error { for _, prioMap := range r.NetPrioIfpriomap { if err := cgroups.WriteFile(path, "net_prio.ifpriomap", prioMap.CgroupString()); err != nil { return err } } return nil } func (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error { return nil }
apache-2.0
leopardoooo/cambodia
boss-core/src/main/java/com/ycsoft/web/action/core/BankAction.java
1796
/** * */ package com.ycsoft.web.action.core; import org.springframework.stereotype.Controller; import com.ycsoft.business.service.impl.AcctService; import com.ycsoft.business.service.impl.CustService; import com.ycsoft.commons.helper.DateHelper; import com.ycsoft.web.commons.abstracts.BaseBusiAction; @Controller public class BankAction extends BaseBusiAction { private String acctPayType;//支付方式 private String custId; //客户编号 private String optionType; private AcctService acctService; private CustService custService; /** * 暂停卡扣 * @return * @throws Exception */ public String bankStop()throws Exception{ custService.saveBankStop(); return JSON; } /** * 恢复卡扣 * @return * @throws Exception */ public String bankResume()throws Exception{ custService.saveBankResume(); return JSON; } /** * 取消签约 * @return * @throws Exception */ public String cancelSign() throws Exception{ acctService.saveRemoveSignBank(acctPayType,DateHelper.now()); return JSON; } public String getAcctPayType() { return acctPayType; } public void setAcctPayType(String acctPayType) { this.acctPayType = acctPayType; } public String getCustId() { return custId; } public void setCustId(String custId) { this.custId = custId; } public void setAcctService(AcctService acctService) { this.acctService = acctService; } public String getOptionType() { return optionType; } public void setOptionType(String optionType) { this.optionType = optionType; } /** * @param custService the custService to set */ public void setCustService(CustService custService) { this.custService = custService; } }
apache-2.0
DevOps-TangoMe/flume-redis
flume-redis-core/src/main/java/com/tango/logstash/flume/redis/core/redis/JedisPoolFactoryImpl.java
1078
/** * Copyright 2014 TangoMe Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tango.logstash.flume.redis.core.redis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisPoolFactoryImpl implements JedisPoolFactory { public JedisPool create(JedisPoolConfig jedisPoolConfig, String host, Integer port, Integer timeout, String password, Integer database) { JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password, database); return jedisPool; } }
apache-2.0
V119/spidersManager
src/com/sicdlib/dto/SpiderInfoEntity.java
3373
package com.sicdlib.dto; import javax.persistence.*; /** * Created by YH on 2017/5/4. */ @Entity @Table(name = "spider_info", schema = "socialMind", catalog = "") public class SpiderInfoEntity { private String id; private String spiderSourcePath; private String websiteId; private String spiderName; private String fileName; private String fileId; private String addTime; @Id @Column(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @Basic @Column(name = "spider_source_path") public String getSpiderSourcePath() { return spiderSourcePath; } public void setSpiderSourcePath(String spiderSourcePath) { this.spiderSourcePath = spiderSourcePath; } @Basic @Column(name = "website_id") public String getWebsiteId() { return websiteId; } public void setWebsiteId(String websiteId) { this.websiteId = websiteId; } @Basic @Column(name = "spider_name") public String getSpiderName() { return spiderName; } public void setSpiderName(String spiderName) { this.spiderName = spiderName; } @Basic @Column(name = "file_name") public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } @Basic @Column(name = "file_id") public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } @Basic @Column(name = "add_time") public String getAddTime() { return addTime; } public void setAddTime(String addTime) { this.addTime = addTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SpiderInfoEntity that = (SpiderInfoEntity) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (spiderSourcePath != null ? !spiderSourcePath.equals(that.spiderSourcePath) : that.spiderSourcePath != null) return false; if (websiteId != null ? !websiteId.equals(that.websiteId) : that.websiteId != null) return false; if (spiderName != null ? !spiderName.equals(that.spiderName) : that.spiderName != null) return false; if (fileName != null ? !fileName.equals(that.fileName) : that.fileName != null) return false; if (fileId != null ? !fileId.equals(that.fileId) : that.fileId != null) return false; if (addTime != null ? !addTime.equals(that.addTime) : that.addTime != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (spiderSourcePath != null ? spiderSourcePath.hashCode() : 0); result = 31 * result + (websiteId != null ? websiteId.hashCode() : 0); result = 31 * result + (spiderName != null ? spiderName.hashCode() : 0); result = 31 * result + (fileName != null ? fileName.hashCode() : 0); result = 31 * result + (fileId != null ? fileId.hashCode() : 0); result = 31 * result + (addTime != null ? addTime.hashCode() : 0); return result; } }
apache-2.0
Panda-Programming-Language/Panda
panda-framework/src/main/java/org/panda_lang/panda/framework/language/architecture/module/ModuleLoaderUtils.java
3098
/* * Copyright (c) 2015-2019 Dzikoysk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.panda_lang.panda.framework.language.architecture.module; import org.jetbrains.annotations.Nullable; import org.panda_lang.panda.framework.design.architecture.module.ModuleLoader; import org.panda_lang.panda.framework.design.architecture.prototype.ClassPrototypeReference; import org.panda_lang.panda.framework.design.interpreter.parser.ParserData; import org.panda_lang.panda.framework.design.interpreter.parser.component.UniversalComponents; import org.panda_lang.panda.framework.design.interpreter.token.snippet.Snippet; import org.panda_lang.panda.framework.language.interpreter.parser.PandaParserFailure; import java.util.Optional; import java.util.function.Function; public class ModuleLoaderUtils { public static @Nullable ClassPrototypeReference getReferenceOrNull(ParserData data, String className) { return getReferenceOrOptional(data, className).orElse(null); } public static Optional<ClassPrototypeReference> getReferenceOrOptional(ParserData data, String className) { return data.getComponent(UniversalComponents.MODULE_LOADER).forClass(className); } public static ClassPrototypeReference getReferenceOrThrow(ParserData data, String className, @Nullable Snippet source) { return getReferenceOrThrow(data, className, "Unknown type " + className, source); } public static ClassPrototypeReference getReferenceOrThrow(ParserData data, String className, String message, @Nullable Snippet source) { return getReferenceOrThrow(data, loader -> loader.forClass(className), "Unknown type " + className, source); } public static ClassPrototypeReference getReferenceOrThrow(ParserData data, Class<?> type, @Nullable Snippet source) { return getReferenceOrThrow(data, type, "Unknown type " + type, source); } public static ClassPrototypeReference getReferenceOrThrow(ParserData data, Class<?> type, String message, @Nullable Snippet source) { return getReferenceOrThrow(data, loader -> loader.forClass(type), message, source); } static ClassPrototypeReference getReferenceOrThrow(ParserData data, Function<ModuleLoader, Optional<ClassPrototypeReference>> mapper, String message, Snippet source) { Optional<ClassPrototypeReference> reference = mapper.apply(data.getComponent(UniversalComponents.MODULE_LOADER)); if (!reference.isPresent()) { throw new PandaParserFailure(message, data, source); } return reference.get(); } }
apache-2.0
sundrio/sundrio
model/base/src/main/java/io/sundr/model/Annotatable.java
1396
/** * Copyright 2015 The original authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **/ package io.sundr.model; import java.util.List; import java.util.stream.Collectors; public interface Annotatable extends Node { List<AnnotationRef> getAnnotations(); /** * Render the annotations. * * @param indent the indentation to use for rendering the annotations * @return the rendered annotations. */ default String renderAnnotations(String indent) { StringBuilder sb = new StringBuilder(); if (getAnnotations() != null && !getAnnotations().isEmpty()) { sb.append( getAnnotations().stream().map(Renderable::render).map(line -> indent + line + NEWLINE).collect(Collectors.joining())); sb.append(indent); //This one is to make sure that lines with annotations are aligned with the rest } return sb.toString(); } }
apache-2.0
2B2i/2B2i.Dom
src/2B2i.Library/Debug.cs
2165
/* Copyright 2015 Bourderon Benjamin - 2B2i Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Runtime.CompilerServices; namespace _2B2i.Library { public static class _2BDebug { public static string Output(string message, [CallerFilePath] string callerpath = "", [CallerMemberName] string callerName = "", [CallerLineNumber] int callerline = 0) { return OutputInternal(message, callerpath, callerName, callerline); } public static string Output(Exception ex, [CallerFilePath] string callerpath = "", [CallerMemberName] string callerName = "", [CallerLineNumber] int callerline = 0) { return OutputInternal(ex.Message, callerpath, callerName, callerline); } private static string OutputInternal(string message, string callerpath = "", string callerName = "", int callerline = 0) { string ret = string.Empty; try { ret = string.Format("{0} : {1}", string.Format("[{0}:{1}] - {2} ", Path.GetFileName(callerpath), callerline, callerName), message); System.Diagnostics.Debug.WriteLine(ret); } catch { } return ret; } } }
apache-2.0
icraftsoftware/BizTalk.Factory
src/BizTalk.TestArtifacts.Binding/Orchestrations.Dummy/ProcessOrchestrationBinding.Designer.cs
4071
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Be.Stateless.BizTalk.Orchestrations.Dummy { using System; using System.CodeDom.Compiler; using Be.Stateless.BizTalk.Dsl.Binding; using Microsoft.XLANGs.Core; using Be.Stateless.BizTalk.Orchestrations.Dummy; [GeneratedCodeAttribute("Be.Stateless.BizTalk.Dsl", "1.0.0.0")] internal partial interface IProcessOrchestrationBinding : IOrchestrationBinding { ISendPort SendPort { get; set; } IReceivePort ReceivePort { get; set; } IReceivePort RequestResponsePort { get; set; } ISendPort SolicitResponsePort { get; set; } } [GeneratedCodeAttribute("Be.Stateless.BizTalk.Dsl", "1.0.0.0")] internal partial class ProcessOrchestrationBinding : OrchestrationBindingBase<Process>, IProcessOrchestrationBinding { #region Nested Type: DirectReceivePort public struct DirectReceivePort { public struct Operations { public struct DirectReceiveOperation { public static string Name = "DirectReceiveOperation"; } } } #endregion #region Nested Type: SendPort public struct SendPort { public struct Operations { public struct SendOperation { public static string Name = "SendOperation"; } } } #endregion #region Nested Type: ReceivePort public struct ReceivePort { public struct Operations { public struct ReceiveOperation { public static string Name = "ReceiveOperation"; } } } #endregion #region Nested Type: DirectSendPort public struct DirectSendPort { public struct Operations { public struct DirectSendOperation { public static string Name = "DirectSendOperation"; } } } #endregion #region Nested Type: RequestResponsePort public struct RequestResponsePort { public struct Operations { public struct RequestResponseOperation { public static string Name = "RequestResponseOperation"; } } } #endregion #region Nested Type: SolicitResponsePort public struct SolicitResponsePort { public struct Operations { public struct SolicitResponseOperation { public static string Name = "SolicitResponseOperation"; } } } #endregion public ProcessOrchestrationBinding() { } public ProcessOrchestrationBinding(Action<IProcessOrchestrationBinding> orchestrationBindingConfigurator) { orchestrationBindingConfigurator(this); ((Be.Stateless.BizTalk.Dsl.Binding.ISupportValidation)(this)).Validate(); } private ISendPort _SendPort; ISendPort IProcessOrchestrationBinding.SendPort { get { return this._SendPort; } set { this._SendPort = value; } } private IReceivePort _ReceivePort; IReceivePort IProcessOrchestrationBinding.ReceivePort { get { return this._ReceivePort; } set { this._ReceivePort = value; } } private IReceivePort _RequestResponsePort; IReceivePort IProcessOrchestrationBinding.RequestResponsePort { get { return this._RequestResponsePort; } set { this._RequestResponsePort = value; } } private ISendPort _SolicitResponsePort; ISendPort IProcessOrchestrationBinding.SolicitResponsePort { get { return this._SolicitResponsePort; } set { this._SolicitResponsePort = value; } } } }
apache-2.0
ariestse/spring-test-hibernate-dbunit
spring-test-hibernate-dbunit/src/test/java/com/github/springtestdbunit/dbunittestexecutionlistener/expected/ExpectedFailureOnClassTest.java
1848
/* * Copyright 2010 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.dbunittestexecutionlistener.expected; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @ExpectedDatabase("/META-INF/db/expectedfail.xml") @Transactional public class ExpectedFailureOnClassTest { @Autowired private EntityAssert entityAssert; @Test public void test() throws Exception { this.entityAssert.assertValues("existing1", "existing2"); } }
apache-2.0
etechi/ServiceFramework
Projects/Server/Sys/SF.Sys.Entities.Implements/AutoEntityProvider/Internals/EntityModifierBuilders/PropertyModifiers/UneditablePropertyModifier.cs
2219
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2017 Yang Chen (cy2000@gmail.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/etechi/ServiceFramework/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 using System; using System.ComponentModel; using System.Reflection; using SF.Sys.Annotations; namespace SF.Sys.Entities.AutoEntityProvider.Internals.EntityModifiers { public class UneditablePropertyModifierProvider : IEntityPropertyModifierProvider { public static int DefaultPriority { get; } = -10000; class UneditablePropertyModifier<T> : IEntityPropertyModifier<T, T> { public int MergePriority => DefaultPriority; public int ExecutePriority => 0; public T Execute(IEntityServiceContext ServiceContext, IEntityModifyContext Context, T OrgValue, T Value) { return Value; } public IEntityPropertyModifier Merge(IEntityPropertyModifier LowPriorityModifier)=> this; } public IEntityPropertyModifier GetPropertyModifier( DataActionType ActionType, Type EntityType, PropertyInfo EntityProperty, Type DataModelType, PropertyInfo DataModelProperty ) { var attr = DataModelProperty?.GetCustomAttribute<UneditableAttribute>() ?? EntityProperty?.GetCustomAttribute<UneditableAttribute>(); if (attr == null) return null; //²»¿É±à¼­ÊôÐÔÖ»ÔÚ´´½¨Ê±ÉèÖà if (ActionType != DataActionType.Create) return new NonePropertyModifier(DefaultPriority); return (IEntityPropertyModifier)Activator.CreateInstance(typeof(UneditablePropertyModifier<>).MakeGenericType(EntityProperty.PropertyType)); } } }
apache-2.0
spulec/moto
tests/test_applicationautoscaling/test_validation.py
4098
import boto3 from moto import mock_applicationautoscaling, mock_ecs from moto.applicationautoscaling import models from moto.applicationautoscaling.exceptions import AWSValidationException import pytest import sure # noqa # pylint: disable=unused-import from botocore.exceptions import ClientError from .test_applicationautoscaling import register_scalable_target DEFAULT_REGION = "us-east-1" DEFAULT_ECS_CLUSTER = "default" DEFAULT_ECS_TASK = "test_ecs_task" DEFAULT_ECS_SERVICE = "sample-webapp" DEFAULT_SERVICE_NAMESPACE = "ecs" DEFAULT_RESOURCE_ID = "service/{}/{}".format(DEFAULT_ECS_CLUSTER, DEFAULT_ECS_SERVICE) DEFAULT_SCALABLE_DIMENSION = "ecs:service:DesiredCount" DEFAULT_MIN_CAPACITY = 1 DEFAULT_MAX_CAPACITY = 1 DEFAULT_ROLE_ARN = "test:arn" @mock_applicationautoscaling def test_describe_scalable_targets_with_invalid_scalable_dimension_should_return_validation_exception(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) with pytest.raises(ClientError) as ex: client.describe_scalable_targets( ServiceNamespace=DEFAULT_SERVICE_NAMESPACE, ScalableDimension="foo", ) err = ex.value.response err["Error"]["Code"].should.equal("ValidationException") err["Error"]["Message"].split(":")[0].should.look_like( "1 validation error detected" ) err["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_applicationautoscaling def test_describe_scalable_targets_with_invalid_service_namespace_should_return_validation_exception(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) with pytest.raises(ClientError) as ex: client.describe_scalable_targets( ServiceNamespace="foo", ScalableDimension=DEFAULT_SCALABLE_DIMENSION, ) err = ex.value.response err["Error"]["Code"].should.equal("ValidationException") err["Error"]["Message"].split(":")[0].should.look_like( "1 validation error detected" ) err["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_applicationautoscaling def test_describe_scalable_targets_with_multiple_invalid_parameters_should_return_validation_exception(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) with pytest.raises(ClientError) as ex: client.describe_scalable_targets( ServiceNamespace="foo", ScalableDimension="bar", ) err = ex.value.response err["Error"]["Code"].should.equal("ValidationException") err["Error"]["Message"].split(":")[0].should.look_like( "2 validation errors detected" ) err["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_ecs @mock_applicationautoscaling def test_register_scalable_target_ecs_with_non_existent_service_should_return_clusternotfound_exception(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) resource_id = "service/{}/foo".format(DEFAULT_ECS_CLUSTER) with pytest.raises(ClientError) as ex: register_scalable_target(client, ServiceNamespace="ecs", ResourceId=resource_id) err = ex.value.response err["Error"]["Code"].should.equal("ClusterNotFoundException") err["Error"]["Message"].should.equal("Cluster not found.") err["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @pytest.mark.parametrize( "namespace,r_id,dimension,expected", [ ("ecs", "service/default/test-svc", "ecs:service:DesiredCount", True), ("ecs", "banana/default/test-svc", "ecs:service:DesiredCount", False), ("rds", "service/default/test-svc", "ecs:service:DesiredCount", False), ], ) def test_target_params_are_valid_success(namespace, r_id, dimension, expected): if expected is True: models._target_params_are_valid(namespace, r_id, dimension).should.equal( expected ) else: with pytest.raises(AWSValidationException): models._target_params_are_valid(namespace, r_id, dimension) # TODO add a test for not-supplied MinCapacity or MaxCapacity (ValidationException)
apache-2.0
doged/dogecoindarkj
core/src/main/java/com/dogecoindark/dogecoindarkj/core/Transaction.java
61048
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dogecoindark.dogecoindarkj.core; import com.dogecoindark.dogecoindarkj.core.TransactionConfidence.ConfidenceType; import com.dogecoindark.dogecoindarkj.crypto.TransactionSignature; import com.dogecoindark.dogecoindarkj.script.Script; import com.dogecoindark.dogecoindarkj.script.ScriptBuilder; import com.dogecoindark.dogecoindarkj.script.ScriptOpCodes; import com.dogecoindark.dogecoindarkj.utils.ExchangeRate; import com.dogecoindark.dogecoindarkj.wallet.WalletTransaction.Pool; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import static com.dogecoindark.dogecoindarkj.core.Utils.*; import static com.google.common.base.Preconditions.checkState; /** * <p>A transaction represents the movement of coins from some addresses to some other addresses. It can also represent * the minting of new coins. A Transaction object corresponds to the equivalent in the Bitcoin C++ implementation.</p> * * <p>Transactions are the fundamental atoms of Bitcoin and have many powerful features. Read * <a href="http://code.google.com/p/bitcoinj/wiki/WorkingWithTransactions">"Working with transactions"</a> in the * documentation to learn more about how to use this class.</p> * * <p>All Bitcoin transactions are at risk of being reversed, though the risk is much less than with traditional payment * systems. Transactions have <i>confidence levels</i>, which help you decide whether to trust a transaction or not. * Whether to trust a transaction is something that needs to be decided on a case by case basis - a rule that makes * sense for selling MP3s might not make sense for selling cars, or accepting payments from a family member. If you * are building a wallet, how to present confidence to your users is something to consider carefully.</p> */ public class Transaction extends ChildMessage implements Serializable { /** * A comparator that can be used to sort transactions by their updateTime field. The ordering goes from most recent * into the past. */ public static final Comparator<Transaction> SORT_TX_BY_UPDATE_TIME = new Comparator<Transaction>() { @Override public int compare(final Transaction tx1, final Transaction tx2) { final long time1 = tx1.getUpdateTime().getTime(); final long time2 = tx2.getUpdateTime().getTime(); final int updateTimeComparison = -(Longs.compare(time1, time2)); //If time1==time2, compare by tx hash to make comparator consistent with equals return updateTimeComparison != 0 ? updateTimeComparison : tx1.getHash().compareTo(tx2.getHash()); } }; /** A comparator that can be used to sort transactions by their chain height. */ public static final Comparator<Transaction> SORT_TX_BY_HEIGHT = new Comparator<Transaction>() { @Override public int compare(final Transaction tx1, final Transaction tx2) { final int height1 = tx1.getConfidence().getAppearedAtChainHeight(); final int height2 = tx2.getConfidence().getAppearedAtChainHeight(); final int heightComparison = -(Ints.compare(height1, height2)); //If height1==height2, compare by tx hash to make comparator consistent with equals return heightComparison != 0 ? heightComparison : tx1.getHash().compareTo(tx2.getHash()); } }; private static final Logger log = LoggerFactory.getLogger(Transaction.class); private static final long serialVersionUID = -8567546957352643140L; /** Threshold for lockTime: below this value it is interpreted as block number, otherwise as timestamp. **/ public static final int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC /** How many bytes a transaction can be before it won't be relayed anymore. Currently 100kb. */ public static final int MAX_STANDARD_TX_SIZE = 100000; /** * If fee is lower than this value (in satoshis), a default reference client will treat it as if there were no fee. * Currently this is 1000 satoshis. */ public static final Coin REFERENCE_DEFAULT_MIN_TX_FEE = Coin.COIN; // 1 DOGE min fee /** * Any standard (ie pay-to-address) output smaller than this value (in satoshis) will most likely be rejected by the network. * This is calculated by assuming a standard output will be 34 bytes, and then using the formula used in * {@link TransactionOutput#getMinNonDustValue(Coin)}. Currently it's 546 satoshis. */ public static final Coin MIN_NONDUST_OUTPUT = Coin.SATOSHI; //DOGE: We can send one "shibetoshi" but this will cost us extra fee! // These are serialized in both bitcoin and java serialization. private long version; private long time; private ArrayList<TransactionInput> inputs; private ArrayList<TransactionOutput> outputs; private long lockTime; // This is either the time the transaction was broadcast as measured from the local clock, or the time from the // block in which it was included. Note that this can be changed by re-orgs so the wallet may update this field. // Old serialized transactions don't have this field, thus null is valid. It is used for returning an ordered // list of transactions from a wallet, which is helpful for presenting to users. private Date updatedAt; // This is an in memory helper only. private transient Sha256Hash hash; // Data about how confirmed this tx is. Serialized, may be null. private TransactionConfidence confidence; // Records a map of which blocks the transaction has appeared in (keys) to an index within that block (values). // The "index" is not a real index, instead the values are only meaningful relative to each other. For example, // consider two transactions that appear in the same block, t1 and t2, where t2 spends an output of t1. Both // will have the same block hash as a key in their appearsInHashes, but the counter would be 1 and 2 respectively // regardless of where they actually appeared in the block. // // If this transaction is not stored in the wallet, appearsInHashes is null. private Map<Sha256Hash, Integer> appearsInHashes; // Transactions can be encoded in a way that will use more bytes than is optimal // (due to VarInts having multiple encodings) // MAX_BLOCK_SIZE must be compared to the optimal encoding, not the actual encoding, so when parsing, we keep track // of the size of the ideal encoding in addition to the actual message size (which Message needs) so that Blocks // can properly keep track of optimal encoded size private transient int optimalEncodingMessageSize; /** * This enum describes the underlying reason the transaction was created. It's useful for rendering wallet GUIs * more appropriately. */ public enum Purpose { /** Used when the purpose of a transaction is genuinely unknown. */ UNKNOWN, /** Transaction created to satisfy a user payment request. */ USER_PAYMENT, /** Transaction automatically created and broadcast in order to reallocate money from old to new keys. */ KEY_ROTATION, /** Transaction that uses up pledges to an assurance contract */ ASSURANCE_CONTRACT_CLAIM, /** Transaction that makes a pledge to an assurance contract. */ ASSURANCE_CONTRACT_PLEDGE, /** Send-to-self transaction that exists just to create an output of the right size we can pledge. */ ASSURANCE_CONTRACT_STUB // In future: de/refragmentation, privacy boosting/mixing, child-pays-for-parent fees, etc. } private Purpose purpose = Purpose.UNKNOWN; /** * This field can be used by applications to record the exchange rate that was valid when the transaction happened. * It's optional. */ @Nullable private ExchangeRate exchangeRate; /** * This field can be used to record the memo of the payment request that initiated the transaction. It's optional. */ @Nullable private String memo; public Transaction(NetworkParameters params) { super(params); version = 1; inputs = new ArrayList<TransactionInput>(); outputs = new ArrayList<TransactionOutput>(); // We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet. length = 8; // 8 for std fields } /** * Creates a transaction from the given serialized bytes, eg, from a block or a tx network message. */ public Transaction(NetworkParameters params, byte[] payloadBytes) throws ProtocolException { super(params, payloadBytes, 0); } /** * Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed. */ public Transaction(NetworkParameters params, byte[] payload, int offset) throws ProtocolException { super(params, payload, offset); // inputs/outputs will be created in parse() } /** * Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed. * @param params NetworkParameters object. * @param payload Bitcoin protocol formatted byte array containing message content. * @param offset The location of the first payload byte within the array. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseRetain Whether to retain the backing byte array for quick reserialization. * If true and the backing byte array is invalidated due to modification of a field then * the cached bytes may be repopulated and retained if the message is serialized again in the future. * @param length The length of message if known. Usually this is provided when deserializing of the wire * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * @throws ProtocolException */ public Transaction(NetworkParameters params, byte[] payload, int offset, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException { super(params, payload, offset, parent, parseLazy, parseRetain, length); } /** * Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed. */ public Transaction(NetworkParameters params, byte[] payload, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException { super(params, payload, 0, parent, parseLazy, parseRetain, length); } /** * Returns the transaction hash as you see them in the block explorer. */ @Override public Sha256Hash getHash() { if (hash == null) { byte[] bits = bitcoinSerialize(); hash = new Sha256Hash(reverseBytes(doubleDigest(bits))); } return hash; } /** * Used by BitcoinSerializer. The serializer has to calculate a hash for checksumming so to * avoid wasting the considerable effort a set method is provided so the serializer can set it. * * No verification is performed on this hash. */ void setHash(Sha256Hash hash) { this.hash = hash; } public String getHashAsString() { return getHash().toString(); } /** * Calculates the sum of the outputs that are sending coins to a key in the wallet. The flag controls whether to * include spent outputs or not. */ Coin getValueSentToMe(TransactionBag transactionBag, boolean includeSpent) { maybeParse(); // This is tested in WalletTest. Coin v = Coin.ZERO; for (TransactionOutput o : outputs) { if (!o.isMineOrWatched(transactionBag)) continue; if (!includeSpent && !o.isAvailableForSpending()) continue; v = v.add(o.getValue()); } return v; } /* * If isSpent - check that all my outputs spent, otherwise check that there at least * one unspent. */ boolean isConsistent(TransactionBag transactionBag, boolean isSpent) { boolean isActuallySpent = true; for (TransactionOutput o : outputs) { if (o.isAvailableForSpending()) { if (o.isMineOrWatched(transactionBag)) isActuallySpent = false; if (o.getSpentBy() != null) { log.error("isAvailableForSpending != spentBy"); return false; } } else { if (o.getSpentBy() == null) { log.error("isAvailableForSpending != spentBy"); return false; } } } return isActuallySpent == isSpent; } /** * Calculates the sum of the outputs that are sending coins to a key in the wallet. */ public Coin getValueSentToMe(TransactionBag transactionBag) { return getValueSentToMe(transactionBag, true); } /** * Returns a map of block [hashes] which contain the transaction mapped to relativity counters, or null if this * transaction doesn't have that data because it's not stored in the wallet or because it has never appeared in a * block. */ @Nullable public Map<Sha256Hash, Integer> getAppearsInHashes() { return appearsInHashes != null ? ImmutableMap.copyOf(appearsInHashes) : null; } /** * Convenience wrapper around getConfidence().getConfidenceType() * @return true if this transaction hasn't been seen in any block yet. */ public boolean isPending() { return getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.PENDING; } /** * <p>Puts the given block in the internal set of blocks in which this transaction appears. This is * used by the wallet to ensure transactions that appear on side chains are recorded properly even though the * block stores do not save the transaction data at all.</p> * * <p>If there is a re-org this will be called once for each block that was previously seen, to update which block * is the best chain. The best chain block is guaranteed to be called last. So this must be idempotent.</p> * * <p>Sets updatedAt to be the earliest valid block time where this tx was seen.</p> * * @param block The {@link StoredBlock} in which the transaction has appeared. * @param bestChain whether to set the updatedAt timestamp from the block header (only if not already set) * @param relativityOffset A number that disambiguates the order of transactions within a block. */ public void setBlockAppearance(StoredBlock block, boolean bestChain, int relativityOffset) { long blockTime = block.getHeader().getTimeSeconds() * 1000; if (bestChain && (updatedAt == null || updatedAt.getTime() == 0 || updatedAt.getTime() > blockTime)) { updatedAt = new Date(blockTime); } addBlockAppearance(block.getHeader().getHash(), relativityOffset); if (bestChain) { TransactionConfidence transactionConfidence = getConfidence(); // This sets type to BUILDING and depth to one. transactionConfidence.setAppearedAtChainHeight(block.getHeight()); } } public void addBlockAppearance(final Sha256Hash blockHash, int relativityOffset) { if (appearsInHashes == null) { // TODO: This could be a lot more memory efficient as we'll typically only store one element. appearsInHashes = new TreeMap<Sha256Hash, Integer>(); } appearsInHashes.put(blockHash, relativityOffset); } /** * Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the * transactions sending coins to those keys to be in the wallet. This method will not attempt to download the * blocks containing the input transactions if the key is in the wallet but the transactions are not. * * @return sum of the inputs that are spending coins with keys in the wallet */ public Coin getValueSentFromMe(TransactionBag wallet) throws ScriptException { maybeParse(); // This is tested in WalletTest. Coin v = Coin.ZERO; for (TransactionInput input : inputs) { // This input is taking value from a transaction in our wallet. To discover the value, // we must find the connected transaction. TransactionOutput connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.UNSPENT)); if (connected == null) connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.SPENT)); if (connected == null) connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.PENDING)); if (connected == null) continue; // The connected output may be the change to the sender of a previous input sent to this wallet. In this // case we ignore it. if (!connected.isMineOrWatched(wallet)) continue; v = v.add(connected.getValue()); } return v; } /** * Returns the difference of {@link Transaction#getValueSentToMe(TransactionBag)} and {@link Transaction#getValueSentFromMe(TransactionBag)}. */ public Coin getValue(TransactionBag wallet) throws ScriptException { return getValueSentToMe(wallet).subtract(getValueSentFromMe(wallet)); } /** * The transaction fee is the difference of the value of all inputs and the value of all outputs. Currently, the fee * can only be determined for transactions created by us. * * @return fee, or null if it cannot be determined */ public Coin getFee() { Coin fee = Coin.ZERO; for (TransactionInput input : inputs) { if (input.getValue() == null) return null; fee = fee.add(input.getValue()); } for (TransactionOutput output : outputs) { fee = fee.subtract(output.getValue()); } return fee; } boolean disconnectInputs() { boolean disconnected = false; maybeParse(); for (TransactionInput input : inputs) { disconnected |= input.disconnect(); } return disconnected; } /** * Returns true if every output is marked as spent. */ public boolean isEveryOutputSpent() { maybeParse(); for (TransactionOutput output : outputs) { if (output.isAvailableForSpending()) return false; } return true; } /** * Returns true if any of the outputs is marked as spent. */ public boolean isAnyOutputSpent() { maybeParse(); for (TransactionOutput output : outputs) { if (!output.isAvailableForSpending()) return true; } return false; } /** * Returns false if this transaction has at least one output that is owned by the given wallet and unspent, true * otherwise. */ public boolean isEveryOwnedOutputSpent(TransactionBag transactionBag) { maybeParse(); for (TransactionOutput output : outputs) { if (output.isAvailableForSpending() && output.isMineOrWatched(transactionBag)) return false; } return true; } public long getTime() { return time; } public void setTime(long nTime) { this.time = nTime; } /** * Returns the earliest time at which the transaction was seen (broadcast or included into the chain), * or the epoch if that information isn't available. */ public Date getUpdateTime() { if (updatedAt == null) { // Older wallets did not store this field. Set to the epoch. updatedAt = new Date(0); } return updatedAt; } public void setUpdateTime(Date updatedAt) { this.updatedAt = updatedAt; } /** * These constants are a part of a scriptSig signature on the inputs. They define the details of how a * transaction can be redeemed, specifically, they control how the hash of the transaction is calculated. * <p/> * In the official client, this enum also has another flag, SIGHASH_ANYONECANPAY. In this implementation, * that's kept separate. Only SIGHASH_ALL is actually used in the official client today. The other flags * exist to allow for distributed contracts. */ public enum SigHash { ALL, // 1 NONE, // 2 SINGLE, // 3 } public static final byte SIGHASH_ANYONECANPAY_VALUE = (byte) 0x80; @Override protected void unCache() { super.unCache(); hash = null; } @Override protected void parseLite() throws ProtocolException { //skip this if the length has been provided i.e. the tx is not part of a block if (parseLazy && length == UNKNOWN_LENGTH) { //If length hasn't been provided this tx is probably contained within a block. //In parseRetain mode the block needs to know how long the transaction is //unfortunately this requires a fairly deep (though not total) parse. //This is due to the fact that transactions in the block's list do not include a //size header and inputs/outputs are also variable length due the contained //script so each must be instantiated so the scriptlength varint can be read //to calculate total length of the transaction. //We will still persist will this semi-light parsing because getting the lengths //of the various components gains us the ability to cache the backing bytearrays //so that only those subcomponents that have changed will need to be reserialized. //parse(); //parsed = true; length = calcLength(payload, offset); cursor = offset + length; } } protected static int calcLength(byte[] buf, int offset) { VarInt varint; // jump past version (uint32) int cursor = offset + 4; int i; long scriptLen; varint = new VarInt(buf, cursor); long txInCount = varint.value; cursor += varint.getOriginalSizeInBytes(); for (i = 0; i < txInCount; i++) { // 36 = length of previous_outpoint cursor += 36; varint = new VarInt(buf, cursor); scriptLen = varint.value; // 4 = length of sequence field (unint32) cursor += scriptLen + 4 + varint.getOriginalSizeInBytes(); } varint = new VarInt(buf, cursor); long txOutCount = varint.value; cursor += varint.getOriginalSizeInBytes(); for (i = 0; i < txOutCount; i++) { // 8 = length of tx value field (uint64) cursor += 8; varint = new VarInt(buf, cursor); scriptLen = varint.value; cursor += scriptLen + varint.getOriginalSizeInBytes(); } // 4 = length of lock_time field (uint32) return cursor - offset + 4; } @Override void parse() throws ProtocolException { if (parsed) return; cursor = offset; version = readUint32(); optimalEncodingMessageSize = 4; // First come the inputs. long numInputs = readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(numInputs); inputs = new ArrayList<TransactionInput>((int) numInputs); for (long i = 0; i < numInputs; i++) { TransactionInput input = new TransactionInput(params, this, payload, cursor, parseLazy, parseRetain); inputs.add(input); long scriptLen = readVarInt(TransactionOutPoint.MESSAGE_LENGTH); optimalEncodingMessageSize += TransactionOutPoint.MESSAGE_LENGTH + VarInt.sizeOf(scriptLen) + scriptLen + 4; cursor += scriptLen + 4; } // Now the outputs long numOutputs = readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(numOutputs); outputs = new ArrayList<TransactionOutput>((int) numOutputs); for (long i = 0; i < numOutputs; i++) { TransactionOutput output = new TransactionOutput(params, this, payload, cursor, parseLazy, parseRetain); outputs.add(output); long scriptLen = readVarInt(8); optimalEncodingMessageSize += 8 + VarInt.sizeOf(scriptLen) + scriptLen; cursor += scriptLen; } lockTime = readUint32(); optimalEncodingMessageSize += 4; length = cursor - offset; } public int getOptimalEncodingMessageSize() { if (optimalEncodingMessageSize != 0) return optimalEncodingMessageSize; maybeParse(); if (optimalEncodingMessageSize != 0) return optimalEncodingMessageSize; optimalEncodingMessageSize = getMessageSize(); return optimalEncodingMessageSize; } /** * A coinbase transaction is one that creates a new coin. They are the first transaction in each block and their * value is determined by a formula that all implementations of Bitcoin share. In 2011 the value of a coinbase * transaction is 50 coins, but in future it will be less. A coinbase transaction is defined not only by its * position in a block but by the data in the inputs. */ public boolean isCoinBase() { maybeParse(); return inputs.size() == 1 && inputs.get(0).isCoinBase(); } /** * A transaction is mature if it is either a building coinbase tx that is as deep or deeper than the required coinbase depth, or a non-coinbase tx. */ public boolean isMature() { if (!isCoinBase()) return true; if (getConfidence().getConfidenceType() != ConfidenceType.BUILDING) return false; return getConfidence().getDepthInBlocks() >= params.getSpendableCoinbaseDepth(); } @Override public String toString() { return toString(null); } /** * A human readable version of the transaction useful for debugging. The format is not guaranteed to be stable. * @param chain If provided, will be used to estimate lock times (if set). Can be null. */ public String toString(@Nullable AbstractBlockChain chain) { // Basic info about the tx. StringBuilder s = new StringBuilder(); s.append(String.format(" %s: %s%n", getHashAsString(), getConfidence())); if (isTimeLocked()) { String time; if (lockTime < LOCKTIME_THRESHOLD) { time = "block " + lockTime; if (chain != null) { time = time + " (estimated to be reached at " + chain.estimateBlockTime((int)lockTime).toString() + ")"; } } else { time = new Date(lockTime*1000).toString(); } s.append(String.format(" time locked until %s%n", time)); } if (inputs.size() == 0) { s.append(String.format(" INCOMPLETE: No inputs!%n")); return s.toString(); } if (isCoinBase()) { String script; String script2; try { script = inputs.get(0).getScriptSig().toString(); script2 = outputs.get(0).getScriptPubKey().toString(); } catch (ScriptException e) { script = "???"; script2 = "???"; } s.append(" == COINBASE TXN (scriptSig " + script + ") (scriptPubKey " + script2 + ")\n"); return s.toString(); } for (TransactionInput in : inputs) { s.append(" "); s.append("in "); try { Script scriptSig = in.getScriptSig(); s.append(scriptSig); if (in.getValue() != null) s.append(" ").append(in.getValue().toFriendlyString()); s.append("\n "); s.append("outpoint:"); final TransactionOutPoint outpoint = in.getOutpoint(); s.append(outpoint.toString()); final TransactionOutput connectedOutput = outpoint.getConnectedOutput(); if (connectedOutput != null) { Script scriptPubKey = connectedOutput.getScriptPubKey(); if (scriptPubKey.isSentToAddress() || scriptPubKey.isPayToScriptHash()) { s.append(" hash160:"); s.append(Utils.HEX.encode(scriptPubKey.getPubKeyHash())); } } } catch (Exception e) { s.append("[exception: ").append(e.getMessage()).append("]"); } s.append(String.format("%n")); } for (TransactionOutput out : outputs) { s.append(" "); s.append("out "); try { Script scriptPubKey = out.getScriptPubKey(); s.append(scriptPubKey); s.append(" "); s.append(out.getValue().toFriendlyString()); if (!out.isAvailableForSpending()) { s.append(" Spent"); } if (out.getSpentBy() != null) { s.append(" by "); s.append(out.getSpentBy().getParentTransaction().getHashAsString()); } } catch (Exception e) { s.append("[exception: ").append(e.getMessage()).append("]"); } s.append(String.format("%n")); } Coin fee = getFee(); if (fee != null) s.append(" fee ").append(fee.toFriendlyString()).append(String.format("%n")); return s.toString(); } /** * Removes all the inputs from this transaction. * Note that this also invalidates the length attribute */ public void clearInputs() { unCache(); for (TransactionInput input : inputs) { input.setParent(null); } inputs.clear(); // You wanted to reserialize, right? this.length = this.bitcoinSerialize().length; } /** * Adds an input to this transaction that imports value from the given output. Note that this input is NOT * complete and after every input is added with addInput() and every output is added with addOutput(), * signInputs() must be called to finalize the transaction and finish the inputs off. Otherwise it won't be * accepted by the network. Returns the newly created input. */ public TransactionInput addInput(TransactionOutput from) { return addInput(new TransactionInput(params, this, from)); } /** Adds an input directly, with no checking that it's valid. Returns the new input. */ public TransactionInput addInput(TransactionInput input) { unCache(); input.setParent(this); inputs.add(input); adjustLength(inputs.size(), input.length); return input; } /** Adds an input directly, with no checking that it's valid. Returns the new input. */ public TransactionInput addInput(Sha256Hash spendTxHash, long outputIndex, Script script) { return addInput(new TransactionInput(params, this, script.getProgram(), new TransactionOutPoint(params, outputIndex, spendTxHash))); } /** * Adds a new and fully signed input for the given parameters. Note that this method is <b>not</b> thread safe * and requires external synchronization. Please refer to general documentation on Bitcoin scripting and contracts * to understand the values of sigHash and anyoneCanPay: otherwise you can use the other form of this method * that sets them to typical defaults. * * @throws ScriptException if the scriptPubKey is not a pay to address or pay to pubkey script. */ public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) throws ScriptException { // Verify the API user didn't try to do operations out of order. checkState(!outputs.isEmpty(), "Attempting to sign tx without outputs."); TransactionInput input = new TransactionInput(params, this, new byte[]{}, prevOut); addInput(input); Sha256Hash hash = hashForSignature(inputs.size() - 1, scriptPubKey, sigHash, anyoneCanPay); ECKey.ECDSASignature ecSig = sigKey.sign(hash); TransactionSignature txSig = new TransactionSignature(ecSig, sigHash, anyoneCanPay); if (scriptPubKey.isSentToRawPubKey()) input.setScriptSig(ScriptBuilder.createInputScript(txSig)); else if (scriptPubKey.isSentToAddress()) input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey)); else throw new ScriptException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey); return input; } /** * Same as {@link #addSignedInput(TransactionOutPoint, com.dogecoindark.dogecoindarkj.script.Script, ECKey, com.dogecoindark.dogecoindarkj.core.Transaction.SigHash, boolean)} * but defaults to {@link SigHash#ALL} and "false" for the anyoneCanPay flag. This is normally what you want. */ public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey) throws ScriptException { return addSignedInput(prevOut, scriptPubKey, sigKey, SigHash.ALL, false); } /** * Adds an input that points to the given output and contains a valid signature for it, calculated using the * signing key. */ public TransactionInput addSignedInput(TransactionOutput output, ECKey signingKey) { return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), signingKey); } /** * Adds an input that points to the given output and contains a valid signature for it, calculated using the * signing key. */ public TransactionInput addSignedInput(TransactionOutput output, ECKey signingKey, SigHash sigHash, boolean anyoneCanPay) { return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), signingKey, sigHash, anyoneCanPay); } /** * Removes all the inputs from this transaction. * Note that this also invalidates the length attribute */ public void clearOutputs() { unCache(); for (TransactionOutput output : outputs) { output.setParent(null); } outputs.clear(); // You wanted to reserialize, right? this.length = this.bitcoinSerialize().length; } /** * Adds the given output to this transaction. The output must be completely initialized. Returns the given output. */ public TransactionOutput addOutput(TransactionOutput to) { unCache(); to.setParent(this); outputs.add(to); adjustLength(outputs.size(), to.length); return to; } /** * Creates an output based on the given address and value, adds it to this transaction, and returns the new output. */ public TransactionOutput addOutput(Coin value, Address address) { return addOutput(new TransactionOutput(params, this, value, address)); } /** * Creates an output that pays to the given pubkey directly (no address) with the given value, adds it to this * transaction, and returns the new output. */ public TransactionOutput addOutput(Coin value, ECKey pubkey) { return addOutput(new TransactionOutput(params, this, value, pubkey)); } /** * Creates an output that pays to the given script. The address and key forms are specialisations of this method, * you won't normally need to use it unless you're doing unusual things. */ public TransactionOutput addOutput(Coin value, Script script) { return addOutput(new TransactionOutput(params, this, value, script.getProgram())); } /** * Calculates a signature that is valid for being inserted into the input at the given position. This is simply * a wrapper around calling {@link Transaction#hashForSignature(int, byte[], com.dogecoindark.dogecoindarkj.core.Transaction.SigHash, boolean)} * followed by {@link ECKey#sign(Sha256Hash)} and then returning a new {@link TransactionSignature}. The key * must be usable for signing as-is: if the key is encrypted it must be decrypted first external to this method. * * @param inputIndex Which input to calculate the signature for, as an index. * @param key The private key used to calculate the signature. * @param redeemScript Byte-exact contents of the scriptPubKey that is being satisified, or the P2SH redeem script. * @param hashType Signing mode, see the enum for documentation. * @param anyoneCanPay Signing mode, see the SigHash enum for documentation. * @return A newly calculated signature object that wraps the r, s and sighash components. */ public synchronized TransactionSignature calculateSignature(int inputIndex, ECKey key, byte[] redeemScript, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForSignature(inputIndex, redeemScript, hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash), hashType, anyoneCanPay); } /** * Calculates a signature that is valid for being inserted into the input at the given position. This is simply * a wrapper around calling {@link Transaction#hashForSignature(int, byte[], com.dogecoindark.dogecoindarkj.core.Transaction.SigHash, boolean)} * followed by {@link ECKey#sign(Sha256Hash)} and then returning a new {@link TransactionSignature}. * * @param inputIndex Which input to calculate the signature for, as an index. * @param key The private key used to calculate the signature. * @param redeemScript The scriptPubKey that is being satisified, or the P2SH redeem script. * @param hashType Signing mode, see the enum for documentation. * @param anyoneCanPay Signing mode, see the SigHash enum for documentation. * @return A newly calculated signature object that wraps the r, s and sighash components. */ public synchronized TransactionSignature calculateSignature(int inputIndex, ECKey key, Script redeemScript, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForSignature(inputIndex, redeemScript.getProgram(), hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash), hashType, anyoneCanPay); } /** * <p>Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction * is simplified is specified by the type and anyoneCanPay parameters.</p> * * <p>This is a low level API and when using the regular {@link Wallet} class you don't have to call this yourself. * When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output * the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the * scriptPubKey of the output you're signing for.</p> * * @param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input. * @param redeemScript the bytes that should be in the given input during signing. * @param type Should be SigHash.ALL * @param anyoneCanPay should be false. */ public synchronized Sha256Hash hashForSignature(int inputIndex, byte[] redeemScript, SigHash type, boolean anyoneCanPay) { byte sigHashType = (byte) TransactionSignature.calcSigHashValue(type, anyoneCanPay); return hashForSignature(inputIndex, redeemScript, sigHashType); } /** * <p>Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction * is simplified is specified by the type and anyoneCanPay parameters.</p> * * <p>This is a low level API and when using the regular {@link Wallet} class you don't have to call this yourself. * When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output * the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the * scriptPubKey of the output you're signing for.</p> * * @param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input. * @param redeemScript the script that should be in the given input during signing. * @param type Should be SigHash.ALL * @param anyoneCanPay should be false. */ public synchronized Sha256Hash hashForSignature(int inputIndex, Script redeemScript, SigHash type, boolean anyoneCanPay) { int sigHash = TransactionSignature.calcSigHashValue(type, anyoneCanPay); return hashForSignature(inputIndex, redeemScript.getProgram(), (byte) sigHash); } /** * This is required for signatures which use a sigHashType which cannot be represented using SigHash and anyoneCanPay * See transaction c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73, which has sigHashType 0 */ public synchronized Sha256Hash hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType) { // The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of // the purposes of the code in this method: // // https://en.bitcoin.it/wiki/Contracts try { // Store all the input scripts and clear them in preparation for signing. If we're signing a fresh // transaction that step isn't very helpful, but it doesn't add much cost relative to the actual // EC math so we'll do it anyway. // // Also store the input sequence numbers in case we are clearing them with SigHash.NONE/SINGLE byte[][] inputScripts = new byte[inputs.size()][]; long[] inputSequenceNumbers = new long[inputs.size()]; for (int i = 0; i < inputs.size(); i++) { inputScripts[i] = inputs.get(i).getScriptBytes(); inputSequenceNumbers[i] = inputs.get(i).getSequenceNumber(); inputs.get(i).setScriptBytes(TransactionInput.EMPTY_ARRAY); } // This step has no purpose beyond being synchronized with the reference clients bugs. OP_CODESEPARATOR // is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1. // It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to // the design we use today where scripts are executed independently but share a stack. This left the // OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually // ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't // do it, we could split off the main chain. connectedScript = Script.removeAllInstancesOfOp(connectedScript, ScriptOpCodes.OP_CODESEPARATOR); // Set the input to the script of its output. Satoshi does this but the step has no obvious purpose as // the signature covers the hash of the prevout transaction which obviously includes the output script // already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written. TransactionInput input = inputs.get(inputIndex); input.setScriptBytes(connectedScript); ArrayList<TransactionOutput> outputs = this.outputs; if ((sigHashType & 0x1f) == (SigHash.NONE.ordinal() + 1)) { // SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a "blank cheque". this.outputs = new ArrayList<TransactionOutput>(0); // The signature isn't broken by new versions of the transaction issued by other parties. for (int i = 0; i < inputs.size(); i++) if (i != inputIndex) inputs.get(i).setSequenceNumber(0); } else if ((sigHashType & 0x1f) == (SigHash.SINGLE.ordinal() + 1)) { // SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output). if (inputIndex >= this.outputs.size()) { // The input index is beyond the number of outputs, it's a buggy signature made by a broken // Bitcoin implementation. The reference client also contains a bug in handling this case: // any transaction output that is signed in this case will result in both the signed output // and any future outputs to this public key being steal-able by anyone who has // the resulting signature and the public key (both of which are part of the signed tx input). // Put the transaction back to how we found it. // // TODO: Only allow this to happen if we are checking a signature, not signing a transactions for (int i = 0; i < inputs.size(); i++) { inputs.get(i).setScriptBytes(inputScripts[i]); inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]); } this.outputs = outputs; // Satoshis bug is that SignatureHash was supposed to return a hash and on this codepath it // actually returns the constant "1" to indicate an error, which is never checked for. Oops. return new Sha256Hash("0100000000000000000000000000000000000000000000000000000000000000"); } // In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before // that position are "nulled out". Unintuitively, the value in a "null" transaction is set to -1. this.outputs = new ArrayList<TransactionOutput>(this.outputs.subList(0, inputIndex + 1)); for (int i = 0; i < inputIndex; i++) this.outputs.set(i, new TransactionOutput(params, this, Coin.NEGATIVE_SATOSHI, new byte[] {})); // The signature isn't broken by new versions of the transaction issued by other parties. for (int i = 0; i < inputs.size(); i++) if (i != inputIndex) inputs.get(i).setSequenceNumber(0); } ArrayList<TransactionInput> inputs = this.inputs; if ((sigHashType & SIGHASH_ANYONECANPAY_VALUE) == SIGHASH_ANYONECANPAY_VALUE) { // SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals // of other inputs. For example, this is useful for building assurance contracts. this.inputs = new ArrayList<TransactionInput>(); this.inputs.add(input); } ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? 256 : length + 4); bitcoinSerialize(bos); // We also have to write a hash type (sigHashType is actually an unsigned char) uint32ToByteStreamLE(0x000000ff & sigHashType, bos); // Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out // however then we would expect that it is IS reversed. Sha256Hash hash = new Sha256Hash(doubleDigest(bos.toByteArray())); bos.close(); // Put the transaction back to how we found it. this.inputs = inputs; for (int i = 0; i < inputs.size(); i++) { inputs.get(i).setScriptBytes(inputScripts[i]); inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]); } this.outputs = outputs; return hash; } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { uint32ToByteStreamLE(version, stream); stream.write(new VarInt(inputs.size()).encode()); for (TransactionInput in : inputs) in.bitcoinSerialize(stream); stream.write(new VarInt(outputs.size()).encode()); for (TransactionOutput out : outputs) out.bitcoinSerialize(stream); uint32ToByteStreamLE(lockTime, stream); } /** * Transactions can have an associated lock time, specified either as a block height or in seconds since the * UNIX epoch. A transaction is not allowed to be confirmed by miners until the lock time is reached, and * since Bitcoin 0.8+ a transaction that did not end its lock period (non final) is considered to be non * standard and won't be relayed or included in the memory pool either. */ public long getLockTime() { maybeParse(); return lockTime; } /** * Transactions can have an associated lock time, specified either as a block height or in seconds since the * UNIX epoch. A transaction is not allowed to be confirmed by miners until the lock time is reached, and * since Bitcoin 0.8+ a transaction that did not end its lock period (non final) is considered to be non * standard and won't be relayed or included in the memory pool either. */ public void setLockTime(long lockTime) { unCache(); // TODO: Consider checking that at least one input has a non-final sequence number. this.lockTime = lockTime; } /** * @return the version */ public long getVersion() { maybeParse(); return version; } /** Returns an unmodifiable view of all inputs. */ public List<TransactionInput> getInputs() { maybeParse(); return Collections.unmodifiableList(inputs); } /** Returns an unmodifiable view of all outputs. */ public List<TransactionOutput> getOutputs() { maybeParse(); return Collections.unmodifiableList(outputs); } /** * <p>Returns the list of transacion outputs, whether spent or unspent, that match a wallet by address or that are * watched by a wallet, i.e., transaction outputs whose script's address is controlled by the wallet and transaction * outputs whose script is watched by the wallet.</p> * * @param transactionBag The wallet that controls addresses and watches scripts. * @return linked list of outputs relevant to the wallet in this transaction */ public List<TransactionOutput> getWalletOutputs(TransactionBag transactionBag){ maybeParse(); List<TransactionOutput> walletOutputs = new LinkedList<TransactionOutput>(); Coin v = Coin.ZERO; for (TransactionOutput o : outputs) { if (!o.isMineOrWatched(transactionBag)) continue; walletOutputs.add(o); } return walletOutputs; } /** Randomly re-orders the transaction outputs: good for privacy */ public void shuffleOutputs() { maybeParse(); Collections.shuffle(outputs); } /** Same as getInputs().get(index). */ public TransactionInput getInput(long index) { maybeParse(); return inputs.get((int)index); } /** Same as getOutputs().get(index) */ public TransactionOutput getOutput(long index) { maybeParse(); return outputs.get((int)index); } /** Returns the confidence object that is owned by this transaction object. */ public synchronized TransactionConfidence getConfidence() { if (confidence == null) { confidence = new TransactionConfidence(getHash()); } return confidence; } /** Check if the transaction has a known confidence */ public synchronized boolean hasConfidence() { return confidence != null && confidence.getConfidenceType() != TransactionConfidence.ConfidenceType.UNKNOWN; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Transaction other = (Transaction) o; return getHash().equals(other.getHash()); } @Override public int hashCode() { return getHash().hashCode(); } /** * Ensure object is fully parsed before invoking java serialization. The backing byte array * is transient so if the object has parseLazy = true and hasn't invoked checkParse yet * then data will be lost during serialization. */ private void writeObject(ObjectOutputStream out) throws IOException { maybeParse(); out.defaultWriteObject(); } /** * Gets the count of regular SigOps in this transactions */ public int getSigOpCount() throws ScriptException { maybeParse(); int sigOps = 0; for (TransactionInput input : inputs) sigOps += Script.getSigOpCount(input.getScriptBytes()); for (TransactionOutput output : outputs) sigOps += Script.getSigOpCount(output.getScriptBytes()); return sigOps; } /** * <p>Checks the transaction contents for sanity, in ways that can be done in a standalone manner. * Does <b>not</b> perform all checks on a transaction such as whether the inputs are already spent. * Specifically this method verifies:</p> * * <ul> * <li>That there is at least one input and output.</li> * <li>That the serialized size is not larger than the max block size.</li> * <li>That no outputs have negative value.</li> * <li>That the outputs do not sum to larger than the max allowed quantity of coin in the system.</li> * <li>If the tx is a coinbase tx, the coinbase scriptSig size is within range. Otherwise that there are no * coinbase inputs in the tx.</li> * </ul> * * @throws VerificationException */ public void verify() throws VerificationException { maybeParse(); if (inputs.size() == 0 || outputs.size() == 0) throw new VerificationException.EmptyInputsOrOutputs(); if (this.getMessageSize() > Block.MAX_BLOCK_SIZE) throw new VerificationException.LargerThanMaxBlockSize(); Coin valueOut = Coin.ZERO; HashSet<TransactionOutPoint> outpoints = new HashSet<TransactionOutPoint>(); for (TransactionInput input : inputs) { if (outpoints.contains(input.getOutpoint())) throw new VerificationException.DuplicatedOutPoint(); outpoints.add(input.getOutpoint()); } try { for (TransactionOutput output : outputs) { if (output.getValue().signum() < 0) // getValue() can throw IllegalStateException throw new VerificationException.NegativeValueOutput(); valueOut = valueOut.add(output.getValue()); // Duplicate the MAX_MONEY check from Coin.add() in case someone accidentally removes it. if (valueOut.compareTo(NetworkParameters.MAX_MONEY) > 0) throw new IllegalArgumentException(); } } catch (IllegalStateException e) { throw new VerificationException.ExcessiveValue(); } catch (IllegalArgumentException e) { throw new VerificationException.ExcessiveValue(); } if (isCoinBase()) { if (inputs.get(0).getScriptBytes().length < 2 || inputs.get(0).getScriptBytes().length > 100) throw new VerificationException.CoinbaseScriptSizeOutOfRange(); } else { for (TransactionInput input : inputs) if (input.isCoinBase()) throw new VerificationException.UnexpectedCoinbaseInput(); } } /** * <p>A transaction is time locked if at least one of its inputs is non-final and it has a lock time</p> * * <p>To check if this transaction is final at a given height and time, see {@link Transaction#isFinal(int, long)} * </p> */ public boolean isTimeLocked() { if (getLockTime() == 0) return false; for (TransactionInput input : getInputs()) if (input.hasSequence()) return true; return false; } /** * <p>Returns true if this transaction is considered finalized and can be placed in a block. Non-finalized * transactions won't be included by miners and can be replaced with newer versions using sequence numbers. * This is useful in certain types of <a href="http://en.bitcoin.it/wiki/Contracts">contracts</a>, such as * micropayment channels.</p> * * <p>Note that currently the replacement feature is disabled in the Satoshi client and will need to be * re-activated before this functionality is useful.</p> */ public boolean isFinal(int height, long blockTimeSeconds) { long time = getLockTime(); if (time < (time < LOCKTIME_THRESHOLD ? height : blockTimeSeconds)) return true; if (!isTimeLocked()) return true; return false; } /** * Returns either the lock time as a date, if it was specified in seconds, or an estimate based on the time in * the current head block if it was specified as a block time. */ public Date estimateLockTime(AbstractBlockChain chain) { if (lockTime < LOCKTIME_THRESHOLD) return chain.estimateBlockTime((int)getLockTime()); else return new Date(getLockTime()*1000); } /** * Returns the purpose for which this transaction was created. See the javadoc for {@link Purpose} for more * information on the point of this field and what it can be. */ public Purpose getPurpose() { return purpose; } /** * Marks the transaction as being created for the given purpose. See the javadoc for {@link Purpose} for more * information on the point of this field and what it can be. */ public void setPurpose(Purpose purpose) { this.purpose = purpose; } /** * Getter for {@link #exchangeRate}. */ @Nullable public ExchangeRate getExchangeRate() { return exchangeRate; } /** * Setter for {@link #exchangeRate}. */ public void setExchangeRate(ExchangeRate exchangeRate) { this.exchangeRate = exchangeRate; } /** * Returns the transaction {@link #memo}. */ public String getMemo() { return memo; } /** * Set the transaction {@link #memo}. It can be used to record the memo of the payment request that initiated the * transaction. */ public void setMemo(String memo) { this.memo = memo; } }
apache-2.0
s3git/s3git-go
internal/config/config.go
5595
/* * Copyright 2016 Frank Wessels <fwessels@xs4all.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package config import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "os" "strings" ) const S3GIT_CONFIG = ".s3git.config" const S3GIT_DIR = ".s3git" const CONFIG = "config" const REMOTE_S3 = "s3" const REMOTE_FAKE = "fake" const REMOTE_ACD = "acd" const REMOTE_DYNAMODB = "dynamodb" const LeafSizeMinimum = 1024 const LeafSizeDefault = 5 * 1024 * 1024 const MaxRepoSizeMinimum = 1024 * 1024 const MaxRepoSizeDefault = 25 * 1024 * 1024 * 1024 var Config ConfigObject type ConfigObject struct { Version int `json:"s3gitVersion"` Type string `json:"s3gitType"` // config BasePath string `json:"s3gitBasePath"` LeafSize uint32 `json:"s3gitLeafSize"` MaxRepoSize uint64 `json:"s3gitMaxRepoSize"` RollingHashBits int `json:"s3gitRollingHashBits"` RollingHashMin int `json:"s3gitRollingHashMin"` Remotes []RemoteObject `json:"s3gitRemotes"` } // Base object for Remotes type RemoteObject struct { Name string `json:"Name"` Type string `json:"Type"` Hydrate bool `json:"Hydrate"` // Remote object for S3 S3Bucket string `json:"S3Bucket"` S3Region string `json:"S3Region"` S3AccessKey string `json:"S3AccessKey"` S3SecretKey string `json:"S3SecretKey"` S3Endpoint string `json:"S3Endpoint"` // Remote object for DynamoDB DynamoDbTable string `json:"DynamoDbTable"` DynamoDbRegion string `json:"DynamoDbRegion"` DynamoDbAccessKey string `json:"DynamoDbAccessKey"` DynamoDbSecretKey string `json:"DynamoDbSecretKey"` MinioInsecure bool `json:"MinioInsecure"` AcdRefreshToken string `json:"AcdRefreshToken"` // Remote object for fake backend FakeDirectory string `json:"FakeDirectory"` } func getConfigFile(dir string) string { return dir + "/" + S3GIT_CONFIG } func LoadConfig(dir string) (bool, error) { configFile := getConfigFile(dir) byteConfig, err := ioutil.ReadFile(configFile) if err != nil { // No config found, fine, ignore return false, nil } dec := json.NewDecoder(strings.NewReader(string(byteConfig))) if err := dec.Decode(&Config); err != nil { return false, err } if Config.LeafSize == 0 { // If unspecified, set to default Config.LeafSize = LeafSizeDefault } if Config.MaxRepoSize == 0 { // If unspecified, set to default Config.MaxRepoSize = MaxRepoSizeDefault } return true, nil } func SaveConfig(dir string, leafSize uint32, maxRepoSize uint64) error { configObject := ConfigObject{Version: 1, Type: CONFIG, BasePath: dir} if leafSize == 0 { configObject.LeafSize = LeafSizeDefault } else if leafSize < LeafSizeMinimum { configObject.LeafSize = LeafSizeMinimum } else { configObject.LeafSize = leafSize } if maxRepoSize == 0 { configObject.MaxRepoSize = MaxRepoSizeDefault } else if maxRepoSize < MaxRepoSizeMinimum { configObject.MaxRepoSize = MaxRepoSizeMinimum } else { configObject.MaxRepoSize = maxRepoSize } return saveConfig(configObject, []RemoteObject{}) } func SaveConfigFromUrl(url, dir, accessKey, secretKey, endpoint string, leafSize uint32, maxRepoSize uint64) error { err := SaveConfig(dir, leafSize, maxRepoSize) if err != nil { return err } remote, err := CreateRemote("primary", url, accessKey, secretKey, endpoint) if err != nil { return err } err = AddRemote(remote) if err != nil { return err } return nil } func saveConfig(configObject ConfigObject, remotes []RemoteObject) error { for _, r := range remotes { configObject.Remotes = append(configObject.Remotes, r) } buf := new(bytes.Buffer) encoder := json.NewEncoder(buf) if err := encoder.Encode(configObject); err != nil { return err } // Save config to file err := ioutil.WriteFile(getConfigFile(configObject.BasePath), buf.Bytes(), os.ModePerm) if err != nil { return err } // Reload config _, err = LoadConfig(configObject.BasePath) if err != nil { return err } return nil } func AddRemote(remote *RemoteObject) error { for _, r := range Config.Remotes { if r.Name == remote.Name { return errors.New(fmt.Sprintf("Remote already exists with name: %s", remote.Name)) } } // TODO: Remove restriction for just a single remote if len(Config.Remotes) >= 1 { return errors.New("Current restriction applies of one remote only (to be lifted)") } remotes := []RemoteObject{} remotes = append(remotes, *remote) return saveConfig(Config, remotes) } func AddFakeRemote(name, directory string) error { for _, r := range Config.Remotes { if r.Name == name { return errors.New(fmt.Sprintf("Remote already exists with name: %s", name)) } } // TODO: Remove restriction for just a single remote if len(Config.Remotes) >= 1 { return errors.New("Current restriction applies of one remote only (to be lifted)") } remotes := []RemoteObject{} remotes = append(remotes, RemoteObject{Name: "fake", Type: REMOTE_FAKE, FakeDirectory: directory}) return saveConfig(Config, remotes) }
apache-2.0
yangzhiye/NLPCC2017-task3
extract_keywords_cal_summary_by_snownlp.py
2221
#-*- coding:utf-8 -*- from gensim import models,corpora from textrank4zh import TextRank4Keyword from snownlp import SnowNLP import get_data import re import heapq def get_max_k_tuple_list (tuple_list , k): return heapq.nlargest(k , tuple_list , key = lambda x : x[1]) def get_stopwords_list(): filepath = "./stopword.txt" f = open(filepath) stopwords_list = [] for i,line in enumerate(f.readlines()): stopwords_list.append(line.decode("utf8")) f.close() return stopwords_list def get_index_of_summary(article,k): list_word = article k = len(article)/k article = ''.join(article) s = SnowNLP(article.decode("utf8")) keyword_list = s.keywords(k) s = " ".join(list_word).replace("\n","") cal_list = [] for i,sen in enumerate(re.split(',|。|:|;|?|!',s)): sen_list = sen.split(' ') temp_list = [] temp_value = 0.0 n = 0 for j , word in enumerate(sen_list): if word in keyword_list: temp_list.insert(j,1) else: temp_list.insert(j,0) length = 0 for k in temp_list: length += 1 if k==1: n += 1 try: temp_value = n*n*1.0/length except: temp_value = 0 sen = ''.join(sen.split()) sen = re.sub("\d{4,}",'',sen) cal_list.append((i,temp_value,sen)) cal_list = sorted(cal_list,key=lambda x : (-x[1],x[0])) all_size = 0 ans_list = [] for t in cal_list: if all_size+len(t[2].decode("utf8"))+1 <= 60 and t[1]>0: ans_list.append(t) all_size+=(len(t[2].decode("utf8"))+1) ans_list = sorted(ans_list,key=lambda x : (x[0])) ans = "" for i,t in enumerate(ans_list): if i == len(ans_list)-1: ans+=t[2] ans+="。" else: ans+=t[2] ans+="," return ans def use_snownlp_cal_summary( test_filepath , result_filepath , k): list_test_article = get_data.get_cut_data_list_list(test_filepath) result_f = open(result_filepath,"w+") for i , article in enumerate(list_test_article): ans = get_index_of_summary(article , k) print i,ans result_f.write(ans+"\n") result_f.close() if __name__ == "__main__": test_filepath = "./data/cut_article_test.txt" for k in range(10,20): result_filepath = "./result/EK_snownlp_result/0521_k=%d.txt"%(k) use_snownlp_cal_summary(test_filepath , result_filepath , k)
apache-2.0
IS-ENES-Data/submission_forms
dkrz_forms/wflow_handler.py
2324
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 26 16:46:24 2017 workflow handler: helper functions to update and process workflow forms @author: stephan """ from datetime import datetime from dkrz_forms import form_handler def get_wflow_description(form): wflow_steps = {} for (short_name,long_name) in form.workflow: wflow_steps[long_name] = short_name return wflow_steps def rename_action(action,form): ''' convinience function to map short names to lang wflow step namees" ''' wflow_dict = get_wflow_description(form) if action not in list(wflow_dict.values()): if action in list(wflow_dict.keys()): action = wflow_dict[action] else: print("Error: wrong action name, should be one of: ",list(wflow_dict.values())) return action def start_action(action,form, my_name): action = rename_action(action,form) wflow_step = getattr(form,action) # set status messages: form.status = action wflow_step.activity.status ="1:in-progress" wflow_step.activity.error_status="0:open" wflow_step.entity_out.status="1:stored" wflow_step.entity_out.check_status="0:open" # set start information: wflow_step.agent.responsible_person = my_name wflow_step.activity.start_time = str(datetime.now()) # store_info saved_form = form_handler.save_form(form,my_name+": " + action +" started") return saved_form def update_action(action,form, my_name): action = rename_action(action,form) wflow_step = getattr(form,action) saved_form = form_handler.save_form(form,my_name+": " + action + " updated") return saved_form def finish_action(action,form, my_name,report): action = rename_action(action,form) wflow_step = getattr(form,action) wflow_step.activity.status ="4:closed" wflow_step.activity.error_status="1:ok" wflow_step.entity_out.status="1:stored" wflow_step.entity_out.check_status="3:ok" wflow_step.entity_out.report=report wflow_step.activity.end_time = str(datetime.now()) wflow_step.activity.timestamp = str(datetime.now()) saved_form = form_handler.save_form(form,my_name+": " + action + " finished") return saved_form
apache-2.0
torrances/swtk-commons
commons-dict-wiktionary/src/main/java/org/swtk/commons/dict/wiktionary/generated/p/d/c/WiktionaryPDC000.java
1001
package org.swtk.commons.dict.wiktionary.generated.p.d.c; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.swtk.common.dict.dto.wiktionary.Entry; import com.trimc.blogger.commons.utils.GsonUtils; public class WiktionaryPDC000 { private static Map<String, Entry> map = new HashMap<String, Entry>(); static { add("pdca", "{\"term\":\"pdca\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"the cycle of Plan-do|Do-check|Check-act|Act, four-step solving process typically used in quality control\", \"priority\":1}]}, \"synonyms\":{}}"); } private static void add(String term, String json) { map.put(term, GsonUtils.toObject(json, Entry.class)); } public static Entry get(String term) { return map.get(term); } public static boolean has(String term) { return null != get(term); } public static Collection<String> terms() { return map.keySet(); } }
apache-2.0
gracefullife/gerrit
gerrit-httpd/src/main/java/com/google/gerrit/httpd/raw/RobotsServlet.java
3167
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.httpd.raw; import com.google.common.io.ByteStreams; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.jgit.lib.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This class provides a mechanism to use a configurable robots.txt file, * outside of the .war of the application. In order to configure it add the * following to the <code>httpd</code> section of the <code>gerrit.conf</code> * file: * * <pre> * [httpd] * robotsFile = etc/myrobots.txt * </pre> * * If the specified file name is relative it will resolved as a sub directory of * the site directory, if it is absolute it will be used as is. * * If the specified file doesn't exist or isn't readable the servlet will * default to the <code>robots.txt</code> file bundled with the .war file of the * application. */ @SuppressWarnings("serial") @Singleton public class RobotsServlet extends HttpServlet { private static final Logger log = LoggerFactory.getLogger(RobotsServlet.class); private final File robotsFile; @Inject RobotsServlet(@GerritServerConfig final Config config, final SitePaths sitePaths) { File file = sitePaths.resolve( config.getString("httpd", null, "robotsFile")); if (file != null && (!file.exists() || !file.canRead())) { log.warn("Cannot read httpd.robotsFile, using default"); file = null; } robotsFile = file; } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { rsp.setContentType("text/plain"); InputStream in = openRobotsFile(); try { OutputStream out = rsp.getOutputStream(); try { ByteStreams.copy(in, out); } finally { out.close(); } } finally { in.close(); } } private InputStream openRobotsFile() { if (robotsFile != null) { try { return new FileInputStream(robotsFile); } catch (IOException e) { log.warn("Cannot read " + robotsFile + "; using default", e); } } return getServletContext().getResourceAsStream("/robots.txt"); } }
apache-2.0
jcmore2/AppCrash
appcrash/src/main/java/com/jcmore2/appcrash/AppCrash.java
7362
package com.jcmore2.appcrash; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; /** * Created by jcmore2 on 28/7/15. * AppCrash let you relaunch the app and manage crash message when your app has an exception. */ public class AppCrash { private static final String TAG = "AppCrash"; private static Application application; private static AppCrash sInstance; private static Intent service; protected static Class<? extends Activity> initActivity; protected static String initActivityName; protected static int contentLayoutView = 0; protected static int backgroundColor = 0; protected static final String CONTENT = "CONTENT"; protected static final String BG_COLOR = "BG_COLOR"; protected static final String INIT_ACTIVITY = "INIT_ACTIVITY"; protected static boolean showDialog = false; private static AppCrashListener mListener; /** * Init the AppCrash instance * * @param context context * @return instance */ public static AppCrash init(Context context) { if (sInstance == null) { sInstance = new AppCrash(context); } return sInstance; } /** * get the AppCrash instance * * @return instance */ public static AppCrash get() { if (sInstance == null) { throw new IllegalStateException( "AppCrash is not initialised - invoke " + "at least once with parameterised init/get"); } return sInstance; } /** * Set Content view * * @param resourceLayout layout * @return instance */ public static AppCrash withView(int resourceLayout) { contentLayoutView = resourceLayout; return sInstance; } /** * Set Background color view * * @param color color * @return instance */ public static AppCrash withBackgroundColor(int color) { backgroundColor = color; return sInstance; } /** * Set Activity to init App when crash * * @param activity activity * @return instance */ public static AppCrash withInitActivity(Class<? extends Activity> activity) { initActivity = activity; initActivityName = activity.getName(); return sInstance; } /** * ShowDialog * * @return instance */ public static AppCrash showDialog() { showDialog = true; return sInstance; } /** * ShowDialog * * @param listener listener */ public static void setListener(AppCrashListener listener) { mListener = listener; } /** * Constructor * * @param context context */ private AppCrash(Context context) { try { if (context == null) { Log.e(TAG, "Cant init, context must not be null"); } else { application = (Application) context.getApplicationContext(); final Thread.UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); // setup handler for uncaught exception Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { traceExcetion(ex); if (mListener != null) mListener.onAppCrash(ex); if (showDialog) { if (initActivity != null) { launch(initActivity); } else { launch(getLauncherActivity(application)); } launchService(); } else { launch(createAppCrashActivity()); } android.os.Process.killProcess(android.os.Process.myPid()); System.exit(10); // re-throw critical exception further to the os (important) defaultUEH.uncaughtException(thread, ex); } }); BackgroundManager.init(application).registerListener(new BackgroundManager.Listener() { @Override public void onBecameForeground(Activity activity) { } @Override public void onBecameBackground(Activity activity) { if (service != null) application.stopService(service); } }); } } catch (Exception e) { e.printStackTrace(); } } /** * Write exception throw in Log * * @param ex exception * @return string */ public static String traceExcetion(Throwable ex) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); ex.printStackTrace(printWriter); String stacktrace = result.toString(); Log.e(TAG, "ERROR ---> " + stacktrace); return stacktrace; } /** * This method return default AppCrashActivity * * @return class */ private static Class<? extends Activity> createAppCrashActivity() { return AppCrashActivity.class; } /** * This Method return default App launcher activity * * @param context context * @return class */ @SuppressWarnings("unchecked") protected static Class<? extends Activity> getLauncherActivity(Context context) { Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); if (intent != null) { try { return (Class<? extends Activity>) Class.forName(intent.getComponent().getClassName()); } catch (ClassNotFoundException e) { Log.e(TAG, "Error", e); } } return null; } /** * Launch the activity with params * * @param activity activity */ protected static void launch(Class<? extends Activity> activity) { final Intent intent = new Intent(application, activity); intent.putExtra(CONTENT, contentLayoutView); intent.putExtra(BG_COLOR, backgroundColor); intent.putExtra(INIT_ACTIVITY, initActivityName); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); application.startActivity(intent); } /** * Launch service with params */ private static void launchService() { service = new Intent(application, AppCrashService.class); service.putExtra(CONTENT, contentLayoutView); service.putExtra(BG_COLOR, backgroundColor); application.startService(service); } public interface AppCrashListener { void onAppCrash(Throwable ex); } }
apache-2.0
pinch-perfect/Infrastructure-As-Code
InfrastructureAsCode.Core/Reports/o365rwsclient/TenantReport/ConnectionByClientTypeDaily.cs
193
using System; namespace InfrastructureAsCode.Core.Reports.o365rwsclient.TenantReport { [Serializable] public class ConnectionbyClientTypeDaily : ConnectionByClientType { } }
apache-2.0
shibathethinker/ChimeraCRM
OnLine/OnLine/Pages/Popups/Purchase/AllRequirement_Specification_Show_Feat.aspx.cs
2695
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Collections; using BackEndObjects; using ActionLibrary; /* THIS CLASS IS NOT BEING USED CURRENTLY AS THE INNER GRID IS WORKING FINE. * In current scenario this page will never be called - kept just for reference */ namespace OnLine.Pages.Popups.Purchase { public partial class AllRequirement_Specification_Show_Feat : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { fillGrid(); } } protected void fillGrid() { String selectedProdCat = Session[SessionFactory.ALL_PURCHASE_ALL_REQUIREMENT_SHOW_FEAT_SELECTED_PRODCAT].ToString(); ArrayList reqrSpecList = (ArrayList)Session[SessionFactory.ALL_PURCHASE_ALL_REQUIREMENT_REQR_SPEC]; DataTable dtSpec = new DataTable(); dtSpec.Columns.Add("Hidden"); dtSpec.Columns.Add("FeatName"); dtSpec.Columns.Add("SpecText"); dtSpec.Columns.Add("FromSpec"); dtSpec.Columns.Add("ToSpec"); int rowCount = 0; for (int j = 0; j < reqrSpecList.Count; j++) { BackEndObjects.Requirement_Spec reqrSpecObj = (BackEndObjects.Requirement_Spec)reqrSpecList[j]; if (reqrSpecObj.getProdCatId().Equals(selectedProdCat)) { dtSpec.Rows.Add(); String featName = BackEndObjects.Features.getFeaturebyIdwoSpecDB(reqrSpecObj.getFeatId()).getFeatureName(); dtSpec.Rows[rowCount]["Hidden"] = reqrSpecObj.getFeatId(); dtSpec.Rows[rowCount]["FeatName"] = (featName != null ? featName.Trim() : ""); dtSpec.Rows[rowCount]["SpecText"] = reqrSpecObj.getSpecText(); if (!reqrSpecObj.getFromSpecId().Equals("")) dtSpec.Rows[rowCount]["FromSpec"] = BackEndObjects.Specifications.getSpecificationDetailbyIdDB(reqrSpecObj.getFromSpecId()).getSpecName(); if (!reqrSpecObj.getToSpecId().Equals("")) dtSpec.Rows[rowCount]["ToSpec"] = BackEndObjects.Specifications.getSpecificationDetailbyIdDB(reqrSpecObj.getToSpecId()).getSpecName(); rowCount++; } } GridView_Spec.DataSource = dtSpec; GridView_Spec.DataBind(); GridView_Spec.Columns[1].Visible = false; } } }
apache-2.0
consulo/consulo-scala
src/org/jetbrains/plugins/scala/lang/scaladoc/lexer/docsyntax/ScaladocSyntaxElementType.java
1347
package org.jetbrains.plugins.scala.lang.scaladoc.lexer.docsyntax; import com.intellij.psi.tree.IElementType; import org.jetbrains.plugins.scala.lang.scaladoc.lexer.ScalaDocElementType; import org.jetbrains.plugins.scala.lang.scaladoc.lexer.ScalaDocTokenType; /** * User: Dmitry Naidanov * Date: 29.10.11 */ public class ScaladocSyntaxElementType extends ScalaDocElementType{ private final int flagConst; public ScaladocSyntaxElementType(String debugName, int flagConst) { super(debugName); this.flagConst = flagConst; } public int getFlagConst() { return flagConst; } @Override public String toString() { return super.toString() + " " + (~(getFlagConst() - 1) & getFlagConst()); } public static boolean canClose(IElementType opening, IElementType closing) { if (opening.getClass() != ScaladocSyntaxElementType.class || closing.getClass() != ScaladocSyntaxElementType.class) { return false; } if (opening == ScalaDocTokenType.DOC_LINK_TAG || opening == ScalaDocTokenType.DOC_HTTP_LINK_TAG) { return closing == ScalaDocTokenType.DOC_LINK_CLOSE_TAG; } else if (opening == ScalaDocTokenType.VALID_DOC_HEADER) { return (closing == ScalaDocTokenType.DOC_HEADER) || (closing == ScalaDocTokenType.VALID_DOC_HEADER); } else { return opening == closing; } } }
apache-2.0