text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
package at.fhjoanneum.ippr.communicator.composer; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xembly.Directives; import org.xembly.ImpossibleModificationException; import org.xembly.Xembler; import at.fhjoanneum.ippr.communicator.composer.datatype.ComposerUtils; import at.fhjoanneum.ippr.communicator.global.GlobalKey; import at.fhjoanneum.ippr.communicator.persistence.objects.DataType; import at.fhjoanneum.ippr.communicator.persistence.objects.datatypecomposer.DataTypeComposer; import at.fhjoanneum.ippr.communicator.persistence.objects.internal.InternalData; import at.fhjoanneum.ippr.communicator.persistence.objects.internal.InternalObject; import at.fhjoanneum.ippr.communicator.persistence.objects.protocol.MessageProtocol; import at.fhjoanneum.ippr.communicator.persistence.objects.protocol.MessageProtocolField; public class XmlComposer implements Composer { private static final Logger LOG = LoggerFactory.getLogger(XmlComposer.class); private String transferIdKey = "TRANSFER_ID"; @Override public String compose(final String transferId, final InternalData data, final MessageProtocol messageProtocol, final Map<DataType, DataTypeComposer> composer, final Map<String, String> configuration) { transferIdKey = configuration.get(GlobalKey.TRANSFER_ID); final Directives root = new Directives().add(messageProtocol.getExternalName()); root.attr(transferIdKey, transferId); final String currentMessage = messageProtocol.getInternalName(); final InternalObject internalObject = data.getObjects().get(currentMessage); for (final MessageProtocolField protocolField : messageProtocol.getFields()) { if (protocolField.isMandatory() && ((internalObject == null) || (internalObject.getFields().get(protocolField.getInternalName()) == null))) { throw new IllegalArgumentException("Could not find protocol field for internal name [" + protocolField.getInternalName() + "]"); } String value = StringUtils.EMPTY; if (internalObject != null) { value = internalObject.getFields().get(protocolField.getInternalName()) != null ? internalObject.getFields().get(protocolField.getInternalName()).getValue() : protocolField.getDefaultValue(); } value = ComposerUtils.compose(value, protocolField.getDataType()); root.attr(protocolField.getExternalName(), value); } try { return new Xembler(root).xml(); } catch (final ImpossibleModificationException e) { LOG.error(e.getMessage()); return null; } } @Override public String getDescription() { // TODO Auto-generated method stub return null; } }
Java
CL
8106527f2f5f456aab295d701241618d3acc86089a3ac79753145e4571e5d77e
package com.prolog.eis.wcs.impl; import com.prolog.eis.wcs.common.Constant; import com.prolog.eis.wcs.dao.WCSCommandMapper; import com.prolog.eis.wcs.dao.WCSHistoryCommandMapper; import com.prolog.eis.wcs.model.WCSCommand; import com.prolog.eis.wcs.model.WCSHistoryCommand; import com.prolog.eis.wcs.service.IWCSCommandService; import com.prolog.eis.wcs.service.IWCSService; import com.prolog.eis.wcs.service.IWCSTaskService; import com.prolog.framework.common.message.RestMessage; import com.prolog.framework.core.exception.ParameterException; import com.prolog.framework.core.restriction.Criteria; import com.prolog.framework.core.restriction.Order; import com.prolog.framework.core.restriction.Restrictions; import com.prolog.framework.utils.JsonUtils; import com.prolog.framework.utils.MapUtils; import com.prolog.framework.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class WCSCommandServiceImpl implements IWCSCommandService { @Autowired private WCSCommandMapper mapper; @Autowired private WCSHistoryCommandMapper historyMapper; @Autowired private IWCSService wcsService; @Autowired private IWCSTaskService taskService; @Override public void add(WCSCommand command) throws Exception { if(command==null || StringUtils.isBlank(command.getTaskId())) throw new ParameterException("参数不能为空"); if(command.getType() != Constant.COMMAND_TYPE_LIGHT && command.getType()!=Constant.COMMAND_TYPE_REQUEST_ORDER_BOX && StringUtils.isBlank(command.getContainerNo()) ){ throw new ParameterException("命令容器号不能为空"); } if(this.getByContainerNo(command.getContainerNo()).size()>0){ throw new ParameterException("同时作业的容器不能重复"); } mapper.save(command); } @Override public void delete(int id) { mapper.deleteById(id,WCSCommand.class); } @Override public List<WCSCommand> getAll() { return mapper.findByMap(null,WCSCommand.class); } /** * 通过求余拆分记录集 * @param denominator 分母 * @param remainder 余数 * @return * @throws Exception */ @Override public List<WCSCommand> getByMod(int denominator, int remainder) throws Exception{ return mapper.getByMod(denominator,remainder); } /** * 发送指令 * * @param command * @throws Exception */ @Override @Transactional public boolean sendCommand(WCSCommand command) throws Exception { if(command==null || command.getType()<1 || StringUtils.isBlank(command.getTaskId())){ throw new ParameterException("参数无效"); } RestMessage<String> result = null; switch(command.getType()){ case Constant.COMMAND_TYPE_CK: //出库 同步 result = wcsService.sendContainerTask(command.getTaskId(),Constant.TASK_TYPE_CK,command.getContainerNo(),command.getAddress(),command.getTarget(),command.getWeight(),command.getPriority(),command.getStatus()); break; case Constant.COMMAND_TYPE_LIGHT: //亮光 同步 if (command.getLights() == null) { result = wcsService.light(command.getStationNo(), new String[]{}); } else { result = wcsService.light(command.getStationNo(), command.getLights().split(",")); } break; case Constant.COMMAND_TYPE_REQUEST_ORDER_BOX: if(StringUtils.isBlank(command.getTarget())) throw new ParameterException("目标地址为空"); result = wcsService.requestOrderBox(command.getTaskId(),command.getTarget()); //当命令接收成功时,开始wctask taskService.startTask(command.getTaskId()); break; case Constant.COMMAND_TYPE_RK: if(StringUtils.isBlank(command.getTarget())||StringUtils.isBlank(command.getAddress())) throw new ParameterException("目标地址或起始地址为空"); result =wcsService.sendContainerTask(command.getTaskId(),Constant.TASK_TYPE_RK,command.getContainerNo(),command.getAddress(),command.getTarget(),"0","99",command.getStatus()); break; case Constant.COMMAND_TYPE_XZ: if(StringUtils.isBlank(command.getTarget())||StringUtils.isBlank(command.getAddress())) throw new ParameterException("目标地址或起始地址为空"); result = wcsService.lineMove(command.getTaskId(),command.getAddress(),command.getTarget(),command.getContainerNo(),Constant.TASK_TYPE_XZ,0); break; case Constant.COMMAND_TYPE_HC: if (command.getTargetLayer()==0 ||command.getSourceLayer()==0){ throw new ParameterException("原层或目标层不能为空"); } result = wcsService.moveCar(command.getTaskId(),0,command.getSourceLayer(),command.getTargetLayer()); break; default: throw new RuntimeException("命令类型错误"); } WCSHistoryCommand his = command.getHistoryCommand(); his.setSendTime(new Date()); his.setResult(JsonUtils.toString(result)); historyMapper.save(his); if(result.isSuccess() && command.getId()>0){ try { this.delete(command.getId()); }catch (Exception e){ e.printStackTrace(); } } return result.isSuccess(); } public WCSCommand getById(int id){ return mapper.findById(id,WCSCommand.class); } @Override public boolean sendHCCommand(String taskId, int sourceLayer, int targetLayer) throws Exception { WCSCommand cmd = new WCSCommand(); cmd.setTaskId(taskId); cmd.setType(Constant.COMMAND_TYPE_HC); cmd.setSourceLayer(sourceLayer); cmd.setTargetLayer(targetLayer); return this.sendCommand(cmd); } @Override public List<WCSCommand> getByContainerNo(String containerNo){ return mapper.findByMap(MapUtils.put("containerNo",containerNo).getMap(),WCSCommand.class); } /** * 根据类型查询任务 * * @param type * @return */ @Override public List<WCSCommand> getByType(int type) { return mapper.findByMap(MapUtils.put("type",type).getMap(),WCSCommand.class); } /** * 根据目标点获取命令 * * @param target * @return */ @Override public List<WCSCommand> getByTarget(String target) { if(StringUtils.isBlank(target)){ return new ArrayList<>(); } Criteria ctr = Criteria.forClass(WCSCommand.class); ctr.setOrder(Order.newInstance().asc("createTime")); ctr.setRestriction(Restrictions.eq("target",target)); return mapper.findByCriteria(ctr); } @Override public long getCountByTarget(String target) { if(StringUtils.isBlank(target)){ return 0; } Criteria ctr = Criteria.forClass(WCSCommand.class); ctr.setOrder(Order.newInstance().asc("createTime")); ctr.setRestriction(Restrictions.eq("target",target)); return mapper.findCountByCriteria(ctr); } /** * 获取命令排除目标点 * * @param targets * @return */ @Override public List<WCSCommand> getExceptTargets(String[] targets) { if(targets==null || targets.length==0){ return new ArrayList<>(); } Criteria ctr = Criteria.forClass(WCSCommand.class); ctr.setOrder(Order.newInstance().asc("createTime")); ctr.setRestriction(Restrictions.notIn("target", String.valueOf(targets))); return mapper.findByCriteria(ctr); } /** * 发送亮灯指令 * * @param taskId * @param stationNo * @param lights * @return */ @Override public boolean sendLightCommand(String taskId, String stationNo, String lights) throws Exception { WCSCommand cmd = new WCSCommand(); cmd.setTaskId(taskId); cmd.setType(Constant.COMMAND_TYPE_LIGHT); cmd.setStationNo(stationNo); cmd.setLights(lights); return this.sendCommand(cmd); } /** * 发送行走指令 * * @param taskId * @param address * @param target * @param containerNo * @return */ @Override public boolean sendXZCommand(String taskId, String address, String target, String containerNo) throws Exception { WCSCommand cmd = new WCSCommand(); cmd.setTaskId(taskId); cmd.setType(Constant.COMMAND_TYPE_XZ); cmd.setAddress(address); cmd.setTarget(target); cmd.setContainerNo(containerNo); return this.sendCommand(cmd); } /** * 发送出库指令 * * @param taskId * @param containerNo * @param address * @param target * @param weight * @param priority * @return */ @Override public boolean sendCKCommand(String taskId, String containerNo, String address, String target, String weight, String priority) throws Exception { WCSCommand cmd = new WCSCommand(); cmd.setTaskId(taskId); cmd.setType(Constant.COMMAND_TYPE_CK); cmd.setAddress(address); cmd.setTarget(target); cmd.setContainerNo(containerNo); cmd.setWeight(weight); cmd.setPriority(priority); cmd.setStatus(0); return this.sendCommand(cmd); } /** * 发送入库指令 * * @param taskId * @param containerNo * @param address * @param target * @param weight * @param priority * @return */ @Override public boolean sendRKCommand(String taskId, String containerNo, String address, String target, String weight, String priority) throws Exception { WCSCommand cmd = new WCSCommand(); cmd.setTaskId(taskId); cmd.setType(Constant.COMMAND_TYPE_RK); cmd.setAddress(address); cmd.setTarget(target); cmd.setContainerNo(containerNo); cmd.setWeight(weight); cmd.setPriority(priority); cmd.setStatus(0); return this.sendCommand(cmd); } /** * 发送订单框请求指令 * * @param taskId * @return */ @Override public boolean sendOrderBoxReqCommand(String taskId,String target) throws Exception{ WCSCommand cmd = new WCSCommand(); cmd.setTaskId(taskId); cmd.setTarget(target); cmd.setType(Constant.COMMAND_TYPE_REQUEST_ORDER_BOX); return this.sendCommand(cmd); } }
Java
CL
48c4d494739b7e858882338e9b477ce8fba3255015d54378c8380ba8b802ca5f
/* * 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 com.jfoenix.controls.cells.editors.base; import javafx.beans.value.ChangeListener; import javafx.event.EventHandler; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Region; /** * <h1>Editor Builder</h1> * this a builder interface to create editors for treetableview/tableview cells * <p> * * @author Shadi Shaheen * @version 1.0 * @since 2016-03-09 */ public interface EditorNodeBuilder<T> { /** * This method is called when the editor start editing the cell * * @return Nothing */ void startEdit(); /** * This method is called when the editor cancel editing the cell * * @return Nothing */ void cancelEdit(); /** * This method is called when the editor updates the visuals of the cell * * @param item the new item for the cell * @param empty whether or not this cell holds a value * @return Nothing */ void updateItem(T item, boolean empty); /** * This method is will create the editor node to be displayed when * editing the cell * * @param value current value of the cell * @param keyEventsHandler keyboard events handler for the cell * @param focusChangeListener focus change listener for the cell * @return the editor node */ Region createNode(T value, EventHandler<KeyEvent> keyEventsHandler, ChangeListener<Boolean> focusChangeListener); /** * This method is used to update the editor node to corresponde with * the new value of the cell * * @param value the new value of the cell * @return Nothing */ void setValue(T value); /** * This method is used to get the current value from the editor node * * @return T the value of the editor node */ T getValue(); /** * This method will be called before committing the new value of the cell * * @return Nothing * @throws Exception */ void validateValue() throws Exception; /** * set ui nodes to null for memory efficiency */ void nullEditorNode(); }
Java
CL
4ca65907e4c5708eb40ac62cb76a9a89e4a332d71639216cb8514953672dc0af
/** * Controller for given a train a route */ package ctc; import trackModel.Block; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.stage.Stage; public class RouteTrainFormController extends FormController { @FXML private ComboBox<String> trackListBox, stationListBox, trainListBox; private static boolean DEBUG = true; /** * Fill dropdowns with information */ public void initialize() { if (ctcOffice != null) { // Add the list of trains for (String trainName : ctcOffice.trains.keySet()) { String trainString = "#" + ctcOffice.trains.get(trainName) + " " + trainName; trainListBox.getItems().add(trainString); } // Add the list of tracks for (TrackLayout track : ctcOffice.tracks.values()) { String trackName = track.toString(); trackListBox.getItems().add(trackName); } // Populate list of stations from the selected track trackListBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { public void changed(ObservableValue<? extends String> selected, String oldTrack, String newTrack) { // Clear the list stationListBox.getItems().clear(); int numBlocks = ctcOffice.tracks.get(newTrack).getNumBlocks(); for (int i = 0; i < numBlocks; i++ ) { // Grab block from track controller Block block = ctcOffice.transitSystem.ctcGetBlock(newTrack, i); if (block.isStation()) { String stationName = block.getStationName(); if (!stationListBox.getItems().contains(stationName)) stationListBox.getItems().add(stationName); } } } }); } } @Override @FXML protected void submit() { String selectedTrain = trainListBox.getValue(); String[] stringParts = selectedTrain.split(" "); selectedTrain = stringParts[1]; String selectedTrack = trackListBox.getValue(); String selectedStation = stationListBox.getValue(); Route route; // If route exists, just update it if (ctcOffice.routes.containsKey(selectedTrain)) route = ctcOffice.routes.get(selectedTrain); // Route doesn't exist, make new one else { int trainId = ctcOffice.trains.get(selectedTrain); route = new Route(trainId, ctcOffice.transitSystem.ctcGetTrack(selectedTrack)); } route.addStation(selectedStation); // Update route in CTC's route database ctcOffice.routes.put(selectedTrain, route); // Update train position int trainID = Integer.parseInt(stringParts[0].substring(1)); ctcOffice.transitSystem.ctcSetInitialPosition(trainID, selectedTrack); // Send route to track controller ctcOffice.transitSystem.ctcSendRoute(trainID, route); // Figure out a way to display this System.out.println(route); // Close window Stage currStage = (Stage) trackListBox.getScene().getWindow(); currStage.close(); } /** * Route train outside of CTC gui * @param selectedTrain * @param selectedTrack * @param selectedStation * @param ctc * @return */ public static boolean routeTrain(String selectedTrain, String selectedTrack, String selectedStation, CTC ctc) { try { Route route; // Modifying name so it's easier to deal with selectedTrain = selectedTrain.trim(); selectedTrain = selectedTrain.replace(" ", ""); int trainId = ctc.trains.get(selectedTrain); // If route exists, just update it if (ctc.routes.containsKey(selectedTrain)) route = ctc.routes.get(selectedTrain); // Route doesn't exist, make new one else { route = new Route(trainId, ctc.transitSystem.ctcGetTrack(selectedTrack)); } route.addStation(selectedStation); // Update route in CTC's route database ctc.routes.put(selectedTrain, route); // Update train position ctc.transitSystem.ctcSetInitialPosition(trainId, selectedTrack); // Send route to track controller ctc.transitSystem.ctcSendRoute(trainId, route); return true; } catch (Exception e) { System.out.println("Error in routing train"); if (DEBUG) e.printStackTrace(); return false; } } }
Java
CL
e1af4bb15f0e02edf11ce0fb9ec16c9eb1a7c8880f664fadaba4e786398d3157
package com.navercorp.pinpoint.plugin.kafka.interceptor.util; import com.navercorp.pinpoint.plugin.kafka.KafkaVersion; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.FetchResponseData; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map; public final class KafkaResponseDataProviderFactory { public static KafkaResponseDataProvider getResponseDataProvider(int version, Method responseDataMethod) { switch (version) { case KafkaVersion.KAFKA_VERSION_LOW: return new Kafka2ResponseDataProvider(responseDataMethod); case KafkaVersion.KAFKA_VERSION_3_1: return new Kafka3ResponseDataProvider(); default: return new UnsupportedResponseDataProvider(); } } }
Java
CL
62f361d65296cc304ec193dc1cb7830f6e9130045b03f8b1b051290cae10d59c
/* * 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.aliyuncs.sofa.model.v20190815; import com.aliyuncs.RpcAcsRequest; import java.util.List; import com.aliyuncs.http.MethodType; import com.aliyuncs.sofa.Endpoint; /** * @author auto create * @version */ public class CountLinkeLinktWorkitemgroupRequest extends RpcAcsRequest<CountLinkeLinktWorkitemgroupResponse> { private Long expectedAtAfter; private List<String> assignedToIdsRepeatLists; private String subject; private String ccsOption; private String relatedProjectSign; private List<Long> tagsRepeatLists; private List<String> signNotInRepeatLists; private Long statusId; private String assignedToId; private String keyword; private String parentSign; private String iterationSign; private String signPathNotLike; private String orderBy; private List<String> stampsRepeatLists; private Long rootLength; private Long templateId; private List<Long> priorityIdsRepeatLists; private List<Long> statusIdsRepeatLists; private Long page; private Long begin; private String customFieldsSearchFormMap; private String relevantProjectSign; private List<String> templateLabelsRepeatLists; private Long updatedAtAfter; private List<String> signListRepeatLists; private String stamp; private String templateLabel; private String tagsOption; private String parentProjectSign; private Long createdAtBefore; private List<String> creatorsRepeatLists; private List<String> ccsRepeatLists; private Long pageSize; private String projectSign; private List<Long> templateIdsRepeatLists; private String creator; private Long expectedAtBefore; private String relevantUid; private Long length; private String moduleIdsOption; private String groupBy; private Long updatedAtBefore; private Long createdAtAfter; private List<Long> moduleIdsRepeatLists; private Long rootBegin; private String showMode; private List<Long> stageListRepeatLists; private List<String> projectSignsRepeatLists; public CountLinkeLinktWorkitemgroupRequest() { super("SOFA", "2019-08-15", "CountLinkeLinktWorkitemgroup", "sofa"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public Long getExpectedAtAfter() { return this.expectedAtAfter; } public void setExpectedAtAfter(Long expectedAtAfter) { this.expectedAtAfter = expectedAtAfter; if(expectedAtAfter != null){ putBodyParameter("ExpectedAtAfter", expectedAtAfter.toString()); } } public List<String> getAssignedToIdsRepeatLists() { return this.assignedToIdsRepeatLists; } public void setAssignedToIdsRepeatLists(List<String> assignedToIdsRepeatLists) { this.assignedToIdsRepeatLists = assignedToIdsRepeatLists; if (assignedToIdsRepeatLists != null) { for (int i = 0; i < assignedToIdsRepeatLists.size(); i++) { putBodyParameter("AssignedToIdsRepeatList." + (i + 1) , assignedToIdsRepeatLists.get(i)); } } } public String getSubject() { return this.subject; } public void setSubject(String subject) { this.subject = subject; if(subject != null){ putBodyParameter("Subject", subject); } } public String getCcsOption() { return this.ccsOption; } public void setCcsOption(String ccsOption) { this.ccsOption = ccsOption; if(ccsOption != null){ putBodyParameter("CcsOption", ccsOption); } } public String getRelatedProjectSign() { return this.relatedProjectSign; } public void setRelatedProjectSign(String relatedProjectSign) { this.relatedProjectSign = relatedProjectSign; if(relatedProjectSign != null){ putBodyParameter("RelatedProjectSign", relatedProjectSign); } } public List<Long> getTagsRepeatLists() { return this.tagsRepeatLists; } public void setTagsRepeatLists(List<Long> tagsRepeatLists) { this.tagsRepeatLists = tagsRepeatLists; if (tagsRepeatLists != null) { for (int i = 0; i < tagsRepeatLists.size(); i++) { putBodyParameter("TagsRepeatList." + (i + 1) , tagsRepeatLists.get(i)); } } } public List<String> getSignNotInRepeatLists() { return this.signNotInRepeatLists; } public void setSignNotInRepeatLists(List<String> signNotInRepeatLists) { this.signNotInRepeatLists = signNotInRepeatLists; if (signNotInRepeatLists != null) { for (int i = 0; i < signNotInRepeatLists.size(); i++) { putBodyParameter("SignNotInRepeatList." + (i + 1) , signNotInRepeatLists.get(i)); } } } public Long getStatusId() { return this.statusId; } public void setStatusId(Long statusId) { this.statusId = statusId; if(statusId != null){ putBodyParameter("StatusId", statusId.toString()); } } public String getAssignedToId() { return this.assignedToId; } public void setAssignedToId(String assignedToId) { this.assignedToId = assignedToId; if(assignedToId != null){ putBodyParameter("AssignedToId", assignedToId); } } public String getKeyword() { return this.keyword; } public void setKeyword(String keyword) { this.keyword = keyword; if(keyword != null){ putBodyParameter("Keyword", keyword); } } public String getParentSign() { return this.parentSign; } public void setParentSign(String parentSign) { this.parentSign = parentSign; if(parentSign != null){ putBodyParameter("ParentSign", parentSign); } } public String getIterationSign() { return this.iterationSign; } public void setIterationSign(String iterationSign) { this.iterationSign = iterationSign; if(iterationSign != null){ putBodyParameter("IterationSign", iterationSign); } } public String getSignPathNotLike() { return this.signPathNotLike; } public void setSignPathNotLike(String signPathNotLike) { this.signPathNotLike = signPathNotLike; if(signPathNotLike != null){ putBodyParameter("SignPathNotLike", signPathNotLike); } } public String getOrderBy() { return this.orderBy; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; if(orderBy != null){ putBodyParameter("OrderBy", orderBy); } } public List<String> getStampsRepeatLists() { return this.stampsRepeatLists; } public void setStampsRepeatLists(List<String> stampsRepeatLists) { this.stampsRepeatLists = stampsRepeatLists; if (stampsRepeatLists != null) { for (int i = 0; i < stampsRepeatLists.size(); i++) { putBodyParameter("StampsRepeatList." + (i + 1) , stampsRepeatLists.get(i)); } } } public Long getRootLength() { return this.rootLength; } public void setRootLength(Long rootLength) { this.rootLength = rootLength; if(rootLength != null){ putBodyParameter("RootLength", rootLength.toString()); } } public Long getTemplateId() { return this.templateId; } public void setTemplateId(Long templateId) { this.templateId = templateId; if(templateId != null){ putBodyParameter("TemplateId", templateId.toString()); } } public List<Long> getPriorityIdsRepeatLists() { return this.priorityIdsRepeatLists; } public void setPriorityIdsRepeatLists(List<Long> priorityIdsRepeatLists) { this.priorityIdsRepeatLists = priorityIdsRepeatLists; if (priorityIdsRepeatLists != null) { for (int i = 0; i < priorityIdsRepeatLists.size(); i++) { putBodyParameter("PriorityIdsRepeatList." + (i + 1) , priorityIdsRepeatLists.get(i)); } } } public List<Long> getStatusIdsRepeatLists() { return this.statusIdsRepeatLists; } public void setStatusIdsRepeatLists(List<Long> statusIdsRepeatLists) { this.statusIdsRepeatLists = statusIdsRepeatLists; if (statusIdsRepeatLists != null) { for (int i = 0; i < statusIdsRepeatLists.size(); i++) { putBodyParameter("StatusIdsRepeatList." + (i + 1) , statusIdsRepeatLists.get(i)); } } } public Long getPage() { return this.page; } public void setPage(Long page) { this.page = page; if(page != null){ putBodyParameter("Page", page.toString()); } } public Long getBegin() { return this.begin; } public void setBegin(Long begin) { this.begin = begin; if(begin != null){ putBodyParameter("Begin", begin.toString()); } } public String getCustomFieldsSearchFormMap() { return this.customFieldsSearchFormMap; } public void setCustomFieldsSearchFormMap(String customFieldsSearchFormMap) { this.customFieldsSearchFormMap = customFieldsSearchFormMap; if(customFieldsSearchFormMap != null){ putBodyParameter("CustomFieldsSearchFormMap", customFieldsSearchFormMap); } } public String getRelevantProjectSign() { return this.relevantProjectSign; } public void setRelevantProjectSign(String relevantProjectSign) { this.relevantProjectSign = relevantProjectSign; if(relevantProjectSign != null){ putBodyParameter("RelevantProjectSign", relevantProjectSign); } } public List<String> getTemplateLabelsRepeatLists() { return this.templateLabelsRepeatLists; } public void setTemplateLabelsRepeatLists(List<String> templateLabelsRepeatLists) { this.templateLabelsRepeatLists = templateLabelsRepeatLists; if (templateLabelsRepeatLists != null) { for (int i = 0; i < templateLabelsRepeatLists.size(); i++) { putBodyParameter("TemplateLabelsRepeatList." + (i + 1) , templateLabelsRepeatLists.get(i)); } } } public Long getUpdatedAtAfter() { return this.updatedAtAfter; } public void setUpdatedAtAfter(Long updatedAtAfter) { this.updatedAtAfter = updatedAtAfter; if(updatedAtAfter != null){ putBodyParameter("UpdatedAtAfter", updatedAtAfter.toString()); } } public List<String> getSignListRepeatLists() { return this.signListRepeatLists; } public void setSignListRepeatLists(List<String> signListRepeatLists) { this.signListRepeatLists = signListRepeatLists; if (signListRepeatLists != null) { for (int i = 0; i < signListRepeatLists.size(); i++) { putBodyParameter("SignListRepeatList." + (i + 1) , signListRepeatLists.get(i)); } } } public String getStamp() { return this.stamp; } public void setStamp(String stamp) { this.stamp = stamp; if(stamp != null){ putBodyParameter("Stamp", stamp); } } public String getTemplateLabel() { return this.templateLabel; } public void setTemplateLabel(String templateLabel) { this.templateLabel = templateLabel; if(templateLabel != null){ putBodyParameter("TemplateLabel", templateLabel); } } public String getTagsOption() { return this.tagsOption; } public void setTagsOption(String tagsOption) { this.tagsOption = tagsOption; if(tagsOption != null){ putBodyParameter("TagsOption", tagsOption); } } public String getParentProjectSign() { return this.parentProjectSign; } public void setParentProjectSign(String parentProjectSign) { this.parentProjectSign = parentProjectSign; if(parentProjectSign != null){ putBodyParameter("ParentProjectSign", parentProjectSign); } } public Long getCreatedAtBefore() { return this.createdAtBefore; } public void setCreatedAtBefore(Long createdAtBefore) { this.createdAtBefore = createdAtBefore; if(createdAtBefore != null){ putBodyParameter("CreatedAtBefore", createdAtBefore.toString()); } } public List<String> getCreatorsRepeatLists() { return this.creatorsRepeatLists; } public void setCreatorsRepeatLists(List<String> creatorsRepeatLists) { this.creatorsRepeatLists = creatorsRepeatLists; if (creatorsRepeatLists != null) { for (int i = 0; i < creatorsRepeatLists.size(); i++) { putBodyParameter("CreatorsRepeatList." + (i + 1) , creatorsRepeatLists.get(i)); } } } public List<String> getCcsRepeatLists() { return this.ccsRepeatLists; } public void setCcsRepeatLists(List<String> ccsRepeatLists) { this.ccsRepeatLists = ccsRepeatLists; if (ccsRepeatLists != null) { for (int i = 0; i < ccsRepeatLists.size(); i++) { putBodyParameter("CcsRepeatList." + (i + 1) , ccsRepeatLists.get(i)); } } } public Long getPageSize() { return this.pageSize; } public void setPageSize(Long pageSize) { this.pageSize = pageSize; if(pageSize != null){ putBodyParameter("PageSize", pageSize.toString()); } } public String getProjectSign() { return this.projectSign; } public void setProjectSign(String projectSign) { this.projectSign = projectSign; if(projectSign != null){ putBodyParameter("ProjectSign", projectSign); } } public List<Long> getTemplateIdsRepeatLists() { return this.templateIdsRepeatLists; } public void setTemplateIdsRepeatLists(List<Long> templateIdsRepeatLists) { this.templateIdsRepeatLists = templateIdsRepeatLists; if (templateIdsRepeatLists != null) { for (int i = 0; i < templateIdsRepeatLists.size(); i++) { putBodyParameter("TemplateIdsRepeatList." + (i + 1) , templateIdsRepeatLists.get(i)); } } } public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; if(creator != null){ putBodyParameter("Creator", creator); } } public Long getExpectedAtBefore() { return this.expectedAtBefore; } public void setExpectedAtBefore(Long expectedAtBefore) { this.expectedAtBefore = expectedAtBefore; if(expectedAtBefore != null){ putBodyParameter("ExpectedAtBefore", expectedAtBefore.toString()); } } public String getRelevantUid() { return this.relevantUid; } public void setRelevantUid(String relevantUid) { this.relevantUid = relevantUid; if(relevantUid != null){ putBodyParameter("RelevantUid", relevantUid); } } public Long getLength() { return this.length; } public void setLength(Long length) { this.length = length; if(length != null){ putBodyParameter("Length", length.toString()); } } public String getModuleIdsOption() { return this.moduleIdsOption; } public void setModuleIdsOption(String moduleIdsOption) { this.moduleIdsOption = moduleIdsOption; if(moduleIdsOption != null){ putBodyParameter("ModuleIdsOption", moduleIdsOption); } } public String getGroupBy() { return this.groupBy; } public void setGroupBy(String groupBy) { this.groupBy = groupBy; if(groupBy != null){ putBodyParameter("GroupBy", groupBy); } } public Long getUpdatedAtBefore() { return this.updatedAtBefore; } public void setUpdatedAtBefore(Long updatedAtBefore) { this.updatedAtBefore = updatedAtBefore; if(updatedAtBefore != null){ putBodyParameter("UpdatedAtBefore", updatedAtBefore.toString()); } } public Long getCreatedAtAfter() { return this.createdAtAfter; } public void setCreatedAtAfter(Long createdAtAfter) { this.createdAtAfter = createdAtAfter; if(createdAtAfter != null){ putBodyParameter("CreatedAtAfter", createdAtAfter.toString()); } } public List<Long> getModuleIdsRepeatLists() { return this.moduleIdsRepeatLists; } public void setModuleIdsRepeatLists(List<Long> moduleIdsRepeatLists) { this.moduleIdsRepeatLists = moduleIdsRepeatLists; if (moduleIdsRepeatLists != null) { for (int i = 0; i < moduleIdsRepeatLists.size(); i++) { putBodyParameter("ModuleIdsRepeatList." + (i + 1) , moduleIdsRepeatLists.get(i)); } } } public Long getRootBegin() { return this.rootBegin; } public void setRootBegin(Long rootBegin) { this.rootBegin = rootBegin; if(rootBegin != null){ putBodyParameter("RootBegin", rootBegin.toString()); } } public String getShowMode() { return this.showMode; } public void setShowMode(String showMode) { this.showMode = showMode; if(showMode != null){ putBodyParameter("ShowMode", showMode); } } public List<Long> getStageListRepeatLists() { return this.stageListRepeatLists; } public void setStageListRepeatLists(List<Long> stageListRepeatLists) { this.stageListRepeatLists = stageListRepeatLists; if (stageListRepeatLists != null) { for (int i = 0; i < stageListRepeatLists.size(); i++) { putBodyParameter("StageListRepeatList." + (i + 1) , stageListRepeatLists.get(i)); } } } public List<String> getProjectSignsRepeatLists() { return this.projectSignsRepeatLists; } public void setProjectSignsRepeatLists(List<String> projectSignsRepeatLists) { this.projectSignsRepeatLists = projectSignsRepeatLists; if (projectSignsRepeatLists != null) { for (int i = 0; i < projectSignsRepeatLists.size(); i++) { putBodyParameter("ProjectSignsRepeatList." + (i + 1) , projectSignsRepeatLists.get(i)); } } } @Override public Class<CountLinkeLinktWorkitemgroupResponse> getResponseClass() { return CountLinkeLinktWorkitemgroupResponse.class; } }
Java
CL
1644d79259ef32317b8ebd8c7fab76bf89a6707483462f3117d33e5ab13e170f
package org.lacassandra.smooshyfaces.persistence.cassandra; import com.google.inject.Injector; import org.lacassandra.smooshyfaces.persistence.*; import javax.inject.Inject; public class CassandraDAOFactory extends DAOFactory { @Inject protected Injector injector; protected <T extends BaseCassandraDAO> T inject(Class<T> clazz) { return injector.getInstance(clazz); } @Override public UserDAO createUserDAO() { return inject(CassandraUserDAO.class); } @Override public UserSessionDAO createUserSessionDAO() { return inject(CassandraUserSessionDAO.class); } @Override public PictureDAO createPictureDAO() { return inject(CassandraPictureDAO.class); } }
Java
CL
832c96d7b3f86f5a1663a8926061f58065828201b865e2abb72e27d4c4c3cddc
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.connector.integration.test.marketo; import org.json.JSONException; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase; import org.wso2.connector.integration.test.base.RestResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class MarketoConnectorIntegrationTest extends ConnectorIntegrationTestBase { private Map<String, String> esbRequestHeadersMap = new HashMap<String, String>(); private Map<String, String> apiRequestHeadersMap = new HashMap<String, String>(); private Map<String, String> mpRequestHeadersMap = new HashMap<String, String>(); private String multipartProxyUrl; /** * Set up the environment. */ @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { init("marketo-connector-1.0.1-SNAPSHOT"); esbRequestHeadersMap.put("Accept-Charset", "UTF-8"); esbRequestHeadersMap.put("Content-Type", "application/json"); apiRequestHeadersMap.putAll(esbRequestHeadersMap); final String authString = connectorProperties.getProperty("accessToken"); final String authorizationHeader = "Bearer " + authString; apiRequestHeadersMap.put("Authorization", authorizationHeader); String multipartPoxyName = connectorProperties.getProperty("multipartProxyName"); //mpRequestHeadersMap.put("Content-Type",) multipartProxyUrl = getProxyServiceURL(multipartPoxyName); } /** * Positive test case for createAndUpdateLeads method with mandatory parameters. */ @Test(priority = 1, description = "Marketo {createAndUpdateLeads} integration test with mandatory parameters.") public void testCreateAndUpdateLeadsWithMandatoryParameters() throws IOException, JSONException { String methodName = "createAndUpdateLeads"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_createAndUpdateLeads_mandatory.json"); String leadId = esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("id"); connectorProperties.put("leadId", leadId); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lead/" + connectorProperties.getProperty("leadId") + ".json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("id"), connectorProperties.getProperty("leadId")); Assert.assertEquals(apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("firstName"), connectorProperties.getProperty("leadFirstName")); Assert.assertEquals(apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("lastName"), connectorProperties.getProperty("leadLastName")); Assert.assertEquals(apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("email"), connectorProperties.getProperty("leadEmail")); } /** * Positive test case for createAndUpdateLeads method with optional parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithMandatoryParameters"}, description = "Marketo {createAndUpdateLeads} integration test with optional parameters.") public void testCreateAndUpdateLeadsWithOptionalParameters() throws IOException, JSONException { String methodName = "createAndUpdateLeads"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_createAndUpdateLeads_optional.json"); String OptionalLeadId = esbRestResponse.getBody().getJSONArray("result").getJSONObject(1).getString("id"); String OptionalLeadId1 = esbRestResponse.getBody().getJSONArray("result").getJSONObject(2).getString("id"); String OptionalLeadId2 = esbRestResponse.getBody().getJSONArray("result").getJSONObject(3).getString("id"); connectorProperties.put("lLeadId", OptionalLeadId); connectorProperties.put("dLeadId", OptionalLeadId1); connectorProperties.put("rLeadId", OptionalLeadId2); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("status"), "updated"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(1).getString("status"), "created"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(2).getString("status"), "created"); } /** * Negative test case for createAndUpdateLeads method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithMandatoryParameters"}, description = "Marketo {createAndUpdateLeads} integration test with negative case.") public void testCreateAndUpdateLeadsWithNegativeCase() throws IOException, JSONException { String methodName = "createAndUpdateLeads"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_createAndUpdateLeads_negative.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("code"), "1005"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("message"), "Lead already exists"); } /** * Positive test case for getLeadById method with mandatory parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getLeadById} integration test with mandatory parameters.") public void testGetLeadByIdWithMandatoryParameters() throws IOException, JSONException { String methodName = "getLeadById"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getLeadById_mandatory.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lead/" + connectorProperties.getProperty("leadId") + ".json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Positive test case for getLeadById method with optional parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getLeadById} integration test with optional parameters.") public void testGetLeadByIdWithOptionalParameters() throws IOException, JSONException { String methodName = "getLeadById"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getLeadById_optional.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lead/" + connectorProperties.getProperty("leadId") + ".json?fields=" + connectorProperties.getProperty("fields"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Negative test case for getLeadById method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getLeadById} integration test with negative case.") public void testGetLeadByIdWithNegativeCase() throws IOException, JSONException { String methodName = "getLeadById"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getLeadById_Negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lead/" + connectorProperties.getProperty("invalidLeadId") + ".json?fields=" + connectorProperties.getProperty("fields"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); } /** * Positive test case for getMultipleLeadsByFilterType method with mandatory parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getMultipleLeadsByFilterType} integration test with mandatory parameters.") public void testGetMultipleLeadsByFilterTypeWithMandatoryParameters() throws IOException, JSONException { String methodName = "getMultipleLeadsByFilterType"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByFilterType_mandatory.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads.json?filterType=" + connectorProperties.getProperty("filterType") + "&filterValues=" + connectorProperties.getProperty("leadId"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Positive test case for getMultipleLeadsByFilterType method with optional parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getMultipleLeadsByFilterType} integration test with optional parameters.") public void testGetMultipleLeadsByFilterTypeWithOptionalParameters() throws IOException, JSONException { String methodName = "getMultipleLeadsByFilterType"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByFilterType_optional.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads.json?filterType=" + connectorProperties.getProperty("filterType") + "&filterValues=" + connectorProperties.getProperty("leadId") + "&fields=" + connectorProperties.getProperty("fields") + "&batchSize=" + connectorProperties.getProperty("batchSize"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Negative test case for getMultipleLeadsByFilterType method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getMultipleLeadsByFilterType} integration test with negative case.") public void testGetMultipleLeadsByFilterTypeWithNegativeCase() throws IOException, JSONException { String methodName = "getMultipleLeadsByFilterType"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByFilterType_Negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads.json?filterType=" + connectorProperties.getProperty("invalidFilterType") + "&filterValues=" + connectorProperties.getProperty("leadId"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").toString(), apiRestResponse.getBody().getJSONArray("errors").toString()); } /** * Positive test case for getMultipleLeadsByListId method with mandatory parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getMultipleLeadsByListId} integration test with mandatory parameters.") public void testGetMultipleLeadsByListIdWithMandatoryParameters() throws IOException, JSONException { String methodName = "getMultipleLeadsByListId"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByListId_mandatory.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/list/" + connectorProperties.getProperty("listId") + "/leads.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Positive test case for getMultipleLeadsByListId method with optional parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getMultipleLeadsByListId} integration test with optional parameters.") public void testGetMultipleLeadsByListIdWithOptionalParameters() throws IOException, JSONException { String methodName = "getMultipleLeadsByListId"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByListId_optional.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/list/" + connectorProperties.getProperty("listId") + "/leads.json?fields=" + connectorProperties.getProperty("fields") + "&batchSize=" + connectorProperties.getProperty("batchSize"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Negative test case for getMultipleLeadsByListId method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getMultipleLeadsByListId} integration test with negative case.") public void testGetMultipleLeadsByListIdWithNegativeCase() throws IOException, JSONException { String methodName = "getMultipleLeadsByListId"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByListId_Negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/list/" + connectorProperties.getProperty("invalidListId") + "/leads.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").toString(), apiRestResponse.getBody().getJSONArray("errors").toString()); } /** * Positive test case for getMultipleLeadsByProgramId method with mandatory parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getLeadByProgramId} integration test with mandatory parameters.") public void testGetMultipleLeadsByProgramIdWithMandatoryParameters() throws IOException, JSONException { String methodName = "getMultipleLeadsByProgramId"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByProgramId_mandatory.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads/programs/" + connectorProperties.getProperty("programId") + ".json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); } /** * Positive test case for getMultipleLeadsByProgramId method with optional parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {getMultipleLeadsByProgramId} integration test with optional parameters.") public void testGetMultipleLeadsByProgramIdWithOptionalParameters() throws IOException, JSONException { String methodName = "getMultipleLeadsByProgramId"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByProgramId_optional.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads/programs/" + connectorProperties.getProperty("programId") + ".json?fields=" + connectorProperties.getProperty("fields") + "&batchSize=" + connectorProperties.getProperty("batchSize"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); } /** * Negative test case for getMultipleLeadsByProgramId method. */ @Test(priority = 1, description = "Marketo {getMultipleLeadsByProgramId} integration test with negative case.") public void testGetMultipleLeadsByProgramIdWithNegativeCase() throws IOException, JSONException { String methodName = "getMultipleLeadsByProgramId"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLeadsByProgramId_negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads/programs/" + connectorProperties.getProperty("invalidProgramId") + ".json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").toString(), apiRestResponse.getBody().getJSONArray("errors").toString()); } /** * Positive test case for addLeadsToList method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {addLeadsToList} integration test with positive case.") public void testAddLeadsToListWithPositiveCase() throws IOException, JSONException { String methodName = "addLeadsToList"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_addLeadsToList_positive.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success"), "true"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("status"), "added"); } /** * Negative test case for addLeadsToList method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {addLeadsToList} integration test with negative case.") public void testAddLeadsToListWithNegativeCase() throws IOException, JSONException { String methodName = "addLeadsToList"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_addLeadsToList_Negative.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("code"), "1004"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("message"), "Lead not found"); } /** * Positive test case for memberOfList method. */ @Test(priority = 1, dependsOnMethods = {"testAddLeadsToListWithPositiveCase"}, description = "Marketo {memberOfList} integration test with positive case.") public void testMemberOfListWithPositiveCase() throws IOException, JSONException { String methodName = "memberOfList"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_addLeadsToList_positive.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success"), "true"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("status"), "memberof"); } /** * Negative test case for memberOfList method. */ @Test(priority = 1, dependsOnMethods = {"testAddLeadsToListWithPositiveCase"}, description = "Marketo {addLeadsToList} integration test with negative case.") public void testMemberOfListWithNegativeCase() throws IOException, JSONException { String methodName = "addLeadsToList"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_addLeadsToList_Negative.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("code"), "1004"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("message"), "Lead not found"); } /** * Positive test case for removeLeadsFromList method. */ @Test(priority = 1, dependsOnMethods = {"testMemberOfListWithPositiveCase"}, description = "Marketo {removeLeadsFromList} integration test with positive case.") public void testRemoveLeadsFromListWithPositiveCase() throws IOException, JSONException { String methodName = "removeLeadsFromList"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_addLeadsToList_positive.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success"), "true"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("status"), "removed"); } /** * Negative test case for removeLeadsFromList method. */ @Test(priority = 1, dependsOnMethods = {"testMemberOfListWithPositiveCase"}, description = "Marketo {removeLeadsFromList} integration test with negative case.") public void testRemoveLeadsFromListWithNegativeCase() throws IOException, JSONException { String methodName = "removeLeadsFromList"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_addLeadsToList_Negative.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("code"), "1004"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("message"), "Lead not found"); } /** * Positive test case for associateLead method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {associateLead} integration test with positive case.") public void testAssociateLeadWithPositiveCase() throws IOException, JSONException { String methodName = "associateLead"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_associateLead_positive.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success"), "true"); } /** * Negative test case for associateLead method. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {associateLead} integration test with negative case.") public void testAssociateLeadWithNegativeCase() throws IOException, JSONException { String methodName = "associateLead"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_associateLead_Negative.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("code"), "1004"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message"), "Lead '" + connectorProperties.getProperty("invalidLeadId") + "' not found"); } /** * Positive test case for mergeLead method with mandatory parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {mergeLead} integration test with mandatory parameters.") public void testMergeLeadWithMandatoryParameters() throws IOException, JSONException { String methodName = "mergeLead"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_mergeLead_mandatory.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success"), "true"); } /** * Positive test case for mergeLead method with optional parameters. */ @Test(priority = 1, dependsOnMethods = {"testCreateAndUpdateLeadsWithOptionalParameters"}, description = "Marketo {mergeLead} integration test with optional parameters.") public void testMergeLeadWithOptionalParameters() throws IOException, JSONException { String methodName = "mergeLead"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_mergeLead_optional.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success"), "true"); } /** * Negative test case for mergeLead method. */ @Test(priority = 1, dependsOnMethods = {"testMergeLeadWithOptionalParameters"}, description = "Marketo {mergeLead} integration test with negative case.") public void testMergeLeadWithNegativeCase() throws IOException, JSONException { String methodName = "mergeLead"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_mergeLead_mandatory.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("code"), "1004"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message"), "Lead '" + connectorProperties.getProperty("leadId") + "' not found"); } /** * Positive test case for deleteLead method. */ @Test(priority = 1, dependsOnMethods = {"testMergeLeadWithOptionalParameters"}, description = "Marketo {deleteLead} integration test with positive case.") public void testDeleteLeadWithPositiveCase() throws IOException, JSONException { String methodName = "deleteLead"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_deleteLead_positive.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("status"), "deleted"); } /** * Negative test case for deleteLead method. */ @Test(priority = 1, dependsOnMethods = {"testDeleteLeadWithPositiveCase"}, description = "Marketo {deleteLead} integration test with negative case.") public void testDeleteLeadWithNegativeCase() throws IOException, JSONException { String methodName = "deleteLead"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_deleteLead_positive.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("code"), "1004"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getJSONArray("reasons").getJSONObject(0).getString("message"), "Lead not found"); } /** * Positive test case for getLeadPartitions method. */ @Test(priority = 1, description = "Marketo {getLeadPartitions} integration test with positive case.") public void testGetLeadPartitionsWithPositiveCase() throws IOException, JSONException { String methodName = "getLeadPartitions"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads/partitions.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Positive test case for describe method. */ @Test(priority = 1, description = "Marketo {describe} integration test with positive case.") public void testGetLeadPartitionsWithMandatoryParameters() throws IOException, JSONException { String methodName = "describe"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/leads/describe.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Positive test case for getListById method. */ @Test(priority = 1, description = "Marketo {getListById} integration test with positive case.") public void testGetListByIdWithPositiveCase() throws IOException, JSONException { String methodName = "getListById"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getListById_positive.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lists/" + connectorProperties.getProperty("listId") + ".json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Negative test case for getListById method. */ @Test(priority = 1, description = "Marketo {getListById} integration test with negative case.") public void testGetListByIdWithNegativeCase() throws IOException, JSONException { String methodName = "getListById"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getListById_negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lists/" + connectorProperties.getProperty("invalidListId") + ".json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("errors").getJSONObject(0).toString()); } /** * Positive test case for getMultipleLists method with mandatory parameters. */ @Test(priority = 1, description = "Marketo {getMultipleLists} integration test with mandatory parameters.") public void testGetMultipleListsWithMandatoryParameters() throws IOException, JSONException { String methodName = "getMultipleLists"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lists.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); // Assert.assertEquals(esbRestResponse.getBody().getJSONArray("success").toString(), "true}"); } /** * Positive test case for getMultipleLists method with optional parameters. */ @Test(priority = 1, description = "Marketo {getMultipleLists} integration test with positive case.") public void testGetMultipleListsWithOptionalParameters() throws IOException, JSONException { String methodName = "getMultipleLists"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLists_optional.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lists.json?name=" + connectorProperties.getProperty("listName"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Negative test case for getMultipleLists method. */ @Test(priority = 1, description = "Marketo {getMultipleLists} integration test with negative case.") public void testGetMultipleListsWithNegativeCase() throws IOException, JSONException { String methodName = "getMultipleLists"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleLists_negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/lists.json?name=" + connectorProperties.getProperty("listId"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); } /** * Positive test case for getCampaignById method. */ @Test(priority = 1, description = "Marketo {getCampaignById} integration test with positive case.") public void testGetCampaignByIdWithPositiveCase() throws IOException, JSONException { String methodName = "getCampaignById"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getCampaignById_positive.json"); String campaignName = esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("name"); connectorProperties.put("campaignName", campaignName); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/campaigns.json?id=" + connectorProperties.getProperty("campaignId"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Negative test case for getCampaignById method. */ @Test(priority = 1, description = "Marketo {getListById} integration test with negative case.") public void testGetCampaignByIdWithNegativeCase() throws IOException, JSONException { String methodName = "getCampaignById"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getCampaignById_negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/campaigns.json?id=" + connectorProperties.getProperty("invalidCampaignId"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); } /** * Positive test case for getMultipleCampaigns method with mandatory parameters. */ @Test(priority = 1, dependsOnMethods = {"testGetCampaignByIdWithPositiveCase"}, description = "Marketo {getMultipleCampaigns} integration test with with mandatory parameters.") public void testGetMultipleCampaignsWithMandatoryParameters() throws IOException, JSONException { String methodName = "getMultipleCampaigns"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/campaigns.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Positive test case for getMultipleCampaigns method with optional parameters. */ @Test(priority = 1, dependsOnMethods = {"testGetCampaignByIdWithPositiveCase"}, description = "Marketo {getMultipleCampaigns} integration test with optional parameters") public void testGetMultipleCampaignsWithOptionalParameters() throws IOException, JSONException { String methodName = "getMultipleCampaigns"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleCampaigns_positive.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/campaigns.json?name=" + connectorProperties.getProperty("campaignName"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString(), apiRestResponse.getBody().getJSONArray("result").getJSONObject(0).toString()); } /** * Negative test case for getMultipleCampaigns method. */ @Test(priority = 1, description = "Marketo {getMultipleCampaigns} integration test with negative case.") public void testGetMultipleCampaignsWithNegativeCase() throws IOException, JSONException { String methodName = "getMultipleCampaigns"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getMultipleCampaigns_negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/campaigns.json?name=" + connectorProperties.getProperty("invalidCampaignName"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); } /** * Positive test case for scheduleCampaign method with mandatory parameters. */ @Test(priority = 1, description = "Marketo {scheduleCampaign} integration test with mandatory parameters.") public void testScheduleCampaignMandatoryParameters() throws IOException, JSONException { String methodName = "scheduleCampaign"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_scheduleCampaign_mandatory.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Positive test case for scheduleCampaign method with optional parameters. */ @Test(priority = 1, description = "Marketo {scheduleCampaign} integration test with positive case.") public void testScheduleCampaignWithOptionalParameters() throws IOException, JSONException { String methodName = "scheduleCampaign"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_scheduleCampaign_optional.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Negative test case for scheduleCampaign method. */ @Test(priority = 1, description = "Marketo {scheduleCampaign} integration test with negative case.") public void testScheduleCampaignWithNegativeCase() throws IOException, JSONException { String methodName = "scheduleCampaign"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_scheduleCampaign_negative.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("code"), "1013"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message"), "Campaign not found"); } /** * Positive test case for requestCampaign method with mandatory parameters. */ @Test(priority = 1, description = "Marketo {requestCampaign} integration test with mandatory parameters.") public void testRequestCampaignWithMandatoryParameters() throws IOException, JSONException { String methodName = "requestCampaign"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_requestCampaign_positive.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Negative test case for requestCampaign method. */ @Test(priority = 1, description = "Marketo {requestCampaign} integration test with negative case.") public void testRequestCampaignWithNegativeCase() throws IOException, JSONException { String methodName = "requestCampaign"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_scheduleCampaign_negative.json"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("code"), "1013"); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message"), "Campaign not found"); } /** * Positive test case for getPagingToken method. */ @Test(priority = 1, description = "Marketo {getPagingToken} integration test with positive case.") public void testGetPagingTokenWithPositiveCase() throws IOException, JSONException { String methodName = "getPagingToken"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getPagingToken_positive.json"); String nextPageToken = esbRestResponse.getBody().getString("nextPageToken"); connectorProperties.put("nextPageToken", nextPageToken); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Positive test case for getActivityTypes method. */ @Test(priority = 1, dependsOnMethods = {"testGetPagingTokenWithPositiveCase"}, description = "Marketo {getActivityTypes} integration test with positive case.") public void testGetActivityTypesWithPositiveCase() throws IOException, JSONException { String methodName = "getActivityTypes"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); String activityTypeId = esbRestResponse.getBody().getJSONArray("result").getJSONObject(0).getString("id"); connectorProperties.put("activityTypeId", activityTypeId); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Positive test case for getLeadChanges method. */ @Test(priority = 1, dependsOnMethods = {"testGetActivityTypesWithPositiveCase"}, description = "Marketo {getLeadChanges} integration test with positive case.") public void testGetLeadChangesWithPositiveCase() throws IOException, JSONException { String methodName = "getLeadChanges"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getLeadChanges_mandatory.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Negative test case for getLeadChanges method. */ @Test(priority = 1, dependsOnMethods = {"testGetActivityTypesWithPositiveCase"}, description = "Marketo {getLeadChanges} integration test with negative case.") public void testGetLeadChangesWithNegativeCase() throws IOException, JSONException { String methodName = "getLeadChanges"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getLeadChanges_negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/activities/leadchanges.json?nextPageToken=" + connectorProperties.getProperty("nextPageToken"); RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message"), apiRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message")); } /** * Positive test case for getDeletedLeads method. */ @Test(priority = 1, dependsOnMethods = {"testGetActivityTypesWithPositiveCase"}, description = "Marketo {getDeletedLeads} integration test with positive case.") public void testGetDeletedLeadsWithPositiveCase() throws IOException, JSONException { String methodName = "getDeletedLeads"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getDeletedLeads_mandatory.json"); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Negative test case for getDeletedLeads method. */ @Test(priority = 1, dependsOnMethods = {"testGetActivityTypesWithPositiveCase"}, description = "Marketo {getLeadChanges} integration test with negative case.") public void testGetDeletedLeadsWithNegativeCase() throws IOException, JSONException { String methodName = "getDeletedLeads"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_getDeletedLeads_negative.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/activities/deletedleads.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message"), apiRestResponse.getBody().getJSONArray("errors").getJSONObject(0).getString("message")); } /** * Positive test case for getDailyErrors method. */ @Test(priority = 1, description = "Marketo {getDailyErrors} integration test with positive case.") public void testGetDailyErrorsWithPositiveCase() throws IOException, JSONException { String methodName = "getDailyErrors"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/stats/errors.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Positive test case for getDailyUsage method. */ @Test(priority = 1, description = "Marketo {getDailyUsage} integration test with positive case.") public void testGetDailyUsageWithPositiveCase() throws IOException, JSONException { String methodName = "getDailyUsage"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/stats/usage.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Positive test case for getLast7DaysErrors method. */ @Test(priority = 1, description = "Marketo {getLast7DaysErrors} integration test with positive case.") public void testGetLast7DaysErrorsWithPositiveCase() throws IOException, JSONException { String methodName = "getLast7DaysErrors"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/stats/errors/last7days.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getJSONArray("result").toString(), apiRestResponse.getBody().getJSONArray("result").toString()); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } /** * Positive test case for getLast7DaysUsage method. */ @Test(priority = 1, description = "Marketo {getLast7DaysUsage} integration test with positive case.") public void testGetLast7DaysUsageWithPositiveCase() throws IOException, JSONException { String methodName = "getLast7DaysUsage"; RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(getProxyServiceURL(methodName), "POST", esbRequestHeadersMap, "esb_init.json"); final String apiUrl = connectorProperties.getProperty("marketoInstanceURL") + "/rest/v1/stats/usage/last7days.json"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); Assert.assertEquals(esbRestResponse.getBody().getString("success").toString(), "true"); } }
Java
CL
09844e3c21d70dfc98abd0d25b4f14f5c6b1c250e2dc788140543e3a52259c01
package org.antman.binaryconverter.application.gui; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.input.DragEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Window; import org.antman.binaryconverter.application.converter.Decoder; import org.antman.binaryconverter.application.converter.structure.BinaryStructure; import org.antman.binaryconverter.application.converter.structure.InvalidBinaryStructureException; import org.antman.binaryconverter.application.util.FileHandler; import java.io.*; import java.net.URL; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * @author Brijesh varsani * @version 1.2 */ public class Controller implements Initializable { @FXML public TextArea inputTextArea; @FXML public TextArea outputTextArea; @FXML public ComboBox<String> addComboBox; public ComboBox<Integer> comboBox2; public TextField textFieldOption; public TextArea structureInputArea; public ComboBox<String> varComboBox; public HBox buttonBox; public Button convertButton; public Button importButton; public Button exportButton; private HashMap<String, String> settingsMap; private String tab = ""; @FXML public CheckBox editableCheckBox; @FXML public Button verifyButton; @FXML public VBox vbMenu; FileChooser fileChooser = new FileChooser(); DirectoryChooser directoryChooser = new DirectoryChooser(); ObservableList<String> optt = FXCollections.observableArrayList("Char", "Int", "Float", "Var", "Loop", "EndLoop"); ObservableList<String> varOption = FXCollections.observableArrayList(); FileHandler handler; private int counter = 0; private ArrayList<File> files; private ArrayList<String> outputStrings = new ArrayList<>(); /*------------------------------------------------ Recent file creator ------------------------------------------------- */ File recentFiles = new File("cfg\\recent-structure.txt"); @Override public void initialize(URL location, ResourceBundle resources) { handler = new FileHandler(); addComboBox.setItems(optt); varComboBox.setItems(varOption); files = new ArrayList<>(); addComboBox.setOnAction(action -> { String str = addComboBox.getSelectionModel().getSelectedItem(); if (str.equals("Loop")) { varComboBox.setVisible(true); textFieldOption.setVisible(true); textFieldOption.setPromptText("Enter Number Of Iteration"); } else if (str.equals("Var")) { textFieldOption.setVisible(true); textFieldOption.setPromptText("Enter Variable Name"); varComboBox.setVisible(false); } else { textFieldOption.setVisible(false); varComboBox.setVisible(false); } }); } /* ----------------------------------------------- Private method -------------------------------------------- */ private void structureOpen() { getRecentPath(0); Window stage = vbMenu.getScene().getWindow(); fileChooser.setTitle("Open File"); File file = fileChooser.showOpenDialog(stage); String fileName = file.getAbsolutePath(); try { List<String> strings = handler.readLines(recentFiles); strings.set(0, file.getParentFile().toString()); handler.write(strings, recentFiles); BufferedReader br = new BufferedReader(new FileReader(fileName)); String sr; while ((sr = br.readLine()) != null) { structureInputArea.appendText(sr + "\r\n"); } } catch (IOException e) { e.printStackTrace(); } } /** * 0 - recent struct * 1 - recent input * 2 - recent output */ private File getRecentPath(int which) { File path = null; try { path = new File(handler.readLines(recentFiles).get(which)); if (path != null && path.isDirectory()) fileChooser.setInitialDirectory(path); else fileChooser.setInitialDirectory(new File("c://")); } catch (FileNotFoundException e) { fileChooser.setInitialDirectory(new File("c://")); } catch (Exception e) { fileChooser.setInitialDirectory(new File("c://")); } finally { return path; } } private void inputFileOpen() { getRecentPath(1); Window stage = vbMenu.getScene().getWindow(); fileChooser.setTitle("Open File"); File file = fileChooser.showOpenDialog(stage); try { List<String> strings = handler.readLines(recentFiles); strings.set(1, file.getParentFile().toString()); handler.write(strings, recentFiles); } catch (IOException e) { e.printStackTrace(); } importFile(file); } private void saveFile() { Window stage = vbMenu.getScene().getWindow(); getRecentPath(0); fileChooser.setTitle("Save File"); fileChooser.setInitialFileName("Structure"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Structure", "*.struc")); try { List<String> strings = handler.readLines(recentFiles); File file = fileChooser.showSaveDialog(stage); StringBuilder sb = new StringBuilder(); sb.append(structureInputArea.getText()); strings.set(0, file.getParentFile().toString()); handler.write(strings, recentFiles); FileWriter fileWriter = new FileWriter(file); fileWriter.write(sb.toString()); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } private void importFile(File file) { files.add(file); inputTextArea.appendText(file.getAbsolutePath() + "\n"); } /* ------------------------------------ Drag Drop ----------------------------------- */ public void handleDragOver(DragEvent dragEvent) { if (dragEvent.getDragboard().hasFiles()) { dragEvent.acceptTransferModes(TransferMode.ANY); } } public void handleDragDrop(DragEvent dragEvent) { inputTextArea.appendText(dragEvent.getDragboard().getFiles().stream().map(File::getAbsolutePath).collect(Collectors.joining("\n")) + "\n"); files.addAll(dragEvent.getDragboard().getFiles()); } public void onDragDroppedStructure(DragEvent dragEvent) { structureInputArea.clear(); File file = dragEvent.getDragboard().getFiles().get(0); String fileName = file.getAbsolutePath(); try { BufferedReader br = new BufferedReader(new FileReader(fileName)); String sr; while ((sr = br.readLine()) != null) { structureInputArea.appendText(sr + "\r\n"); } } catch (IOException e) { e.printStackTrace(); } System.out.println(file.getAbsolutePath()); } public void onDragOverStructure(DragEvent dragEvent) { // Drag Drop structure file if (dragEvent.getDragboard().hasFiles()) { dragEvent.acceptTransferModes(TransferMode.ANY); } } /* --------------------------------------------------- Add structure ---------------------------------------------------- */ public void buttonAddMouseClicked() { String str = addComboBox.getSelectionModel().getSelectedItem(); if (!str.equals("Loop") && !str.equals("Var") && !str.equals("EndLoop") && str != null) { addPrimitive(addComboBox.getSelectionModel().getSelectedItem()); } else if (str.equals("Loop")) { addLoop(str); } else if (str.equals("Var")) { addVar(str); } else if (str.equals("EndLoop")) { addEndLoop(str); } } private void addEndLoop(String str) { if (counter >= 1) { tab = tab.substring(0, tab.length() - 2); structureInputArea.appendText(tab + addComboBox.getSelectionModel().getSelectedItem() + "\n"); counter -= 1; } else { Alert.display("Loop Must be include "); } } private void addVar(String str) { String var = textFieldOption.getCharacters().toString(); System.out.println(var); if (!var.isEmpty() && !var.contains(" ") && !var.matches("^[0-9]*$")) { varOption.add(var); structureInputArea.appendText(tab + str + "(" + var + ")\n"); textFieldOption.clear(); } else { textFieldOption.clear(); } } private void addLoop(String str) { String num = textFieldOption.getCharacters().toString(); String varName = varComboBox.getValue(); System.out.println(num); try { if (num.matches("^[0-9]*$") && Integer.parseInt(num) < 10000) { //&& Integer.parseInt(numOrVar +"") < 10000 structureInputArea.appendText(tab + str + "(" + num + ")\n"); } } catch (NumberFormatException e) { if (varName != null) { structureInputArea.appendText(tab + str + "(" + varName + ")\n"); } } finally { textFieldOption.clear(); varComboBox.setAccessibleText(varComboBox.getPromptText()); counter += 1; tab += " "; } } private void addPrimitive(String selectedItem) { if (counter == 0) { structureInputArea.appendText(selectedItem + "\n"); } else { structureInputArea.appendText(tab + selectedItem + "\n"); } } /* ------------------------------------------------------------------- Menu Bar ------------------------------------------------------------------- */ public void inputFileOpenMenu(ActionEvent actionEvent) { inputFileOpen(); } public void menuOpenStructure(ActionEvent actionEvent) { structureOpen(); } public void saveStructureMenu(ActionEvent actionEvent) { saveFile(); } public void saveOutputMenu(ActionEvent actionEvent) { try { exportButtonClicked(null); } catch (IOException e) { e.printStackTrace(); } } public void clearAllMenu(ActionEvent actionEvent) { structureInputArea.clear(); inputTextArea.clear(); outputTextArea.clear(); files.clear(); outputStrings.clear(); } public void helpMenuAction(ActionEvent actionEvent) { Runtime runtime = Runtime.getRuntime(); try { runtime.exec("cmd /c cfg\\file.pdf"); Process pwd = runtime.exec("pwd"); System.out.println(new Scanner(pwd.getInputStream()).nextLine()); } catch (IOException e) { e.printStackTrace(); } } /* ------------------------------------------------------------------------------------------------- Enable Editing for Structure and Input File ------------------------------------------------------------------------------------------------- */ public void editableCheck(ActionEvent actionEvent) { if (editableCheckBox.isSelected()) { inputTextArea.setEditable(true); structureInputArea.setEditable(true); } else { inputTextArea.setEditable(false); structureInputArea.setEditable(false); } } /* ------------------------------------------------------------------------------------------------- Clear Structure ,Input and Output text area ------------------------------------------------------------------------------------------------- */ public void clearStructureButton(MouseEvent mouseEvent) { structureInputArea.clear(); } public void clearAllButton(MouseEvent mouseEvent) { structureInputArea.clear(); inputTextArea.clear(); outputTextArea.clear(); files.clear(); outputStrings.clear(); } public void clearOutputButton(MouseEvent mouseEvent) { outputTextArea.clear(); outputStrings.clear(); outputStrings.clear(); } public void clearInputButton(MouseEvent mouseEvent) { inputTextArea.clear(); files.clear(); } /* ----------------------------------------------------------------------- Verify Button and Save structure button ---------------------------------------------------------------------- */ public void verifyButtonClicked(MouseEvent mouseEvent) { List<String> structureList = Arrays.asList(structureInputArea.getText().split("\n")); boolean success = false; try { BinaryStructure structure = BinaryStructure.getInstance(structureList); success = true; } catch (InvalidBinaryStructureException e) { Alert.display(e.getMessage()); verifyButton.setText("Verify"); } if (success) { verifyButton.setText("Verified"); success = false; } } public void saveAsStructureOnMouseClicked(MouseEvent mouseEvent) { saveFile(); } /* ------------------------------------------------------------------------ Import , Export and Convert Button ------------------------------------------------------------------------- */ public void importButtonClicked(MouseEvent mouseEvent) { inputFileOpen(); } public void convertButtonOnMouseClicked(MouseEvent mouseEvent) { outputTextArea.clear(); HashMap<File, String> encodedDecoded = new HashMap<>(); List<String> structureList = Arrays.asList(structureInputArea.getText().split("\n")); try { System.out.println(files.size()); CountDownLatch latch = new CountDownLatch(files.size()); for (int i = 0; i < files.size(); i++) { File file = files.get(i); outputStrings.add(""); final int notFinal = i; new Thread(() -> { try { Decoder decoder = new Decoder(); BinaryStructure structure = BinaryStructure.getInstance(structureList); System.out.println("Thread "); ByteBuffer buffer = handler.readBytesToBuffer(file); outputStrings.set(notFinal, decoder.decode(structure, buffer)); latch.countDown(); System.out.println(outputStrings); } catch (IOException e) { e.printStackTrace(); } catch (InvalidBinaryStructureException e) { Alert.display(e.getMessage()); System.out.println(e.getMessage()); } }).start(); } latch.await(2 * files.size(), TimeUnit.SECONDS); for (int i = 0; i < files.size(); i++) { outputTextArea.appendText("-----Decoded file - " + files.get(i).toString() + "-----\n"); outputTextArea.appendText(outputStrings.get(i) + "\n\n"); } } catch (InterruptedException e) { e.printStackTrace(); } } public void exportButtonClicked(MouseEvent mouseEvent) throws IOException { if (outputStrings == null || outputStrings.size() < 1) return; List<File> filesToExport = new ArrayList<>(); Window stage = vbMenu.getScene().getWindow(); directoryChooser.setTitle("Select a folder to export to..."); directoryChooser.setInitialDirectory(getRecentPath(2)); File exportDir = directoryChooser.showDialog(stage); List<String> strings = handler.readLines(recentFiles); strings.set(2, exportDir.toString()); handler.write(strings, recentFiles); for (int i = 0; i < files.size(); i++) { File file = new File(exportDir + "\\" + files.get(i).getName().split("[.]")[0] + "-decoded.txt"); System.out.println(file.getName()); handler.createFile(file); handler.write(outputStrings.get(i), file); } } }
Java
CL
638ab7fb9c3eaf14b8dbfa5c7be711fef6a75a0207abc848e9a879a9a9a81b54
package root.client.controllers; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.Observable; import java.util.Observer; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import ocsf.client.ObservableClient; import root.client.managers.DataKeepManager; import root.client.managers.ScreensManager; import root.dao.app.Course; import root.dao.app.Exam; import root.dao.app.Question; import root.dao.app.QuestionInExam; import root.dao.app.Subject; import root.dao.app.User; import root.dao.message.CourseMessage; import root.dao.message.ExamMessage; import root.dao.message.MessageFactory; import root.dao.message.QuestionsMessage; import root.dao.message.SimpleMessage; import root.dao.message.SubjectMessage; import root.server.managers.dbmgr.DbManagerInterface; import root.util.log.Log; import root.util.log.LogLine; /** * * * * A class that is responsible for adding an exam window * * @author Omer Haimovich * */ public class AddExamController implements Observer { // FXML variables ********************************************** @FXML private Button btnRemove; @FXML private Button btnAddToExam; @FXML private FlowPane myFlow; @FXML private ComboBox<String> cmbCourse; @FXML private ComboBox<String> cmbSubject; @FXML private AnchorPane rootPane; @FXML private Button btnAddExam; @FXML private TextField txtDuration; @FXML private TextField txtTeacher; @FXML private Button btnAddQuestion; // Instance variables ********************************************** /** * Counter that counts how many time teacher select subject from the subject * combo box */ private int count; /** * The login teacher */ private User teacher; /** * Generates new communications between server and client */ private MessageFactory messageFact; /** * * Keeps our client in order to communicate with the server */ private ObservableClient client; /** * * A list of all the subjects taught by the teacher */ private ArrayList<Subject> teacherSubject; /** * A list of all the courses taught by the teacher */ private ArrayList<Course> CourseInSubject; /** * * A log file that is responsible for documenting the actions performed in the * application */ private Log log; /** * A list of all questions belonging to the chosen course and subject */ private ArrayList<Question> question; /** * A list of all exams belonging to the chosen course and subject */ private ArrayList<Exam> exams; /** * list of the custom component */ private ArrayList<AddQuestionToExam> myComponent = new ArrayList<AddQuestionToExam>(); /** * The number of exams */ private static int countId = 1; /** * The chosen subject */ private Subject newSubject; /** * The chosen course */ private Course newCourse; /** * The manager that responsible for switching between windows in the system */ private ScreensManager screenManager; /** * The manager that responsible for transmit data between windows in the system */ private DataKeepManager dkm; /** * The main window of the application */ private Stage mainApp; /** * The id of the exam */ private String examId; /** * The custom component */ private AddQuestionToExam newQuestion; // CLASS METHODS ************************************************* /** * * A method that allows the teacher to select a subject * * @param event * * An event that happens when a teacher select from subject combo box */ @FXML void SelectSubject(ActionEvent event) { int i = 0; int size; count++; String selectedVaule = cmbSubject.getValue(); String[] selectedSubject = selectedVaule.toLowerCase().split("-"); if (count > 1) { size = cmbCourse.getItems().size(); while (i < size) { cmbCourse.getItems().remove(0); i++; } i = 0; size = myComponent.size(); while (i < size) { myFlow.getChildren().remove(0); myComponent.remove(0); i++; } i = 0; size = question.size(); while (i < size) { question.remove(0); i++; } i = 0; if (newQuestion != null) { newQuestion.clearQuestionInExam(); newQuestion.clearComboBox(); } btnRemove.setDisable(true); } newSubject = new Subject(selectedSubject[0], selectedSubject[1]); CourseMessage getCourseSubject = (CourseMessage) messageFact.getMessage("get-courses", newSubject); QuestionsMessage getQuestionOfsubject = (QuestionsMessage) messageFact.getMessage("get-questions", newSubject); try { client.sendToServer(getCourseSubject); client.sendToServer(getQuestionOfsubject); } catch (IOException e) { log.writeToLog(LogLine.LineType.ERROR, e.getMessage()); e.printStackTrace(); } } /** * * A method that allows the teacher to select a course * * @param event * * An event that happens when a teacher select from course combo box */ @FXML void SelectCourse(ActionEvent event) { if (cmbCourse.getValue() != null) { String selectedVaule = cmbCourse.getValue(); String[] selectedCourse = selectedVaule.toLowerCase().split("-"); newCourse = new Course(selectedCourse[0], selectedCourse[1]); setIdToExam(); btnAddQuestion.setDisable(false); } } /** * A method that allows the teacher to add a component to the exam form * * @param event * An event occurs when the teacher presses a `add question` button * */ @FXML void AddQuestionToTheExam(ActionEvent event) { newQuestion = new AddQuestionToExam(); btnRemove.setDisable(false); newQuestion.setQuestionCombo(question); myFlow.getChildren().add(newQuestion); btnAddToExam.setDisable(false); btnAddQuestion.setDisable(true); btnAddExam.setDisable(true); myComponent.add(newQuestion); } /** * A method that allows the teacher to add exam to exams pool * * @param event * An event occurs when the teacher presses a `add exam` button * */ @FXML void AddExam(ActionEvent event) { if (isInputValidAddExam()) { ArrayList<QuestionInExam> theQuestions = new ArrayList<QuestionInExam>(); String examDuration = txtDuration.getText(); int duration = Integer.parseInt(examDuration); for (AddQuestionToExam add : myComponent) { theQuestions.add(add.getExamQuestion()); } Exam newExam = new Exam(examId, teacher, duration, theQuestions); ExamMessage newMessage = (ExamMessage) messageFact.getMessage("put-exams", newExam); try { client.sendToServer(newMessage); } catch (IOException e) { log.writeToLog(LogLine.LineType.ERROR, e.getMessage()); e.printStackTrace(); } } } /** * * * A method that sets a new id to the exam */ public void setIdToExam() { String examId = newSubject.getSubjectID() + newCourse.getCourseId(); ExamMessage newMessage = (ExamMessage) messageFact.getMessage("get-exams", examId); try { client.sendToServer(newMessage); } catch (IOException e) { log.writeToLog(LogLine.LineType.ERROR, e.getMessage()); e.printStackTrace(); } } /** * * * The method initializes the window when it comes up * * @throws IOException * if the window cannot be shown */ @FXML public void initialize() throws IOException { count = 0; log = Log.getInstance(); dkm = DataKeepManager.getInstance(); screenManager = ScreensManager.getInstance(); mainApp = screenManager.getPrimaryStage(); client = new ObservableClient((String) dkm.getObject_NoRemove("ip"), 8000); client.addObserver(this); client.openConnection(); messageFact = MessageFactory.getInstance(); cmbCourse.setPromptText("Choose course"); cmbSubject.setPromptText("Choose subject"); teacher = dkm.getUser(); txtTeacher.setText(teacher.getUserFirstName() + " " + teacher.getUserLastName()); txtTeacher.setDisable(true); btnAddToExam.setDisable(true); btnAddQuestion.setDisable(true); btnRemove.setDisable(true); cmbCourse.setDisable(true); SubjectMessage getTeacherSubject = (SubjectMessage) messageFact.getMessage("get-subjects", teacher.getUserID()); client.sendToServer(getTeacherSubject); } /** * * A method that is responsible for handling messages sent from the server */ @Override public void update(Observable arg0, Object arg1) { if (arg1 instanceof SubjectMessage) { SubjectMessage intialSubjectMessage = (SubjectMessage) arg1; teacherSubject = intialSubjectMessage.getTeacherSubject(); for (Subject s : teacherSubject) { cmbSubject.getItems().add(s.getSubjectID() + "-" + s.getSubjectName()); } } if (arg1 instanceof CourseMessage) { CourseMessage intialCourseMessage = (CourseMessage) arg1; CourseInSubject = intialCourseMessage.getCourses(); for (Course c : CourseInSubject) { cmbCourse.getItems().add(c.getCourseId() + "-" + c.getCourseName()); } cmbCourse.setDisable(false); } if (arg1 instanceof QuestionsMessage) { QuestionsMessage intialQuestionMessage = (QuestionsMessage) arg1; question = intialQuestionMessage.getQuestions(); } if (arg1 instanceof ExamMessage) { ExamMessage intialExamMessage = (ExamMessage) arg1; exams = intialExamMessage.getExams(); if (exams.size() > 0) { Exam exam = exams.get(exams.size() - 1); String tempId = exam.getExamId().substring(4, 6); int id = Integer.parseInt(tempId) + 1; countId = id; if (countId <= 9) examId = newSubject.getSubjectID() + newCourse.getCourseId() + "0" + Integer.toString(countId); else examId = newSubject.getSubjectID() + newCourse.getCourseId() + Integer.toString(countId); } else { countId = 1; examId = newSubject.getSubjectID() + newCourse.getCourseId() + "0" + Integer.toString(countId); } } if (arg1 instanceof SimpleMessage) { log.writeToLog(LogLine.LineType.INFO, "Exam added"); newQuestion.clearQuestionInExam(); newQuestion.clearComboBox(); Platform.runLater(() -> { // In order to run javaFX thread.(we recieve from server a java thread) try { Alert alert = new Alert(AlertType.INFORMATION); alert.initOwner(mainApp); alert.setTitle("Exam added"); alert.setHeaderText("Exam added successeful"); alert.setContentText("The exam was added successful"); alert.showAndWait(); screenManager.activate("home"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); log.writeToLog(LogLine.LineType.ERROR, e.getMessage()); } }); } } /** * Checks whether all fields are valid * * @return true if all inputs valid and false if not */ private boolean isInputValidAddExam() { String errorMessage = ""; if (cmbSubject.getSelectionModel().getSelectedItem() == null) {// || firstNameField.getText().length() == 0) { errorMessage += "Please Select a Subject!\n"; } if (cmbCourse.getSelectionModel().getSelectedItem() == null) { errorMessage += "Please Select a Course!\n"; } if (AddQuestionToExam.getCount() == 0) { errorMessage += "Please Add Question!\n"; } if (txtDuration.getText() == null || txtDuration.getText().length() == 0) { errorMessage += "No valid exam duration\n"; } if (!(txtDuration.getText().matches("[0-9]+"))) { errorMessage += "can not enter letters in duration\n"; } if (txtDuration.getText().matches("[0-9]+")) { if (Integer.parseInt(txtDuration.getText()) <= 0) errorMessage += "Duration must be more than 0\n"; } if (AddQuestionToExam.getTotalPoints() < 100) { errorMessage += "can not enter letters in duration\n"; } if (errorMessage.length() == 0) { return true; } else { // Show the error message. Alert alert = new Alert(AlertType.ERROR); alert.initOwner(mainApp); alert.setTitle("Invalid Fields"); alert.setHeaderText("Please correct invalid fields"); alert.setContentText(errorMessage); alert.showAndWait(); return false; } } /** * A method that allows the teacher to add question to the exam * * @param event * An event occurs when the teacher presses a `add question to exam` * button * */ @FXML void AddToTheExamForm(ActionEvent event) { if (newQuestion.AddQuestion()) { btnAddQuestion.setDisable(false); btnAddExam.setDisable(false); Alert alert = new Alert(AlertType.INFORMATION); alert.initOwner(mainApp); alert.setTitle("Question added successful"); alert.setHeaderText("Question added successful"); alert.setContentText("The question is added"); alert.showAndWait(); } } /** * A method that allows the teacher to remove question from exam * * @param event * An event occurs when the teacher presses a `remove question` * button * */ @FXML void removeQuestion(ActionEvent event) { int i = 0; btnAddToExam.setDisable(true); btnAddQuestion.setDisable(false); ArrayList<String> deleted = new ArrayList<String>(); for (AddQuestionToExam add : myComponent) { if (add.checkRemove.isSelected()) { add.removeTheQuestion(add); myFlow.getChildren().remove(add); deleted.add(add.getID()); } i++; } i = 0; for (String s : deleted) { for (AddQuestionToExam add : myComponent) { if (add.getID().equals(s)) { myComponent.remove(i); break; } i++; } } } }
Java
CL
da14eb0b8116657f8f97c70faf15f679242224b9dea620e443b9d95c0d3f4b3e
package geoand.junit.agent; import javassist.*; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; public class Agent { private static final String CLASS_NAME = "org.junit.runner.notification.RunNotifier"; public static void premain(String agentArgs, Instrumentation inst) { inst.addTransformer(new ClassFileTransformer() { @Override public byte[] transform(ClassLoader classLoader, String s, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException { if (CLASS_NAME.replace(".", "/").equals(s)) { try { final ClassPool cp = ClassPool.getDefault(); final CtClass cc = cp.get(CLASS_NAME); doNotNotifyListenersOfTestFailures(cc); byte[] byteCode = cc.toBytecode(); cc.detach(); return byteCode; } catch (Exception ex) { ex.printStackTrace(); } } return null; } }); } private static void doNotNotifyListenersOfTestFailures(CtClass cc) throws NotFoundException, CannotCompileException { final CtMethod fireTestFailuresMethod = cc.getDeclaredMethod("fireTestFailure"); fireTestFailuresMethod.setBody("{return;}"); } }
Java
CL
fb63ceaeeee8e70daf4d2b53ad0b948f31ce0edbf1e9605200460a7f5d79973f
package com.juniorproject.orderbook; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.juniorproject.orderbook.repository.BookTreeSetImpl; import com.juniorproject.orderbook.service.CommandHandler; import com.juniorproject.orderbook.service.MyWriter; import com.juniorproject.orderbook.service.MyWriterException; /** * Simple implementation of limit order book. * * Default input file is input.txt * default output file is output.txt * * They can be overridden by command line arguments, first argument - input file name (or path), * second command line argument - output file name (or path) * * @author Slava Shishkanu * */ public class OrderBookMain { private static Logger log = LoggerFactory.getLogger(OrderBookMain.class.getName()); public static void main(String[] args) { String inputFilePath = "input.txt"; String outputFilePath = "output.txt"; if (args.length != 0) { inputFilePath = args[0]; if (args.length >= 2) { outputFilePath = args[1]; } } log.info("input file is {}", inputFilePath); log.info("output file is {}", outputFilePath); final CommandHandler commandHandler; try (Stream<String> stream = Files.lines(Paths.get(inputFilePath)); BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFilePath), StandardCharsets.UTF_8)) { final MyWriter myWriter = new MyWriter(writer); commandHandler = new CommandHandler(BookTreeSetImpl.getInstance(), myWriter); stream.forEach(commandHandler::handle); } catch (IOException e) { log.error("error while reading, looks like input file does not exist", e); throw new MyWriterException("error while reading, looks like input file does not exist", e); } } }
Java
CL
99240563204aa69da7ac4919f4fc518daed78e56dd7a6e11a011744f8e3402cf
package com.mediatek.mms.ext; import android.content.Context; import android.net.Uri; import com.google.android.mms.pdu.AcknowledgeInd; import com.mediatek.mms.callback.IDownloadManagerCallback; public interface IOpRetrieveTransactionExt { /** * @internal */ void sendAcknowledgeInd(Context context, int subId, AcknowledgeInd acknowledgeInd); /** * @internal */ boolean run(boolean isCancelling, Uri uri, Context context, Uri trxnUri, String contentLocation); /** * @internal */ void init(IDownloadManagerCallback downloadManager); }
Java
CL
58014c8227de95ceed075b40b6eb100754783efe7fcb3a602b0894d6467fac43
/** * Autogenerated by Jack * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING */ package com.rapleaf.jack.test_project.database_1.impl; import java.sql.SQLRecoverableException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Collection; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Date; import java.sql.Timestamp; import com.rapleaf.jack.AbstractDatabaseModel; import com.rapleaf.jack.BaseDatabaseConnection; import com.rapleaf.jack.queries.WhereConstraint; import com.rapleaf.jack.queries.WhereClause; import com.rapleaf.jack.util.JackUtility; import com.rapleaf.jack.test_project.database_1.iface.IUserPersistence; import com.rapleaf.jack.test_project.database_1.models.User; import com.rapleaf.jack.test_project.database_1.query.UserQueryBuilder; import com.rapleaf.jack.test_project.database_1.query.UserDeleteBuilder; import com.rapleaf.jack.test_project.IDatabases; public class BaseUserPersistenceImpl extends AbstractDatabaseModel<User> implements IUserPersistence { private final IDatabases databases; public BaseUserPersistenceImpl(BaseDatabaseConnection conn, IDatabases databases) { super(conn, "users", Arrays.<String>asList("handle", "created_at_millis", "num_posts", "some_date", "some_datetime", "bio", "some_binary", "some_float", "some_decimal", "some_boolean")); this.databases = databases; } @Override public User create(Map<Enum, Object> fieldsMap) throws IOException { String handle = (String) fieldsMap.get(User._Fields.handle); Long created_at_millis = (Long) fieldsMap.get(User._Fields.created_at_millis); int num_posts = (Integer) fieldsMap.get(User._Fields.num_posts); Long some_date = (Long) fieldsMap.get(User._Fields.some_date); Long some_datetime = (Long) fieldsMap.get(User._Fields.some_datetime); String bio = (String) fieldsMap.get(User._Fields.bio); byte[] some_binary = (byte[]) fieldsMap.get(User._Fields.some_binary); Double some_float = (Double) fieldsMap.get(User._Fields.some_float); Double some_decimal = (Double) fieldsMap.get(User._Fields.some_decimal); Boolean some_boolean = (Boolean) fieldsMap.get(User._Fields.some_boolean); return create(handle, created_at_millis, num_posts, some_date, some_datetime, bio, some_binary, some_float, some_decimal, some_boolean); } public User create(final String handle, final Long created_at_millis, final int num_posts, final Long some_date, final Long some_datetime, final String bio, final byte[] some_binary, final Double some_float, final Double some_decimal, final Boolean some_boolean) throws IOException { StatementCreator statementCreator = new StatementCreator() { private final List<String> nonNullFields = new ArrayList<>(); private final List<AttrSetter> statementSetters = new ArrayList<>(); { int index = 1; nonNullFields.add("handle"); int fieldIndex0 = index++; statementSetters.add(stmt -> stmt.setString(fieldIndex0, handle)); if (created_at_millis != null) { nonNullFields.add("created_at_millis"); int fieldIndex1 = index++; statementSetters.add(stmt -> stmt.setLong(fieldIndex1, created_at_millis)); } nonNullFields.add("num_posts"); int fieldIndex2 = index++; statementSetters.add(stmt -> stmt.setInt(fieldIndex2, num_posts)); if (some_date != null) { nonNullFields.add("some_date"); int fieldIndex3 = index++; statementSetters.add(stmt -> stmt.setDate(fieldIndex3, new Date(some_date))); } if (some_datetime != null) { nonNullFields.add("some_datetime"); int fieldIndex4 = index++; statementSetters.add(stmt -> stmt.setTimestamp(fieldIndex4, new Timestamp(some_datetime))); } if (bio != null) { nonNullFields.add("bio"); int fieldIndex5 = index++; statementSetters.add(stmt -> stmt.setString(fieldIndex5, bio)); } if (some_binary != null) { nonNullFields.add("some_binary"); int fieldIndex6 = index++; statementSetters.add(stmt -> stmt.setBytes(fieldIndex6, some_binary)); } if (some_float != null) { nonNullFields.add("some_float"); int fieldIndex7 = index++; statementSetters.add(stmt -> stmt.setDouble(fieldIndex7, some_float)); } if (some_decimal != null) { nonNullFields.add("some_decimal"); int fieldIndex8 = index++; statementSetters.add(stmt -> stmt.setDouble(fieldIndex8, some_decimal)); } if (some_boolean != null) { nonNullFields.add("some_boolean"); int fieldIndex9 = index++; statementSetters.add(stmt -> stmt.setBoolean(fieldIndex9, some_boolean)); } } @Override public String getStatement() { return getInsertStatement(nonNullFields); } @Override public void setStatement(PreparedStatement statement) throws SQLException { for (AttrSetter setter : statementSetters) { setter.set(statement); } } }; long __id = realCreate(statementCreator); User newInst = new User(__id, handle, created_at_millis, num_posts, some_date, some_datetime, bio, some_binary, some_float, some_decimal, some_boolean, databases); newInst.setCreated(true); cachedById.put(__id, newInst); clearForeignKeyCache(); return newInst; } public User create(final String handle, final int num_posts) throws IOException { StatementCreator statementCreator = new StatementCreator() { private final List<String> nonNullFields = new ArrayList<>(); private final List<AttrSetter> statementSetters = new ArrayList<>(); { int index = 1; nonNullFields.add("handle"); int fieldIndex0 = index++; statementSetters.add(stmt -> stmt.setString(fieldIndex0, handle)); nonNullFields.add("num_posts"); int fieldIndex2 = index++; statementSetters.add(stmt -> stmt.setInt(fieldIndex2, num_posts)); } @Override public String getStatement() { return getInsertStatement(nonNullFields); } @Override public void setStatement(PreparedStatement statement) throws SQLException { for (AttrSetter setter : statementSetters) { setter.set(statement); } } }; long __id = realCreate(statementCreator); User newInst = new User(__id, handle, null, num_posts, null, null, null, null, null, null, null, databases); newInst.setCreated(true); cachedById.put(__id, newInst); clearForeignKeyCache(); return newInst; } public User createDefaultInstance() throws IOException { return create("", 0); } public List<User> find(Map<Enum, Object> fieldsMap) throws IOException { return find(null, fieldsMap); } public List<User> find(Collection<Long> ids, Map<Enum, Object> fieldsMap) throws IOException { List<User> foundList = new ArrayList<>(); if (fieldsMap == null || fieldsMap.isEmpty()) { return foundList; } StringBuilder statementString = new StringBuilder(); statementString.append("SELECT * FROM users WHERE ("); List<Object> nonNullValues = new ArrayList<>(); List<User._Fields> nonNullValueFields = new ArrayList<>(); Iterator<Map.Entry<Enum, Object>> iter = fieldsMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Enum, Object> entry = iter.next(); Enum field = entry.getKey(); Object value = entry.getValue(); String queryValue = value != null ? " = ? " : " IS NULL"; if (value != null) { nonNullValueFields.add((User._Fields) field); nonNullValues.add(value); } statementString.append(field).append(queryValue); if (iter.hasNext()) { statementString.append(" AND "); } } if (ids != null) statementString.append(" AND ").append(getIdSetCondition(ids)); statementString.append(")"); int retryCount = 0; PreparedStatement preparedStatement; while (true) { preparedStatement = getPreparedStatement(statementString.toString()); for (int i = 0; i < nonNullValues.size(); i++) { User._Fields field = nonNullValueFields.get(i); try { switch (field) { case handle: preparedStatement.setString(i+1, (String) nonNullValues.get(i)); break; case created_at_millis: preparedStatement.setLong(i+1, (Long) nonNullValues.get(i)); break; case num_posts: preparedStatement.setInt(i+1, (Integer) nonNullValues.get(i)); break; case some_date: preparedStatement.setDate(i+1, new Date((Long) nonNullValues.get(i))); break; case some_datetime: preparedStatement.setTimestamp(i+1, new Timestamp((Long) nonNullValues.get(i))); break; case bio: preparedStatement.setString(i+1, (String) nonNullValues.get(i)); break; case some_binary: preparedStatement.setBytes(i+1, (byte[]) nonNullValues.get(i)); break; case some_float: preparedStatement.setDouble(i+1, (Double) nonNullValues.get(i)); break; case some_decimal: preparedStatement.setDouble(i+1, (Double) nonNullValues.get(i)); break; case some_boolean: preparedStatement.setBoolean(i+1, (Boolean) nonNullValues.get(i)); break; } } catch (SQLException e) { throw new IOException(e); } } try { executeQuery(foundList, preparedStatement); return foundList; } catch (SQLRecoverableException e) { if (++retryCount > AbstractDatabaseModel.MAX_CONNECTION_RETRIES) { throw new IOException(e); } } catch (SQLException e) { throw new IOException(e); } } } @Override protected void setStatementParameters(PreparedStatement preparedStatement, WhereClause whereClause) throws IOException { int index = 0; for (WhereConstraint constraint : whereClause.getWhereConstraints()) { for (Object parameter : constraint.getParameters()) { if (parameter == null) { continue; } try { if (constraint.isId()) { preparedStatement.setLong(++index, (Long)parameter); } else { User._Fields field = (User._Fields)constraint.getField(); switch (field) { case handle: preparedStatement.setString(++index, (String) parameter); break; case created_at_millis: preparedStatement.setLong(++index, (Long) parameter); break; case num_posts: preparedStatement.setInt(++index, (Integer) parameter); break; case some_date: preparedStatement.setDate(++index, new Date((Long) parameter)); break; case some_datetime: preparedStatement.setTimestamp(++index, new Timestamp((Long) parameter)); break; case bio: preparedStatement.setString(++index, (String) parameter); break; case some_binary: preparedStatement.setBytes(++index, (byte[]) parameter); break; case some_float: preparedStatement.setDouble(++index, (Double) parameter); break; case some_decimal: preparedStatement.setDouble(++index, (Double) parameter); break; case some_boolean: preparedStatement.setBoolean(++index, (Boolean) parameter); break; } } } catch (SQLException e) { throw new IOException(e); } } } } @Override protected void setAttrs(User model, PreparedStatement stmt, boolean setNull) throws SQLException { int index = 1; { stmt.setString(index++, model.getHandle()); } if (setNull && model.getCreatedAtMillis() == null) { stmt.setNull(index++, java.sql.Types.INTEGER); } else if (model.getCreatedAtMillis() != null) { stmt.setLong(index++, model.getCreatedAtMillis()); } { stmt.setInt(index++, model.getNumPosts()); } if (setNull && model.getSomeDate() == null) { stmt.setNull(index++, java.sql.Types.DATE); } else if (model.getSomeDate() != null) { stmt.setDate(index++, new Date(model.getSomeDate())); } if (setNull && model.getSomeDatetime() == null) { stmt.setNull(index++, java.sql.Types.DATE); } else if (model.getSomeDatetime() != null) { stmt.setTimestamp(index++, new Timestamp(model.getSomeDatetime())); } if (setNull && model.getBio() == null) { stmt.setNull(index++, java.sql.Types.CHAR); } else if (model.getBio() != null) { stmt.setString(index++, model.getBio()); } if (setNull && model.getSomeBinary() == null) { stmt.setNull(index++, java.sql.Types.BINARY); } else if (model.getSomeBinary() != null) { stmt.setBytes(index++, model.getSomeBinary()); } if (setNull && model.getSomeFloat() == null) { stmt.setNull(index++, java.sql.Types.DOUBLE); } else if (model.getSomeFloat() != null) { stmt.setDouble(index++, model.getSomeFloat()); } if (setNull && model.getSomeDecimal() == null) { stmt.setNull(index++, java.sql.Types.DECIMAL); } else if (model.getSomeDecimal() != null) { stmt.setDouble(index++, model.getSomeDecimal()); } if (setNull && model.isSomeBoolean() == null) { stmt.setNull(index++, java.sql.Types.BOOLEAN); } else if (model.isSomeBoolean() != null) { stmt.setBoolean(index++, model.isSomeBoolean()); } stmt.setLong(index, model.getId()); } @Override protected User instanceFromResultSet(ResultSet rs, Collection<Enum> selectedFields) throws SQLException { boolean allFields = selectedFields == null || selectedFields.isEmpty(); long id = rs.getLong("id"); return new User(id, allFields || selectedFields.contains(User._Fields.handle) ? rs.getString("handle") : "", allFields || selectedFields.contains(User._Fields.created_at_millis) ? getLongOrNull(rs, "created_at_millis") : null, allFields || selectedFields.contains(User._Fields.num_posts) ? getIntOrNull(rs, "num_posts") : 0, allFields || selectedFields.contains(User._Fields.some_date) ? getDateAsLong(rs, "some_date") : null, allFields || selectedFields.contains(User._Fields.some_datetime) ? getDateAsLong(rs, "some_datetime") : null, allFields || selectedFields.contains(User._Fields.bio) ? rs.getString("bio") : null, allFields || selectedFields.contains(User._Fields.some_binary) ? rs.getBytes("some_binary") : null, allFields || selectedFields.contains(User._Fields.some_float) ? getDoubleOrNull(rs, "some_float") : null, allFields || selectedFields.contains(User._Fields.some_decimal) ? getDoubleOrNull(rs, "some_decimal") : null, allFields || selectedFields.contains(User._Fields.some_boolean) ? getBooleanOrNull(rs, "some_boolean") : null, databases ); } public List<User> findByHandle(final String value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.handle, value)); } public List<User> findByCreatedAtMillis(final Long value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.created_at_millis, value)); } public List<User> findByNumPosts(final int value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.num_posts, value)); } public List<User> findBySomeDate(final Long value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.some_date, value)); } public List<User> findBySomeDatetime(final Long value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.some_datetime, value)); } public List<User> findByBio(final String value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.bio, value)); } public List<User> findBySomeBinary(final byte[] value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.some_binary, value)); } public List<User> findBySomeFloat(final Double value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.some_float, value)); } public List<User> findBySomeDecimal(final Double value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.some_decimal, value)); } public List<User> findBySomeBoolean(final Boolean value) throws IOException { return find(Collections.<Enum, Object>singletonMap(User._Fields.some_boolean, value)); } public UserQueryBuilder query() { return new UserQueryBuilder(this); } public UserDeleteBuilder delete() { return new UserDeleteBuilder(this); } }
Java
CL
1b8f43c619e26a10410a9d718c41d7b86305101c1392b8fb6c953f9b806b8691
package ch.ethz.matsim.baseline_scenario.zurich.router.parallel; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import org.matsim.api.core.v01.population.PlanElement; import ch.ethz.matsim.baseline_scenario.zurich.utils.ActivityWithFacility; public interface ParallelTripRouter { CompletableFuture<List<PlanElement>> route(ActivityWithFacility originActivity, List<PlanElement> trip, ActivityWithFacility destinationActivity, Executor executor); }
Java
CL
11ad90e4d0e46bd6ae1a1f82d345e6b6894f7de13af853f15db2dbc9464d5699
/* * 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.druid.data.input.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Strings; import org.apache.druid.guice.annotations.PublicApi; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.emitter.EmittingLogger; import org.apache.druid.segment.AutoTypeColumnSchema; import org.apache.druid.segment.DimensionHandler; import org.apache.druid.segment.DimensionHandlerUtils; import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.column.TypeSignature; import org.apache.druid.segment.column.ValueType; import org.apache.druid.segment.incremental.IncrementalIndex; import org.apache.druid.segment.nested.NestedDataComplexTypeSerde; import java.util.Objects; /** */ @PublicApi @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = StringDimensionSchema.class) @JsonSubTypes(value = { @JsonSubTypes.Type(name = DimensionSchema.STRING_TYPE_NAME, value = StringDimensionSchema.class), @JsonSubTypes.Type(name = DimensionSchema.LONG_TYPE_NAME, value = LongDimensionSchema.class), @JsonSubTypes.Type(name = DimensionSchema.FLOAT_TYPE_NAME, value = FloatDimensionSchema.class), @JsonSubTypes.Type(name = DimensionSchema.DOUBLE_TYPE_NAME, value = DoubleDimensionSchema.class), @JsonSubTypes.Type(name = DimensionSchema.SPATIAL_TYPE_NAME, value = NewSpatialDimensionSchema.class), @JsonSubTypes.Type(name = NestedDataComplexTypeSerde.TYPE_NAME, value = AutoTypeColumnSchema.class), @JsonSubTypes.Type(name = AutoTypeColumnSchema.TYPE, value = AutoTypeColumnSchema.class) }) public abstract class DimensionSchema { public static DimensionSchema getDefaultSchemaForBuiltInType(String name, TypeSignature<ValueType> type) { switch (type.getType()) { case STRING: return new StringDimensionSchema(name); case LONG: return new LongDimensionSchema(name); case FLOAT: return new FloatDimensionSchema(name); case DOUBLE: return new DoubleDimensionSchema(name); default: // the auto column indexer can handle any type return new AutoTypeColumnSchema(name); } } public static final String STRING_TYPE_NAME = "string"; public static final String LONG_TYPE_NAME = "long"; public static final String FLOAT_TYPE_NAME = "float"; public static final String SPATIAL_TYPE_NAME = "spatial"; public static final String DOUBLE_TYPE_NAME = "double"; private static final EmittingLogger log = new EmittingLogger(DimensionSchema.class); public enum MultiValueHandling { SORTED_ARRAY, SORTED_SET, ARRAY { @Override public boolean needSorting() { return false; } }; public boolean needSorting() { return true; } @Override @JsonValue public String toString() { return StringUtils.toUpperCase(name()); } @JsonCreator public static MultiValueHandling fromString(String name) { return name == null ? ofDefault() : valueOf(StringUtils.toUpperCase(name)); } // this can be system configuration public static MultiValueHandling ofDefault() { return SORTED_ARRAY; } } private final String name; private final MultiValueHandling multiValueHandling; private final boolean createBitmapIndex; protected DimensionSchema(String name, MultiValueHandling multiValueHandling, boolean createBitmapIndex) { if (Strings.isNullOrEmpty(name)) { log.warn("Null or Empty Dimension found"); } this.name = name; this.multiValueHandling = multiValueHandling == null ? MultiValueHandling.ofDefault() : multiValueHandling; this.createBitmapIndex = createBitmapIndex; } @JsonProperty public String getName() { return name; } @JsonProperty public MultiValueHandling getMultiValueHandling() { return multiValueHandling; } @JsonProperty("createBitmapIndex") public boolean hasBitmapIndex() { return createBitmapIndex; } @JsonIgnore public abstract String getTypeName(); @JsonIgnore public abstract ColumnType getColumnType(); @JsonIgnore public DimensionHandler getDimensionHandler() { // default implementation for backwards compatibility return DimensionHandlerUtils.getHandlerFromCapabilities( name, IncrementalIndex.makeDefaultCapabilitiesFromValueType(getColumnType()), multiValueHandling ); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final DimensionSchema that = (DimensionSchema) o; return createBitmapIndex == that.createBitmapIndex && Objects.equals(name, that.name) && Objects.equals(getTypeName(), that.getTypeName()) && Objects.equals(getColumnType(), that.getColumnType()) && multiValueHandling == that.multiValueHandling; } @Override public int hashCode() { return Objects.hash(name, multiValueHandling, createBitmapIndex, getTypeName(), getColumnType()); } @Override public String toString() { return "DimensionSchema{" + "name='" + name + '\'' + ", valueType=" + getColumnType() + ", typeName=" + getTypeName() + ", multiValueHandling=" + multiValueHandling + ", createBitmapIndex=" + createBitmapIndex + '}'; } }
Java
CL
d0c592d2826f3c8c17cc87c89d18bacecdbe374e9d532c73ea52d386a1346e26
/* * Copyright 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 in.afckstechnologies.afcksenquirymanagement.provider; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Log; import in.afckstechnologies.afcksenquirymanagement.common.db.SelectionBuilder; public class StudentProvider extends ContentProvider { AFCKSDatabase mDatabaseHelper; /** * Content authority for this provider. */ private static final String AUTHORITY = StudentContract.CONTENT_AUTHORITY; // The constants below represent individual URI routes, as IDs. Every URI pattern recognized by // this ContentProvider is defined using sUriMatcher.addURI(), and associated with one of these // IDs. // // When a incoming URI is run through sUriMatcher, it will be tested against the defined // URI patterns, and the corresponding route ID will be returned. /** * URI ID for route: /entries */ public static final int ROUTE_ENTRIES = 1; /** * URI ID for route: /entries/{ID} */ public static final int ROUTE_ENTRIES_ID = 2; /** * URI ID for route: /location */ public static final int ROUTE_LOC_ENTRIES = 3; /** * URI ID for route: /location/{ID} */ public static final int ROUTE_LOC_ENTRIES_ID = 4; /** * URI ID for route: /course */ public static final int ROUTE_COURSE_ENTRIES = 5; /** * URI ID for route: /course/{ID} */ public static final int ROUTE_COURSE_ENTRIES_ID = 6; /** * URI ID for route: /course */ public static final int ROUTE_TEMPLATE_ENTRIES = 7; /** * URI ID for route: /course/{ID} */ public static final int ROUTE_TEMPLATE_ENTRIES_ID = 8; /** * URI ID for route: /student_batchdetails */ public static final int ROUTE_STUDENT_BATCHDETAILS_ENTRIES = 9; /** * URI ID for route: /student_batchdetails/{ID} */ public static final int ROUTE_STUDENT_BATCHDETAILS_ENTRIES_ID = 10; /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_COMING_BATCHDETAILS_ENTRIES = 11; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_COMING_BATCHDETAILS_ENTRIES_ID = 12; /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_STUDENT_ATTENDANCE_ENTRIES = 13; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_STUDENT_ATTENDANCE_ENTRIES_ID = 14; /** * /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_BRANCHES_ENTRIES = 15; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_BRANCHES_ENTRIES_ID = 16; /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_COURSES_ENTRIES = 17; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_COURSES_ENTRIES_ID = 18; /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_COURSE_TYPE_ENTRIES = 19; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_COURSE_TYPE_ENTRIES_ID = 20; /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_DAYPREFRENCE_ENTRIES = 21; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_DAYPREFRENCE_ENTRIES_ID = 22; /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_USERDAYPREFRENCE_ENTRIES = 23; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_USERDAYPREFRENCE_ENTRIES_ID = 24; /** /** * URI ID for route: /coming_batchdetails */ public static final int ROUTE_STUDENTCOMMENTS_ENTRIES = 25; /** * URI ID for route: /coming_batchdetails/{ID} */ public static final int ROUTE_STUDENTCOMMENTS_ENTRIES_ID = 26; /** * UriMatcher, used to decode incoming URIs. */ private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI(AUTHORITY, "entries", ROUTE_ENTRIES); sUriMatcher.addURI(AUTHORITY, "entries/*", ROUTE_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "locentries", ROUTE_LOC_ENTRIES); sUriMatcher.addURI(AUTHORITY, "locentries/*", ROUTE_LOC_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "courses", ROUTE_COURSE_ENTRIES); sUriMatcher.addURI(AUTHORITY, "courses/*", ROUTE_COURSE_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "templates", ROUTE_TEMPLATE_ENTRIES); sUriMatcher.addURI(AUTHORITY, "templates/*", ROUTE_TEMPLATE_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "studentbatches", ROUTE_STUDENT_BATCHDETAILS_ENTRIES); sUriMatcher.addURI(AUTHORITY, "studentbatches/*", ROUTE_STUDENT_BATCHDETAILS_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "comingbatches", ROUTE_COMING_BATCHDETAILS_ENTRIES); sUriMatcher.addURI(AUTHORITY, "comingbatches/*", ROUTE_COMING_BATCHDETAILS_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "studentattendance", ROUTE_STUDENT_ATTENDANCE_ENTRIES); sUriMatcher.addURI(AUTHORITY, "studentattendance/*", ROUTE_STUDENT_ATTENDANCE_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "branchesdetails", ROUTE_BRANCHES_ENTRIES); sUriMatcher.addURI(AUTHORITY, "branchesdetails/*", ROUTE_BRANCHES_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "coursesdetails", ROUTE_COURSES_ENTRIES); sUriMatcher.addURI(AUTHORITY, "coursesdetails/*", ROUTE_COURSES_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "coursetype", ROUTE_COURSE_TYPE_ENTRIES); sUriMatcher.addURI(AUTHORITY, "coursetype/*", ROUTE_COURSE_TYPE_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "dayprefrencedetails", ROUTE_DAYPREFRENCE_ENTRIES); sUriMatcher.addURI(AUTHORITY, "dayprefrencedetails/*", ROUTE_DAYPREFRENCE_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "userdayprefrencedetails", ROUTE_USERDAYPREFRENCE_ENTRIES); sUriMatcher.addURI(AUTHORITY, "userdayprefrencedetails/*", ROUTE_USERDAYPREFRENCE_ENTRIES_ID); sUriMatcher.addURI(AUTHORITY, "studentscommentdetails", ROUTE_STUDENTCOMMENTS_ENTRIES); sUriMatcher.addURI(AUTHORITY, "studentscommentdetails/*", ROUTE_STUDENTCOMMENTS_ENTRIES_ID); } @Override public boolean onCreate() { mDatabaseHelper = new AFCKSDatabase(getContext()); return true; } /** * Determine the mime type for entries returned by a given URI. */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case ROUTE_ENTRIES: return StudentContract.Entry.CONTENT_TYPE; case ROUTE_ENTRIES_ID: return StudentContract.Entry.CONTENT_ITEM_TYPE; case ROUTE_LOC_ENTRIES: return StudentContract.StudentLocation.CONTENT_TYPE; case ROUTE_LOC_ENTRIES_ID: return StudentContract.StudentLocation.CONTENT_ITEM_TYPE; case ROUTE_COURSE_ENTRIES: return StudentContract.StudentCourse.CONTENT_TYPE; case ROUTE_COURSE_ENTRIES_ID: return StudentContract.StudentCourse.CONTENT_ITEM_TYPE; case ROUTE_TEMPLATE_ENTRIES: return StudentContract.TrainersTemplate.CONTENT_TYPE; case ROUTE_TEMPLATE_ENTRIES_ID: return StudentContract.TrainersTemplate.CONTENT_ITEM_TYPE; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES: return StudentContract.StudentBatchdetails.CONTENT_TYPE; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES_ID: return StudentContract.StudentBatchdetails.CONTENT_ITEM_TYPE; case ROUTE_COMING_BATCHDETAILS_ENTRIES: return StudentContract.ComingBatchdetails.CONTENT_TYPE; case ROUTE_COMING_BATCHDETAILS_ENTRIES_ID: return StudentContract.ComingBatchdetails.CONTENT_ITEM_TYPE; case ROUTE_STUDENT_ATTENDANCE_ENTRIES: return StudentContract.StudentAttendance.CONTENT_TYPE; case ROUTE_STUDENT_ATTENDANCE_ENTRIES_ID: return StudentContract.StudentAttendance.CONTENT_ITEM_TYPE; case ROUTE_BRANCHES_ENTRIES: return StudentContract.Branches.CONTENT_TYPE; case ROUTE_BRANCHES_ENTRIES_ID: return StudentContract.Branches.CONTENT_ITEM_TYPE; case ROUTE_COURSES_ENTRIES: return StudentContract.Courses.CONTENT_TYPE; case ROUTE_COURSES_ENTRIES_ID: return StudentContract.Courses.CONTENT_ITEM_TYPE; case ROUTE_COURSE_TYPE_ENTRIES: return StudentContract.CourseType.CONTENT_TYPE; case ROUTE_COURSE_TYPE_ENTRIES_ID: return StudentContract.CourseType.CONTENT_ITEM_TYPE; case ROUTE_DAYPREFRENCE_ENTRIES: return StudentContract.DayPrefrence.CONTENT_TYPE; case ROUTE_DAYPREFRENCE_ENTRIES_ID: return StudentContract.DayPrefrence.CONTENT_ITEM_TYPE; case ROUTE_USERDAYPREFRENCE_ENTRIES: return StudentContract.UserDayPrefrence.CONTENT_TYPE; case ROUTE_USERDAYPREFRENCE_ENTRIES_ID: return StudentContract.UserDayPrefrence.CONTENT_ITEM_TYPE; case ROUTE_STUDENTCOMMENTS_ENTRIES: return StudentContract.StudentComments.CONTENT_TYPE; case ROUTE_STUDENTCOMMENTS_ENTRIES_ID: return StudentContract.StudentComments.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** * Perform a database query by URI. * * <p>Currently supports returning all entries (/entries) and individual entries by ID * (/entries/{ID}). */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mDatabaseHelper.getReadableDatabase(); SelectionBuilder builder = new SelectionBuilder(); int uriMatch = sUriMatcher.match(uri); switch (uriMatch) { case ROUTE_ENTRIES_ID: // Return a single entry, by ID. String id = uri.getLastPathSegment(); builder.where(StudentContract.Entry._ID + "=?", id); case ROUTE_ENTRIES: // Return all known entries. builder.table(StudentContract.Entry.TABLE_NAME) .where(selection, selectionArgs); Cursor c = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context ctx = getContext(); assert ctx != null; c.setNotificationUri(ctx.getContentResolver(), uri); return c; case ROUTE_LOC_ENTRIES_ID: // Return a single entry, by ID. String lid = uri.getLastPathSegment(); builder.where(StudentContract.StudentLocation._ID + "=?", lid); case ROUTE_LOC_ENTRIES: // Return all known entries. builder.table(StudentContract.StudentLocation.TABLE_NAME) .where(selection, selectionArgs); Cursor cl = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context ctxl = getContext(); assert ctxl != null; cl.setNotificationUri(ctxl.getContentResolver(), uri); return cl; case ROUTE_COURSE_ENTRIES_ID: // Return a single entry, by ID. String cid = uri.getLastPathSegment(); builder.where(StudentContract.StudentCourse._ID + "=?", cid); case ROUTE_COURSE_ENTRIES: // Return all known entries. builder.table(StudentContract.StudentCourse.TABLE_NAME) .where(selection, selectionArgs); Cursor cc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context ctxc = getContext(); assert ctxc != null; cc.setNotificationUri(ctxc.getContentResolver(), uri); return cc; case ROUTE_TEMPLATE_ENTRIES_ID: // Return a single entry, by ID. String tid = uri.getLastPathSegment(); builder.where(StudentContract.TrainersTemplate._ID + "=?", tid); case ROUTE_TEMPLATE_ENTRIES: // Return all known entries. builder.table(StudentContract.TrainersTemplate.TABLE_NAME) .where(selection, selectionArgs); Cursor tc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context ttxc = getContext(); assert ttxc != null; tc.setNotificationUri(ttxc.getContentResolver(), uri); return tc; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES_ID: // Return a single entry, by ID. String sbid = uri.getLastPathSegment(); builder.where(StudentContract.StudentBatchdetails._ID + "=?", sbid); case ROUTE_STUDENT_BATCHDETAILS_ENTRIES: // Return all known entries. builder.table(StudentContract.StudentBatchdetails.TABLE_NAME) .where(selection, selectionArgs); Cursor sbc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context sbtxc = getContext(); assert sbtxc != null; sbc.setNotificationUri(sbtxc.getContentResolver(), uri); return sbc; case ROUTE_COMING_BATCHDETAILS_ENTRIES_ID: // Return a single entry, by ID. String cbid = uri.getLastPathSegment(); builder.where(StudentContract.ComingBatchdetails._ID + "=?", cbid); case ROUTE_COMING_BATCHDETAILS_ENTRIES: // Return all known entries. builder.table(StudentContract.ComingBatchdetails.TABLE_NAME) .where(selection, selectionArgs); Cursor cbc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context cbtxc = getContext(); assert cbtxc != null; cbc.setNotificationUri(cbtxc.getContentResolver(), uri); return cbc; case ROUTE_STUDENT_ATTENDANCE_ENTRIES_ID: // Return a single entry, by ID. String said = uri.getLastPathSegment(); builder.where(StudentContract.StudentAttendance._ID + "=?", said); case ROUTE_STUDENT_ATTENDANCE_ENTRIES: // Return all known entries. builder.table(StudentContract.StudentAttendance.TABLE_NAME) .where(selection, selectionArgs); Cursor sac = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context satxc = getContext(); assert satxc != null; sac.setNotificationUri(satxc.getContentResolver(), uri); return sac; case ROUTE_BRANCHES_ENTRIES_ID: // Return a single entry, by ID. String bid = uri.getLastPathSegment(); builder.where(StudentContract.Branches._ID + "=?", bid); case ROUTE_BRANCHES_ENTRIES: // Return all known entries. builder.table(StudentContract.Branches.TABLE_NAME) .where(selection, selectionArgs); Cursor bc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context bctxc = getContext(); assert bctxc != null; bc.setNotificationUri(bctxc.getContentResolver(), uri); return bc; case ROUTE_COURSES_ENTRIES_ID: // Return a single entry, by ID. String cdid = uri.getLastPathSegment(); builder.where(StudentContract.Courses._ID + "=?", cdid); case ROUTE_COURSES_ENTRIES: // Return all known entries. builder.table(StudentContract.Courses.TABLE_NAME) .where(selection, selectionArgs); Cursor cdc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context cdtxc = getContext(); assert cdtxc != null; cdc.setNotificationUri(cdtxc.getContentResolver(), uri); return cdc; case ROUTE_COURSE_TYPE_ENTRIES_ID: // Return a single entry, by ID. String ctid = uri.getLastPathSegment(); builder.where(StudentContract.CourseType._ID + "=?", ctid); case ROUTE_COURSE_TYPE_ENTRIES: // Return all known entries. builder.table(StudentContract.CourseType.TABLE_NAME) .where(selection, selectionArgs); Cursor ctc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context cttxc = getContext(); assert cttxc != null; ctc.setNotificationUri(cttxc.getContentResolver(), uri); return ctc; case ROUTE_DAYPREFRENCE_ENTRIES_ID: // Return a single entry, by ID. String dpid = uri.getLastPathSegment(); builder.where(StudentContract.DayPrefrence._ID + "=?", dpid); case ROUTE_DAYPREFRENCE_ENTRIES: // Return all known entries. builder.table(StudentContract.DayPrefrence.TABLE_NAME) .where(selection, selectionArgs); Cursor dpc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context dptxc = getContext(); assert dptxc != null; dpc.setNotificationUri(dptxc.getContentResolver(), uri); return dpc; case ROUTE_USERDAYPREFRENCE_ENTRIES_ID: // Return a single entry, by ID. String udid = uri.getLastPathSegment(); builder.where(StudentContract.UserDayPrefrence._ID + "=?", udid); case ROUTE_USERDAYPREFRENCE_ENTRIES: // Return all known entries. builder.table(StudentContract.UserDayPrefrence.TABLE_NAME) .where(selection, selectionArgs); Cursor udc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context udtxc = getContext(); assert udtxc != null; udc.setNotificationUri(udtxc.getContentResolver(), uri); return udc; case ROUTE_STUDENTCOMMENTS_ENTRIES_ID: // Return a single entry, by ID. String scid = uri.getLastPathSegment(); builder.where(StudentContract.StudentComments._ID + "=?", scid); case ROUTE_STUDENTCOMMENTS_ENTRIES: // Return all known entries. builder.table(StudentContract.StudentComments.TABLE_NAME) .where(selection, selectionArgs); Cursor scdc = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to correctly // register ContentObservers. Context sctxc = getContext(); assert sctxc != null; scdc.setNotificationUri(sctxc.getContentResolver(), uri); return scdc; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** * Insert a new entry into the database. */ @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); assert db != null; final int match = sUriMatcher.match(uri); Uri result; switch (match) { case ROUTE_ENTRIES: long id = db.insertOrThrow(StudentContract.Entry.TABLE_NAME, null, values); result = Uri.parse(StudentContract.Entry.CONTENT_URI + "/" + id); break; case ROUTE_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_LOC_ENTRIES: long idl = db.insertOrThrow(StudentContract.StudentLocation.TABLE_NAME, null, values); result = Uri.parse(StudentContract.StudentLocation.CONTENT_URI + "/" + idl); break; case ROUTE_LOC_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_COURSE_ENTRIES: long idc = db.insertOrThrow(StudentContract.StudentCourse.TABLE_NAME, null, values); result = Uri.parse(StudentContract.StudentCourse.CONTENT_URI + "/" + idc); break; case ROUTE_COURSE_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_TEMPLATE_ENTRIES: long idt = db.insertOrThrow(StudentContract.TrainersTemplate.TABLE_NAME, null, values); result = Uri.parse(StudentContract.TrainersTemplate.CONTENT_URI + "/" + idt); break; case ROUTE_TEMPLATE_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_STUDENT_BATCHDETAILS_ENTRIES: long idsb = db.insertOrThrow(StudentContract.StudentBatchdetails.TABLE_NAME, null, values); result = Uri.parse(StudentContract.StudentBatchdetails.CONTENT_URI + "/" + idsb); break; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_COMING_BATCHDETAILS_ENTRIES: long cdsb = db.insertOrThrow(StudentContract.ComingBatchdetails.TABLE_NAME, null, values); result = Uri.parse(StudentContract.ComingBatchdetails.CONTENT_URI + "/" + cdsb); break; case ROUTE_COMING_BATCHDETAILS_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_STUDENT_ATTENDANCE_ENTRIES: long csa = db.insertOrThrow(StudentContract.StudentAttendance.TABLE_NAME, null, values); result = Uri.parse(StudentContract.StudentAttendance.CONTENT_URI + "/" + csa); break; case ROUTE_STUDENT_ATTENDANCE_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_BRANCHES_ENTRIES: long cb = db.insertOrThrow(StudentContract.Branches.TABLE_NAME, null, values); result = Uri.parse(StudentContract.Branches.CONTENT_URI + "/" + cb); break; case ROUTE_BRANCHES_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_COURSES_ENTRIES: long cdb = db.insertOrThrow(StudentContract.Courses.TABLE_NAME, null, values); result = Uri.parse(StudentContract.Courses.CONTENT_URI + "/" + cdb); break; case ROUTE_COURSES_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_COURSE_TYPE_ENTRIES: long ctb = db.insertOrThrow(StudentContract.CourseType.TABLE_NAME, null, values); result = Uri.parse(StudentContract.CourseType.CONTENT_URI + "/" + ctb); break; case ROUTE_COURSE_TYPE_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_DAYPREFRENCE_ENTRIES: long cdp = db.insertOrThrow(StudentContract.DayPrefrence.TABLE_NAME, null, values); result = Uri.parse(StudentContract.DayPrefrence.CONTENT_URI + "/" + cdp); break; case ROUTE_DAYPREFRENCE_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_USERDAYPREFRENCE_ENTRIES: long cud = db.insertOrThrow(StudentContract.UserDayPrefrence.TABLE_NAME, null, values); result = Uri.parse(StudentContract.DayPrefrence.CONTENT_URI + "/" + cud); break; case ROUTE_USERDAYPREFRENCE_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); case ROUTE_STUDENTCOMMENTS_ENTRIES: long scd = db.insertOrThrow(StudentContract.StudentComments.TABLE_NAME, null, values); result = Uri.parse(StudentContract.StudentComments.CONTENT_URI + "/" + scd); break; case ROUTE_STUDENTCOMMENTS_ENTRIES_ID: throw new UnsupportedOperationException("Insert not supported on URI: " + uri); default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Send broadcast to registered ContentObservers, to refresh UI. Context ctx = getContext(); assert ctx != null; ctx.getContentResolver().notifyChange(uri, null, false); return result; } /** * Delete an entry by database by URI. */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SelectionBuilder builder = new SelectionBuilder(); final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int count; switch (match) { case ROUTE_ENTRIES: count = builder.table(StudentContract.Entry.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_ENTRIES_ID: String id = uri.getLastPathSegment(); count = builder.table(StudentContract.Entry.TABLE_NAME) .where(StudentContract.Entry._ID + "=?", id) .where(selection, selectionArgs) .delete(db); break; case ROUTE_LOC_ENTRIES: count = builder.table(StudentContract.StudentLocation.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_LOC_ENTRIES_ID: String idl = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentLocation.TABLE_NAME) .where(StudentContract.StudentLocation._ID + "=?", idl) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COURSE_ENTRIES: count = builder.table(StudentContract.StudentCourse.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COURSE_ENTRIES_ID: String idc = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentCourse.TABLE_NAME) .where(StudentContract.StudentCourse._ID + "=?", idc) .where(selection, selectionArgs) .delete(db); break; case ROUTE_TEMPLATE_ENTRIES: count = builder.table(StudentContract.TrainersTemplate.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_TEMPLATE_ENTRIES_ID: String idt = uri.getLastPathSegment(); count = builder.table(StudentContract.TrainersTemplate.TABLE_NAME) .where(StudentContract.TrainersTemplate._ID + "=?", idt) .where(selection, selectionArgs) .delete(db); break; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES: count = builder.table(StudentContract.StudentBatchdetails.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES_ID: String idsb = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentBatchdetails.TABLE_NAME) .where(StudentContract.StudentBatchdetails._ID + "=?", idsb) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COMING_BATCHDETAILS_ENTRIES: count = builder.table(StudentContract.ComingBatchdetails.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COMING_BATCHDETAILS_ENTRIES_ID: String idcb = uri.getLastPathSegment(); count = builder.table(StudentContract.ComingBatchdetails.TABLE_NAME) .where(StudentContract.ComingBatchdetails._ID + "=?", idcb) .where(selection, selectionArgs) .delete(db); break; case ROUTE_STUDENT_ATTENDANCE_ENTRIES: count = builder.table(StudentContract.StudentAttendance.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_STUDENT_ATTENDANCE_ENTRIES_ID: String idsa = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentAttendance.TABLE_NAME) .where(StudentContract.StudentAttendance._ID + "=?", idsa) .where(selection, selectionArgs) .delete(db); break; case ROUTE_BRANCHES_ENTRIES: count = builder.table(StudentContract.Branches.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_BRANCHES_ENTRIES_ID: String idb = uri.getLastPathSegment(); count = builder.table(StudentContract.Branches.TABLE_NAME) .where(StudentContract.Branches._ID + "=?", idb) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COURSES_ENTRIES: count = builder.table(StudentContract.Courses.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COURSES_ENTRIES_ID: String idcd = uri.getLastPathSegment(); count = builder.table(StudentContract.Courses.TABLE_NAME) .where(StudentContract.Courses._ID + "=?", idcd) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COURSE_TYPE_ENTRIES: count = builder.table(StudentContract.CourseType.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_COURSE_TYPE_ENTRIES_ID: String idct = uri.getLastPathSegment(); count = builder.table(StudentContract.CourseType.TABLE_NAME) .where(StudentContract.CourseType._ID + "=?", idct) .where(selection, selectionArgs) .delete(db); break; case ROUTE_DAYPREFRENCE_ENTRIES: count = builder.table(StudentContract.DayPrefrence.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_DAYPREFRENCE_ENTRIES_ID: String iddp = uri.getLastPathSegment(); count = builder.table(StudentContract.DayPrefrence.TABLE_NAME) .where(StudentContract.DayPrefrence._ID + "=?", iddp) .where(selection, selectionArgs) .delete(db); break; case ROUTE_USERDAYPREFRENCE_ENTRIES: count = builder.table(StudentContract.UserDayPrefrence.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_USERDAYPREFRENCE_ENTRIES_ID: String idud = uri.getLastPathSegment(); count = builder.table(StudentContract.UserDayPrefrence.TABLE_NAME) .where(StudentContract.UserDayPrefrence._ID + "=?", idud) .where(selection, selectionArgs) .delete(db); break; case ROUTE_STUDENTCOMMENTS_ENTRIES: count = builder.table(StudentContract.StudentComments.TABLE_NAME) .where(selection, selectionArgs) .delete(db); break; case ROUTE_STUDENTCOMMENTS_ENTRIES_ID: String idsc = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentComments.TABLE_NAME) .where(StudentContract.StudentComments._ID + "=?", idsc) .where(selection, selectionArgs) .delete(db); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Send broadcast to registered ContentObservers, to refresh UI. Context ctx = getContext(); assert ctx != null; ctx.getContentResolver().notifyChange(uri, null, false); return count; } /** * Update an etry in the database by URI. */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SelectionBuilder builder = new SelectionBuilder(); final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int count; switch (match) { case ROUTE_ENTRIES: count = builder.table(StudentContract.Entry.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_ENTRIES_ID: String id = uri.getLastPathSegment(); count = builder.table(StudentContract.Entry.TABLE_NAME) .where(StudentContract.Entry._ID + "=?", id) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_LOC_ENTRIES: count = builder.table(StudentContract.StudentLocation.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_LOC_ENTRIES_ID: String idl = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentLocation.TABLE_NAME) .where(StudentContract.StudentLocation._ID + "=?", idl) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COURSE_ENTRIES: count = builder.table(StudentContract.StudentCourse.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COURSE_ENTRIES_ID: String idc = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentCourse.TABLE_NAME) .where(StudentContract.StudentCourse._ID + "=?", idc) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_TEMPLATE_ENTRIES: count = builder.table(StudentContract.TrainersTemplate.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_TEMPLATE_ENTRIES_ID: String idt = uri.getLastPathSegment(); count = builder.table(StudentContract.TrainersTemplate.TABLE_NAME) .where(StudentContract.TrainersTemplate._ID + "=?", idt) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES: count = builder.table(StudentContract.StudentBatchdetails.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_STUDENT_BATCHDETAILS_ENTRIES_ID: String idsb = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentBatchdetails.TABLE_NAME) .where(StudentContract.StudentBatchdetails._ID + "=?", idsb) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COMING_BATCHDETAILS_ENTRIES: count = builder.table(StudentContract.ComingBatchdetails.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COMING_BATCHDETAILS_ENTRIES_ID: String idcb = uri.getLastPathSegment(); count = builder.table(StudentContract.ComingBatchdetails.TABLE_NAME) .where(StudentContract.ComingBatchdetails._ID + "=?", idcb) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_STUDENT_ATTENDANCE_ENTRIES: count = builder.table(StudentContract.StudentAttendance.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_STUDENT_ATTENDANCE_ENTRIES_ID: String idsa = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentAttendance.TABLE_NAME) .where(StudentContract.StudentAttendance._ID + "=?", idsa) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_BRANCHES_ENTRIES: count = builder.table(StudentContract.Branches.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_BRANCHES_ENTRIES_ID: String idb = uri.getLastPathSegment(); count = builder.table(StudentContract.Branches.TABLE_NAME) .where(StudentContract.Branches._ID + "=?", idb) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COURSES_ENTRIES: count = builder.table(StudentContract.Courses.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COURSES_ENTRIES_ID: String idcd = uri.getLastPathSegment(); count = builder.table(StudentContract.Courses.TABLE_NAME) .where(StudentContract.Courses._ID + "=?", idcd) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COURSE_TYPE_ENTRIES: count = builder.table(StudentContract.CourseType.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_COURSE_TYPE_ENTRIES_ID: String idct = uri.getLastPathSegment(); count = builder.table(StudentContract.CourseType.TABLE_NAME) .where(StudentContract.CourseType._ID + "=?", idct) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_DAYPREFRENCE_ENTRIES: count = builder.table(StudentContract.DayPrefrence.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_DAYPREFRENCE_ENTRIES_ID: String iddp = uri.getLastPathSegment(); count = builder.table(StudentContract.DayPrefrence.TABLE_NAME) .where(StudentContract.DayPrefrence._ID + "=?", iddp) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_USERDAYPREFRENCE_ENTRIES: count = builder.table(StudentContract.UserDayPrefrence.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_USERDAYPREFRENCE_ENTRIES_ID: String idud = uri.getLastPathSegment(); count = builder.table(StudentContract.UserDayPrefrence.TABLE_NAME) .where(StudentContract.UserDayPrefrence._ID + "=?", idud) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_STUDENTCOMMENTS_ENTRIES: count = builder.table(StudentContract.StudentComments.TABLE_NAME) .where(selection, selectionArgs) .update(db, values); break; case ROUTE_STUDENTCOMMENTS_ENTRIES_ID: String idsc = uri.getLastPathSegment(); count = builder.table(StudentContract.StudentComments.TABLE_NAME) .where(StudentContract.StudentComments._ID + "=?", idsc) .where(selection, selectionArgs) .update(db, values); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } Context ctx = getContext(); assert ctx != null; ctx.getContentResolver().notifyChange(uri, null, false); return count; } /** * SQLite backend for @{link FeedProvider}. * <p> * Provides access to an disk-backed, SQLite datastore which is utilized by FeedProvider. This * database should never be accessed by other parts of the application directly. */ public static class AFCKSDatabase extends SQLiteOpenHelper { /** * Schema version. */ public static final int DATABASE_VERSION = 1; /** * Filename for SQLite file. */ public static final String DATABASE_NAME = "dbafcks.db"; private static final String TYPE_TEXT = " TEXT"; private static final String TYPE_INTEGER = " INTEGER"; private static final String TYPE_REAL = " REAL"; private static final String COMMA_SEP = ","; /** * SQL statement to create "users" table. */ private static final String SQL_CREATE_USERS = "CREATE TABLE " + StudentContract.Entry.TABLE_NAME + " (" + StudentContract.Entry._ID + " INTEGER PRIMARY KEY," + StudentContract.Entry.COLUMN_NAME_ENTRY_ID + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_FIRST_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_LAST_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_MOBILE_NO + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_EMAIL_ID + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_GENDER + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_FCM_ID + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_CREATED_AT + TYPE_INTEGER + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_STATUS + TYPE_INTEGER + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_NOTES + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_PREFERENCE + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_CALLBACK + TYPE_INTEGER + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_ENQNOTES + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_NICK_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_NATIONALITY + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_DOB + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_MARITAL_STATUS + TYPE_INTEGER + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_PROFILE_PIC + TYPE_TEXT + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_JOB_SEARCH_STATUS + TYPE_INTEGER + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_JOB_PROGRAM_STATUS + TYPE_INTEGER + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_CURRENT_CTC + TYPE_REAL + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_EXPECTED_FROM_CTC + TYPE_REAL + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_EXPECTED_TO_CTC + TYPE_REAL + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_U_TIMESTAMP + TYPE_INTEGER + COMMA_SEP + StudentContract.Entry.COLUMN_NAME_SYNC_STATUS + TYPE_INTEGER + ")"; /** * SQL statement to drop "users" table. */ /** * SQL statement to create "Location" table. */ private static final String SQL_CREATE_USERS_LOC = "CREATE TABLE " + StudentContract.StudentLocation.TABLE_NAME + "(" + StudentContract.StudentLocation._ID + " INTEGER PRIMARY KEY," + StudentContract.StudentLocation.COLUMN_NAME_S_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentLocation.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentLocation.COLUMN_NAME_BRANCH_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentLocation.COLUMN_NAME_USER_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentLocation.COLUMN_NAME_U_TIMESTAMP + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentLocation.COLUMN_NAME_SYNC_STATUS + TYPE_INTEGER + COMMA_SEP + "UNIQUE("+StudentContract.StudentLocation.COLUMN_NAME_BRANCH_NAME+COMMA_SEP+StudentContract.StudentLocation.COLUMN_NAME_USER_ID+")" +")"; /** * SQL statement to drop "location" table. */ /** * SQL statement to create "Course" table. */ private static final String SQL_CREATE_USERS_COURSE = "CREATE TABLE " + StudentContract.StudentCourse.TABLE_NAME + " (" + StudentContract.StudentCourse._ID + " INTEGER PRIMARY KEY," + StudentContract.StudentCourse.COLUMN_NAME_S_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_TYPE_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_TYPE_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_COURSE_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_COURSE_CODE + TYPE_TEXT + COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_USER_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_U_TIMESTAMP + TYPE_INTEGER+ COMMA_SEP + StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS + TYPE_INTEGER + COMMA_SEP + "UNIQUE("+StudentContract.StudentCourse.COLUMN_NAME_COURSE_NAME+COMMA_SEP+StudentContract.StudentCourse.COLUMN_NAME_USER_ID+")" +")"; /** * SQL statement to drop "Course" table. */ /** * SQL statement to create "template" table. */ private static final String SQL_CREATE_TRAINER_TEMPLATE = "CREATE TABLE " + StudentContract.TrainersTemplate.TABLE_NAME + " (" + StudentContract.TrainersTemplate._ID + " INTEGER PRIMARY KEY," + StudentContract.TrainersTemplate.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.TrainersTemplate.COLUMN_NAME_SUBJECT + TYPE_TEXT + COMMA_SEP + StudentContract.TrainersTemplate.COLUMN_NAME_TEMPLATE_TEXT + TYPE_TEXT + COMMA_SEP + StudentContract.TrainersTemplate.COLUMN_NAME_TAG + TYPE_TEXT + COMMA_SEP + StudentContract.TrainersTemplate.COLUMN_NAME_COURSE_MAP_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.TrainersTemplate.COLUMN_NAME_LOCATION_MAP_ID + TYPE_INTEGER + ")"; /** * SQL statement to drop "template" table. */ /** * SQL statement to create "users" table. */ private static final String SQL_CREATE_STUDENT_BATCHDETAILS = "CREATE TABLE " + StudentContract.StudentBatchdetails.TABLE_NAME + " (" + StudentContract.StudentBatchdetails._ID + " INTEGER PRIMARY KEY," + StudentContract.StudentBatchdetails.COLUMN_NAME_SBD_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_FIRST_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_LAST_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_MOBILE_NO + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_EMAIL_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_GENDER + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_BATCH_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_BATCH_CODE + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_STUDENT_BATCH_CAT + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_STATUS + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_PREVIOUS_ATTENDANCE + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_COURSE_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_COURSE_CODE + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_NOTES_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_DISCONTINUE_REASON + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_STUDENTS_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_FEES + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_BASEFEES + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_DUE_AMOUNT + TYPE_TEXT + COMMA_SEP + StudentContract.StudentBatchdetails.COLUMN_NAME_START_DATE + TYPE_TEXT + ")"; /** * SQL statement to drop "users" table. */ /** * SQL statement to create "Course" table. */ private static final String SQL_CREATE_COMING_BATCH_DETAILS = "CREATE TABLE " + StudentContract.ComingBatchdetails.TABLE_NAME + " (" + StudentContract.ComingBatchdetails._ID + " INTEGER PRIMARY KEY," + StudentContract.ComingBatchdetails.COLUMN_NAME_ENTRY_ID + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_BATCH_TYPE + TYPE_INTEGER + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_BRANCH_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_COURSE_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_COURSE_ID + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_DURATION + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_FACULTY_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_FEES + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_NEW_START_DATE + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_FREQUENCY + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_NOTES + TYPE_TEXT + COMMA_SEP + StudentContract.ComingBatchdetails.COLUMN_NAME_TIMINGS + TYPE_TEXT + ")"; /** * SQL statement to drop "Course" table. */ /** * SQL statement to create "Course" table. */ private static final String SQL_CREATE_STUDENT_ATTENDANCE = "CREATE TABLE " + StudentContract.StudentAttendance.TABLE_NAME + " (" + StudentContract.StudentAttendance._ID + " INTEGER PRIMARY KEY," + StudentContract.StudentAttendance.COLUMN_NAME_ENTRY_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentAttendance.COLUMN_NAME_USER_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentAttendance.COLUMN_NAME_BATCH_ID + TYPE_TEXT + COMMA_SEP + StudentContract.StudentAttendance.COLUMN_NAME_ATTENDANCE + TYPE_TEXT + COMMA_SEP + StudentContract.StudentAttendance.COLUMN_NAME_STUDENT_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.StudentAttendance.COLUMN_NAME_BATCH_DATE + TYPE_TEXT + COMMA_SEP + StudentContract.StudentAttendance.COLUMN_NAME_ATTENDANCEDATE + TYPE_TEXT + ")"; /** * SQL statement to drop "Course" table. */ /** * SQL statement to create "template" table. */ private static final String SQL_CREATE_BRANCHES = "CREATE TABLE " + StudentContract.Branches.TABLE_NAME + " (" + StudentContract.Branches._ID + " INTEGER PRIMARY KEY," + StudentContract.Branches.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.Branches.COLUMN_NAME_BRANCH_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.Branches.COLUMN_NAME_LATITUDE + TYPE_REAL + COMMA_SEP + StudentContract.Branches.COLUMN_NAME_LONGITUDE + TYPE_REAL + COMMA_SEP + StudentContract.Branches.COLUMN_NAME_BRANCH_SHORT + TYPE_TEXT + COMMA_SEP + StudentContract.Branches.COLUMN_NAME_ADDRESS + TYPE_TEXT + COMMA_SEP + StudentContract.Branches.COLUMN_NAME_M_TIMESTAMP + TYPE_INTEGER + ")"; /** * SQL statement to drop "template" table. */ /** * SQL statement to create "template" table. */ private static final String SQL_CREATE_COURSES = "CREATE TABLE " + StudentContract.Courses.TABLE_NAME + " (" + StudentContract.Courses._ID + " INTEGER PRIMARY KEY," + StudentContract.Courses.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_COURSE_TYPE_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_COURSE_CODE + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_COURSE_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_TIME_DURATION + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_PREREQUISITE + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_RECOMMONDED + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_FEES + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_SYLLABUSPATH + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_YOU_TUBE_LINK + TYPE_TEXT + COMMA_SEP + StudentContract.Courses.COLUMN_NAME_M_TIMESTAMP + TYPE_INTEGER + ")"; /** * SQL statement to drop "template" table. */ /** * SQL statement to create "template" table. */ private static final String SQL_CREATE_COURSETYPE = "CREATE TABLE " + StudentContract.CourseType.TABLE_NAME + " (" + StudentContract.CourseType._ID + " INTEGER PRIMARY KEY," + StudentContract.CourseType.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.CourseType.COLUMN_NAME_TYPE_NAME + TYPE_TEXT + COMMA_SEP + StudentContract.CourseType.COLUMN_NAME_M_TIMESTAMP + TYPE_INTEGER + ")"; /** * SQL statement to drop "template" table. */ /** * SQL statement to create "template" table. */ private static final String SQL_CREATE_DAYPREFRENCE = "CREATE TABLE " + StudentContract.DayPrefrence.TABLE_NAME + " (" + StudentContract.DayPrefrence._ID + " INTEGER PRIMARY KEY," + StudentContract.DayPrefrence.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.DayPrefrence.COLUMN_NAME_PREFRENCE + TYPE_TEXT + COMMA_SEP + StudentContract.DayPrefrence.COLUMN_NAME_M_TIMESTAMP + TYPE_INTEGER + ")"; /** * SQL statement to drop "template" table. */ /** * SQL statement to create "template" table. */ private static final String SQL_CREATE_USERDAYPREFRENCE = "CREATE TABLE " + StudentContract.UserDayPrefrence.TABLE_NAME + " (" + StudentContract.UserDayPrefrence._ID + " INTEGER PRIMARY KEY," + StudentContract.UserDayPrefrence.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.UserDayPrefrence.COLUMN_NAME_USER_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.UserDayPrefrence.COLUMN_NAME_DAYPREFRENCE_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.UserDayPrefrence.COLUMN_NAME_DEL_STATUS + TYPE_INTEGER + COMMA_SEP + StudentContract.UserDayPrefrence.COLUMN_NAME_M_TIMESTAMP + TYPE_INTEGER + COMMA_SEP + StudentContract.UserDayPrefrence.COLUMN_NAME_SYNC_STATUS + TYPE_INTEGER + ")"; /** * SQL statement to drop "template" table. */ /** * SQL statement to create "template" table. */ private static final String SQL_CREATE_STUDENTCOMMENTS = "CREATE TABLE " + StudentContract.StudentComments.TABLE_NAME + " (" + StudentContract.StudentComments._ID + " INTEGER PRIMARY KEY," + StudentContract.StudentComments.COLUMN_NAME_ENTRY_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentComments.COLUMN_NAME_USER_ID + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentComments.COLUMN_NAME_STUDENT_COMMENT + TYPE_TEXT + COMMA_SEP + StudentContract.StudentComments.COLUMN_NAME_COMMENTS_DATE + TYPE_TEXT + COMMA_SEP + StudentContract.StudentComments.COLUMN_NAME_M_TIMESTAMP + TYPE_INTEGER + COMMA_SEP + StudentContract.StudentComments.COLUMN_NAME_SYNC_STATUS + TYPE_INTEGER + ")"; /** * SQL statement to drop "template" table. */ /** * SQL statement to drop "users" view. */ private static final String SQL_CREATE_VIEW_USERS = "CREATE VIEW vwSearchUsers AS select users.id AS id,users.gender AS gender,users.first_name AS first_name,users.last_name AS last_name,users.mobile_no AS mobile_no,users.email_id AS email_id,trim(users.first_name||' '||users.last_name||' '||users.mobile_no||' '||users.email_id||' '||users.gender) AS Details,sync_status,status from users where sync_status<3"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + StudentContract.Entry.TABLE_NAME; /** * SQL statement to drop "location" table. */ private static final String SQL_DELETE_LOC_ENTRIES = "DROP TABLE IF EXISTS " + StudentContract.StudentLocation.TABLE_NAME; /** * SQL statement to drop "course" table. */ private static final String SQL_DELETE_COURSE_ENTRIES = "DROP TABLE IF EXISTS " + StudentContract.StudentCourse.TABLE_NAME; /** * SQL statement to drop "template" table. */ private static final String SQL_DELETE_TEMPLATE_ENTRIES = "DROP TABLE IF EXISTS " + StudentContract.TrainersTemplate.TABLE_NAME; /** * SQL statement to drop "template" table. */ private static final String SQL_DELETE_STUDENT_BATCHDETAILS_ENTRIES = "DROP TABLE IF EXISTS " + StudentContract.StudentBatchdetails.TABLE_NAME; /** * SQL statement to drop "template" view. */ /** * SQL statement to drop "coming batches" table. */ private static final String SQL_DELETE_COMING_BATCHDETAILS_ENTRIES = "DROP TABLE IF EXISTS " + StudentContract.ComingBatchdetails.TABLE_NAME; /** * SQL statement to drop "template" view. */ /** * SQL statement to drop "coming batches" table. */ private static final String SQL_DELETE_STUDENT_ATTENDANCE = "DROP TABLE IF EXISTS " + StudentContract.StudentAttendance.TABLE_NAME; /** * SQL statement to drop "coming Branches" table. */ private static final String SQL_DELETE_BRANCHES = "DROP TABLE IF EXISTS " + StudentContract.Branches.TABLE_NAME; /** * SQL statement to drop "coming Branches" table. */ private static final String SQL_DELETE_COURSES = "DROP TABLE IF EXISTS " + StudentContract.Courses.TABLE_NAME; /** * SQL statement to drop "coming Branches" table. */ private static final String SQL_DELETE_COURSETYPE = "DROP TABLE IF EXISTS " + StudentContract.CourseType.TABLE_NAME; /** * SQL statement to drop "coming Branches" table. */ private static final String SQL_DELETE_DAYPREFRENCE = "DROP TABLE IF EXISTS " + StudentContract.DayPrefrence.TABLE_NAME; /** * SQL statement to drop "coming Branches" table. */ private static final String SQL_DELETE_USERDAYPREFRENCE = "DROP TABLE IF EXISTS " + StudentContract.UserDayPrefrence.TABLE_NAME; /** * SQL statement to drop "template" view. */ private static final String SQL_DELETE_USER_VIEW = "DROP VIEW IF EXISTS vwSearchUsers"; /** * SQL statement to drop "template" view. */ private static final String SQL_DELETE_STUDENTCOMMENTS = "DROP TABLE IF EXISTS " + StudentContract.StudentComments.TABLE_NAME; public AFCKSDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_USERS); db.execSQL(SQL_CREATE_USERS_LOC); db.execSQL(SQL_CREATE_USERS_COURSE); db.execSQL(SQL_CREATE_TRAINER_TEMPLATE); db.execSQL(SQL_CREATE_STUDENT_BATCHDETAILS); db.execSQL(SQL_CREATE_VIEW_USERS); db.execSQL(SQL_CREATE_COMING_BATCH_DETAILS); db.execSQL(SQL_CREATE_STUDENT_ATTENDANCE); db.execSQL(SQL_CREATE_BRANCHES); db.execSQL(SQL_CREATE_COURSES); db.execSQL(SQL_CREATE_COURSETYPE); db.execSQL(SQL_CREATE_DAYPREFRENCE); db.execSQL(SQL_CREATE_USERDAYPREFRENCE); db.execSQL(SQL_CREATE_STUDENTCOMMENTS); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over db.execSQL(SQL_DELETE_ENTRIES); db.execSQL(SQL_DELETE_LOC_ENTRIES); db.execSQL(SQL_DELETE_COURSE_ENTRIES); db.execSQL(SQL_DELETE_TEMPLATE_ENTRIES); db.execSQL(SQL_DELETE_STUDENT_BATCHDETAILS_ENTRIES); db.execSQL(SQL_DELETE_COMING_BATCHDETAILS_ENTRIES); db.execSQL(SQL_DELETE_STUDENT_ATTENDANCE); db.execSQL(SQL_DELETE_USER_VIEW); db.execSQL(SQL_DELETE_BRANCHES); db.execSQL(SQL_DELETE_COURSES); db.execSQL(SQL_DELETE_COURSETYPE); db.execSQL(SQL_DELETE_DAYPREFRENCE); db.execSQL(SQL_DELETE_USERDAYPREFRENCE); db.execSQL(SQL_DELETE_STUDENTCOMMENTS); onCreate(db); } //fetching data public Cursor getUserId(String mobile_no) { String mno = "\"" + mobile_no + "\""; SQLiteDatabase db = this.getReadableDatabase(); String sql = "select * from " + StudentContract.Entry.TABLE_NAME + " where " + StudentContract.Entry.COLUMN_NAME_MOBILE_NO + " = " + mno + ""; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getSerachUser(String search) { String COLUMN_DETAILS_NAME = "Details"; SQLiteDatabase db = this.getReadableDatabase(); //String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_STATUS + " <> 3 ORDER BY " + COLUMN_ID + " ASC;"; String sql = "SELECT * FROM vwSearchUsers " + " where "+ StudentContract.Entry.COLUMN_NAME_MOBILE_NO + " like '%" + search + "%' or " + COLUMN_DETAILS_NAME + " like '%" + search + "%'"; // "Select id,dept_name from vwDepartments where dept_name Like '%$Prefixtext%' or group_user_name Like '%$Prefixtext%'" Cursor c = db.rawQuery(sql, null); return c; } public Cursor getLocNames(String user_id) { SQLiteDatabase db = this.getReadableDatabase(); String sql = "select * from " + StudentContract.StudentLocation.TABLE_NAME + " where " + StudentContract.StudentLocation.COLUMN_NAME_SYNC_STATUS + "<3 "+" and "+StudentContract.StudentLocation.COLUMN_NAME_USER_ID + " = '" + user_id + "'"; Cursor c = db.rawQuery(sql, null); return c; } public boolean updateLocDeleteStatus(String user_id, int locid,int status) { String temp_id = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.StudentLocation.COLUMN_NAME_SYNC_STATUS , status); db.update(StudentContract.StudentLocation.TABLE_NAME, contentValues, StudentContract.StudentLocation.COLUMN_NAME_USER_ID + "=" + temp_id+" and "+StudentContract.StudentLocation.COLUMN_NAME_ENTRY_ID + "=" + locid, null); db.close(); return true; } public void deleteLoc(String id, String user_id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(StudentContract.StudentLocation.TABLE_NAME, StudentContract.StudentLocation.COLUMN_NAME_ENTRY_ID + "=? AND " + StudentContract.StudentLocation.COLUMN_NAME_USER_ID + "=? ", new String[]{id, user_id}); db.close(); } public Cursor getCourseNames(String user_id) { SQLiteDatabase db = this.getReadableDatabase(); String sql = "select * from " + StudentContract.StudentCourse.TABLE_NAME + " where " + StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS +"<3"+" and "+StudentContract.StudentCourse.COLUMN_NAME_USER_ID + " = '" + user_id + "'"; Cursor c = db.rawQuery(sql, null); return c; } public boolean updateCourseDeleteStatus(String user_id, int cid,int status) { String temp_id = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS , status); db.update(StudentContract.StudentCourse.TABLE_NAME, contentValues, StudentContract.StudentCourse.COLUMN_NAME_USER_ID + "=" + temp_id+" and "+StudentContract.StudentCourse.COLUMN_NAME_ENTRY_ID + "=" + cid, null); db.close(); return true; } public void deleteCourse(String id, String user_id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(StudentContract.StudentCourse.TABLE_NAME, StudentContract.StudentCourse.COLUMN_NAME_ENTRY_ID + "=? AND " + StudentContract.StudentCourse.COLUMN_NAME_USER_ID + "=? ", new String[]{id, user_id}); db.close(); } public boolean updateDayPreDeleteStatus(String user_id, int did,int status) { String temp_id = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS , status); db.update(StudentContract.UserDayPrefrence.TABLE_NAME, contentValues, StudentContract.UserDayPrefrence.COLUMN_NAME_USER_ID + "=" + temp_id+" and "+StudentContract.UserDayPrefrence.COLUMN_NAME_DAYPREFRENCE_ID + "=" + did, null); db.close(); return true; } public void deleteUserDayPre(String id, String user_id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(StudentContract.UserDayPrefrence.TABLE_NAME, StudentContract.UserDayPrefrence.COLUMN_NAME_DAYPREFRENCE_ID + " = " + Integer.parseInt(id) + "" + " and " + StudentContract.UserDayPrefrence.COLUMN_NAME_USER_ID + " = " + Integer.parseInt(user_id) + "", null); db.close(); } public String getConDisCountUsers(int user_id) { String count = ""; int c1 = 0, c2 = 0,c3=0; SQLiteDatabase db = this.getReadableDatabase(); String sql = "select count(Status) as Cont from " + StudentContract.StudentBatchdetails.TABLE_NAME + " where " + StudentContract.StudentBatchdetails.COLUMN_NAME_ENTRY_ID + " = " + user_id + "" + " and " + StudentContract.StudentBatchdetails.COLUMN_NAME_STATUS + " = 1 "+ " and " + StudentContract.StudentBatchdetails.COLUMN_NAME_STUDENT_BATCH_CAT + " <> 5 "; Cursor c = db.rawQuery(sql, null); assert c != null; if (c.moveToFirst()) { do { c1 = c.getInt(c.getColumnIndex("Cont")); } while (c.moveToNext()); } String sql1 = "select count(Status) as DisCont from " + StudentContract.StudentBatchdetails.TABLE_NAME + " where " + StudentContract.StudentBatchdetails.COLUMN_NAME_ENTRY_ID + " = " + user_id + "" + " and " + StudentContract.StudentBatchdetails.COLUMN_NAME_STATUS + " = 0 "+ " and " + StudentContract.StudentBatchdetails.COLUMN_NAME_STUDENT_BATCH_CAT + " <> 5 "; Cursor cc = db.rawQuery(sql1, null); assert cc != null; if (cc.moveToFirst()) { do { c2 = cc.getInt(cc.getColumnIndex("DisCont")); } while (cc.moveToNext()); } String sql2 = "select count(Status) as Demo from " + StudentContract.StudentBatchdetails.TABLE_NAME + " where " + StudentContract.StudentBatchdetails.COLUMN_NAME_ENTRY_ID + " = " + user_id + "" + " and " + StudentContract.StudentBatchdetails.COLUMN_NAME_STATUS + " = 1 "+ " and " + StudentContract.StudentBatchdetails.COLUMN_NAME_STUDENT_BATCH_CAT + " = 5 "; Cursor ccc = db.rawQuery(sql2, null); assert ccc != null; if (ccc.moveToFirst()) { do { c3 = ccc.getInt(ccc.getColumnIndex("Demo")); } while (ccc.moveToNext()); } count = "(" + c1 + ", " + c2 + ", " + c3 +")"; return count; } public String getUserNotes(String user_id) { String s = ""; SQLiteDatabase db = this.getReadableDatabase(); String sql = "select Notes from " + StudentContract.Entry.TABLE_NAME + " where " + StudentContract.Entry.COLUMN_NAME_ENTRY_ID + " = '" + user_id + "'"; Cursor cursor = db.rawQuery(sql, null); if (cursor.moveToFirst()) { do { s = cursor.getString(cursor.getColumnIndex("Notes")); } while (cursor.moveToNext()); } return s; } public Cursor getPreBatchStudentDetails(int user_id) { SQLiteDatabase db = this.getReadableDatabase(); String sql = "select * from " + StudentContract.StudentBatchdetails.TABLE_NAME + " where " + StudentContract.StudentBatchdetails.COLUMN_NAME_ENTRY_ID + " = " + user_id + ""; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getTemplatesDetails() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "select * from " + StudentContract.TrainersTemplate.TABLE_NAME; Cursor c = db.rawQuery(sql, null); return c; } public void updateUserDetails(String user_id, String name, String lastname, String phoneno, String emailid, String gender,int syncstatus) { String id1 = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.Entry.COLUMN_NAME_FIRST_NAME, name); contentValues.put(StudentContract.Entry.COLUMN_NAME_LAST_NAME, lastname); contentValues.put(StudentContract.Entry.COLUMN_NAME_MOBILE_NO, phoneno); contentValues.put(StudentContract.Entry.COLUMN_NAME_EMAIL_ID, emailid); contentValues.put(StudentContract.Entry.COLUMN_NAME_GENDER, gender); contentValues.put(StudentContract.Entry.COLUMN_NAME_SYNC_STATUS, syncstatus); db.update(StudentContract.Entry.TABLE_NAME, contentValues, StudentContract.Entry.COLUMN_NAME_ENTRY_ID + "=" + id1, null); db.close(); } public void updateUserActiveStatus(String user_id,int status) { String id1 = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.Entry.COLUMN_NAME_STATUS, status); contentValues.put(StudentContract.Entry.COLUMN_NAME_SYNC_STATUS, 2); db.update(StudentContract.Entry.TABLE_NAME, contentValues, StudentContract.Entry.COLUMN_NAME_ENTRY_ID + "=" + id1, null); db.close(); } public void updateUserNotes(String user_id, String cooments,int status) { String id1 = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.Entry.COLUMN_NAME_NOTES, cooments); contentValues.put(StudentContract.Entry.COLUMN_NAME_SYNC_STATUS, status); db.update(StudentContract.Entry.TABLE_NAME, contentValues, StudentContract.Entry.COLUMN_NAME_ENTRY_ID + "=" + id1, null); db.close(); } public void addNameSync(String user_id, String name, String lastname, String phoneno, String emailid, String gender,int syncstatus) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.Entry.COLUMN_NAME_ENTRY_ID, user_id); contentValues.put(StudentContract.Entry.COLUMN_NAME_FIRST_NAME, name); contentValues.put(StudentContract.Entry.COLUMN_NAME_LAST_NAME, lastname); contentValues.put(StudentContract.Entry.COLUMN_NAME_MOBILE_NO, phoneno); contentValues.put(StudentContract.Entry.COLUMN_NAME_EMAIL_ID, emailid); contentValues.put(StudentContract.Entry.COLUMN_NAME_GENDER, gender); contentValues.put(StudentContract.Entry.COLUMN_NAME_FCM_ID, "Admin"); contentValues.put(StudentContract.Entry.COLUMN_NAME_NOTES, ""); contentValues.put(StudentContract.Entry.COLUMN_NAME_SYNC_STATUS, syncstatus); contentValues.put(StudentContract.Entry.COLUMN_NAME_STATUS, 1); db.insert(StudentContract.Entry.TABLE_NAME, null, contentValues); db.close(); } public void deleteUser(String user_id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(StudentContract.Entry.TABLE_NAME, StudentContract.Entry.COLUMN_NAME_ENTRY_ID + "=? ", new String[]{user_id}); db.close(); } public void addUserLoc(String s_no, String id, String branch, String userid,int syncstatus) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.StudentLocation.COLUMN_NAME_S_ID, s_no); contentValues.put(StudentContract.StudentLocation.COLUMN_NAME_ENTRY_ID, Integer.parseInt(id)); contentValues.put(StudentContract.StudentLocation.COLUMN_NAME_BRANCH_NAME, branch); contentValues.put(StudentContract.StudentLocation.COLUMN_NAME_USER_ID, userid); contentValues.put(StudentContract.StudentLocation.COLUMN_NAME_SYNC_STATUS, syncstatus); db.insert(StudentContract.StudentLocation.TABLE_NAME, null, contentValues); db.close(); } public void addUserCourse(String s_no, String id, String cousername,String coursecode,String coursetypeid, String userid,int syncstatus) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_S_ID, s_no); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_ENTRY_ID, Integer.parseInt(id)); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_COURSE_NAME, cousername); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_COURSE_CODE, coursecode); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_TYPE_ID, coursetypeid); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_USER_ID, userid); contentValues.put(StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS, syncstatus); db.insert(StudentContract.StudentCourse.TABLE_NAME, null, contentValues); db.close(); } public void addUserDayPre(String s_no, String id,String userid,int syncstatus) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.UserDayPrefrence.COLUMN_NAME_ENTRY_ID, Integer.parseInt(s_no)); contentValues.put(StudentContract.UserDayPrefrence.COLUMN_NAME_USER_ID, Integer.parseInt(userid)); contentValues.put(StudentContract.UserDayPrefrence.COLUMN_NAME_DAYPREFRENCE_ID, Integer.parseInt(id)); contentValues.put(StudentContract.UserDayPrefrence.COLUMN_NAME_SYNC_STATUS, syncstatus); db.insert(StudentContract.UserDayPrefrence.TABLE_NAME, null, contentValues); db.close(); } public Cursor getComingBatches(String course_id) { SQLiteDatabase db = this.getReadableDatabase(); String sql = "select * from " + StudentContract.ComingBatchdetails.TABLE_NAME + " where " + StudentContract.ComingBatchdetails.COLUMN_NAME_COURSE_ID + " = '" + course_id + "'"; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getBranches(int user_id) { SQLiteDatabase db = this.getReadableDatabase(); //String sql = "select * from " + StudentContract.Branches.TABLE_NAME + " where " + StudentContract.Branches.COLUMN_NAME_ENTRY_ID + " = '" + user_id + "'"; String sql ="Select d.id as id, b.branch_name,b.address,b.latitude,b.longitude,b.branch_short,b.m_timestamp, d.isselected from (select id, \"selected\" as isselected from vwLocationsDemandedUserWise where user_id="+user_id+" union all select id, \"notselected\" from branches where id not in (select id from vwLocationsDemandedUserWise where user_id="+user_id+")) as d inner join branches as b on d.id=b.id"; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getCourses(int user_id,int course_type) { SQLiteDatabase db = this.getReadableDatabase(); String sql ="Select d.id as id,c.course_type_id,c.course_code, c.course_name,c.time_duration,c.prerequisite,c.recommonded,c.fees,c.syllabuspath,c.you_tube_link, d.isselected from (select id, \"selected\" as isselected from vwCourseDemandedUserWise where user_id="+user_id+" union all select id, \"notselected\" from courses where id not in (select id from vwCourseDemandedUserWise where user_id="+user_id+") and course_type_id ="+course_type+") as d inner join courses as c on d.id=c.id ORDER BY c.id ASC"; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getUserDayPre(int user_id) { SQLiteDatabase db = this.getReadableDatabase(); String sql ="Select du.dayprefrence_id as id, dp.Prefrence,dp.m_timestamp, du.isselected from (select dayprefrence_id, \"selected\" as isselected from user_dayprefrence where user_id="+user_id+" union all select id, \"notselected\" from DayPrefrence where id not in (select dayprefrence_id from user_dayprefrence where user_id="+user_id+")) as du inner join DayPrefrence as dp on du.dayprefrence_id=dp.id"; Cursor c = db.rawQuery(sql, null); return c; } //syncing data public Cursor getUnsyncedUsers() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.Entry.TABLE_NAME + " WHERE " + StudentContract.Entry.COLUMN_NAME_SYNC_STATUS + " = 0"; Cursor c = db.rawQuery(sql, null); return c; } public boolean updateUserIdStatus(String user_id,String id, int status) { String temp_id = "\"" + id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.Entry.COLUMN_NAME_SYNC_STATUS , status); contentValues.put(StudentContract.Entry.COLUMN_NAME_ENTRY_ID , user_id); db.update(StudentContract.Entry.TABLE_NAME, contentValues, StudentContract.Entry.COLUMN_NAME_ENTRY_ID + "=" + temp_id, null); ContentValues contentUserId = new ContentValues(); contentUserId.put(StudentContract.UserDayPrefrence.COLUMN_NAME_USER_ID , user_id); db.update(StudentContract.UserDayPrefrence.TABLE_NAME, contentUserId, StudentContract.UserDayPrefrence.COLUMN_NAME_USER_ID + "=" + temp_id, null); db.update(StudentContract.StudentLocation.TABLE_NAME, contentUserId, StudentContract.StudentLocation.COLUMN_NAME_USER_ID + "=" + temp_id, null); db.update(StudentContract.StudentCourse.TABLE_NAME, contentUserId, StudentContract.StudentCourse.COLUMN_NAME_USER_ID + "=" + temp_id, null); db.close(); return true; } public Cursor getUnsyncedUserDayPrefrence() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.UserDayPrefrence.TABLE_NAME + " WHERE " + StudentContract.UserDayPrefrence.COLUMN_NAME_SYNC_STATUS + " = 0"; Cursor c = db.rawQuery(sql, null); return c; } public boolean updateUserDayPre(String user_id,String id,String pre_id, int status) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentUserId = new ContentValues(); contentUserId.put(StudentContract.UserDayPrefrence.COLUMN_NAME_ENTRY_ID , id); contentUserId.put(StudentContract.UserDayPrefrence.COLUMN_NAME_SYNC_STATUS , status); db.update(StudentContract.UserDayPrefrence.TABLE_NAME, contentUserId, StudentContract.UserDayPrefrence.COLUMN_NAME_USER_ID + "=" + user_id+" and "+StudentContract.UserDayPrefrence.COLUMN_NAME_DAYPREFRENCE_ID + "=" + pre_id, null); db.close(); return true; } public Cursor getUnsyncedUserLoc() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.StudentLocation.TABLE_NAME + " WHERE " + StudentContract.StudentLocation.COLUMN_NAME_SYNC_STATUS + " = 0"; Cursor c = db.rawQuery(sql, null); return c; } public boolean updateUserLoc(String user_id,String bid,String id, int status) { String temp_id = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentUserId = new ContentValues(); contentUserId.put(StudentContract.StudentLocation.COLUMN_NAME_S_ID , bid); contentUserId.put(StudentContract.StudentLocation.COLUMN_NAME_SYNC_STATUS , status); db.update(StudentContract.StudentLocation.TABLE_NAME, contentUserId, StudentContract.StudentLocation.COLUMN_NAME_USER_ID + "=" + temp_id+" and "+StudentContract.StudentLocation.COLUMN_NAME_ENTRY_ID + "=" + id, null); db.close(); return true; } public Cursor getUnsyncedUserCourse() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.StudentCourse.TABLE_NAME + " WHERE " + StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS + " = 0"; Cursor c = db.rawQuery(sql, null); return c; } public boolean updateUserCourse(String user_id,String cid,String id, int status) { String temp_id = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentUserId = new ContentValues(); contentUserId.put(StudentContract.StudentCourse.COLUMN_NAME_S_ID , cid); contentUserId.put(StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS , status); db.update(StudentContract.StudentCourse.TABLE_NAME, contentUserId, StudentContract.StudentCourse.COLUMN_NAME_USER_ID + "=" + temp_id+" and "+StudentContract.StudentCourse.COLUMN_NAME_ENTRY_ID + "=" + id, null); db.close(); return true; } public boolean updateUserDeleteStatus(String user_id, int status) { String temp_id = "\"" + user_id + "\""; SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentContract.Entry.COLUMN_NAME_SYNC_STATUS , status); db.update(StudentContract.Entry.TABLE_NAME, contentValues, StudentContract.Entry.COLUMN_NAME_ENTRY_ID + "=" + temp_id, null); db.close(); return true; } public Cursor getUnsyncedUserDelete() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.Entry.TABLE_NAME + " WHERE " + StudentContract.Entry.COLUMN_NAME_SYNC_STATUS + " = 3"; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getUnsyncedUserDeleteLoc() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.StudentLocation.TABLE_NAME + " WHERE " + StudentContract.StudentLocation.COLUMN_NAME_SYNC_STATUS + " = 3"; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getUnsyncedUserDeleteCourse() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.StudentCourse.TABLE_NAME + " WHERE " + StudentContract.StudentCourse.COLUMN_NAME_SYNC_STATUS + " = 3"; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getUnsyncedUserDeleteDayPre() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.UserDayPrefrence.TABLE_NAME + " WHERE " + StudentContract.UserDayPrefrence.COLUMN_NAME_SYNC_STATUS + " = 3"; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getUserDetails(String user_id) { String temp_id = "\"" + user_id + "\""; SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.Entry.TABLE_NAME + " WHERE " + StudentContract.Entry.COLUMN_NAME_ENTRY_ID + " ="+temp_id; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getStudentComment(int user_id) { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.StudentComments.TABLE_NAME + " WHERE " + StudentContract.StudentComments.COLUMN_NAME_USER_ID + " ="+user_id; Cursor c = db.rawQuery(sql, null); return c; } public Cursor getUserDetailsUpdate() { SQLiteDatabase db = this.getReadableDatabase(); String sql = "SELECT * FROM " + StudentContract.Entry.TABLE_NAME + " WHERE " + StudentContract.Entry.COLUMN_NAME_SYNC_STATUS + " =2"; Cursor c = db.rawQuery(sql, null); return c; } } }
Java
CL
126345fdd03ea9f7f06d0f8d74d2a90d52fa35ae6a3014490dbd4c1334d82d66
package com.abings.baby.injection.component; import android.content.Context; import com.abings.baby.injection.ActivityContext; import com.abings.baby.injection.PerActivity; import com.abings.baby.injection.module.ActivityModule; import com.abings.baby.ui.aboutme.AboutMeActivity; import com.abings.baby.ui.aboutme.association.AssociationActivity; import com.abings.baby.ui.aboutme.teacher.AboutMeTeacherFragment; import com.abings.baby.ui.aboutme.user.AboutMeFragment; import com.abings.baby.ui.baby.BabyInfoActivity; import com.abings.baby.ui.contacts.ContactsActivity; import com.abings.baby.ui.contacts.ContactsFragment; import com.abings.baby.ui.contacts.detail.ContactDetailActivity; import com.abings.baby.ui.exercise.Exercise; import com.abings.baby.ui.exercise.createnew.ExerciseNew; import com.abings.baby.ui.exercise.exerciseDetail.ExerciseDetailActivity; import com.abings.baby.ui.feedback.FeedBackActivity; import com.abings.baby.ui.feedback.FeedBackFragment; import com.abings.baby.ui.finder.FinderActivity; import com.abings.baby.ui.finder.FinderFragment; import com.abings.baby.ui.home2.HomeFragment2; import com.abings.baby.ui.infolist.InfoListActivity; import com.abings.baby.ui.infolist.news.NewsActivity; import com.abings.baby.ui.login.LoginActivity; import com.abings.baby.ui.login.SplashActivity; import com.abings.baby.ui.main.MainActivity; import com.abings.baby.ui.message.center.MsgCenterActivity; import com.abings.baby.ui.message.center.MsgCenterListFragment; import com.abings.baby.ui.message.center.MsgCenterListFragment_copy; import com.abings.baby.ui.message.center.detail.MessageDetailActivity; import com.abings.baby.ui.message.send.SendMsgActivity; import com.abings.baby.ui.message.unread.UnreadActivity; import com.abings.baby.ui.publish.PublishActivity; import com.abings.baby.ui.publishvideo.PublishVideoActivity; import com.abings.baby.ui.publishvideo.VideoPlayActivity; import com.abings.baby.ui.register.RegisterActivity; import com.abings.baby.ui.setting.SettingFragment; import com.abings.baby.ui.setting.about.AboutActivity; import com.abings.baby.ui.setting.passwd.PasswdActivity; import com.abings.baby.ui.setting.question.QuestionActivity; import com.abings.baby.ui.setting.version.VersionActivity; import com.abings.baby.ui.signin.SignInActivity; import com.abings.baby.ui.signin.SingInFragment; import com.abings.baby.ui.signin.SingInHistoryActivity; import com.abings.baby.ui.upapp.UpAppDialogActivity; import com.abings.baby.ui.waterfall.WaterfallActivity; import com.abings.baby.ui.waterfall.photoviewpagedetail.PhotoViewpageDetailActivity; import com.abings.baby.ui.waterfall.photoviewpagedetail.fragment.PhotoDatailFragment; import dagger.Component; @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { void inject(SignInActivity signInActivity); void inject(SplashActivity splashActivity); void inject(PhotoDatailFragment photoDatailFragment); void inject(Exercise exercise); void inject(SingInFragment singInFragment); void inject(PhotoViewpageDetailActivity photoViewpageDetailActivity); void inject(ExerciseNew exerciseNew); void inject(ExerciseDetailActivity exerciseDetailActivity); void inject(MainActivity mainActivity); void inject(LoginActivity loginActivity); void inject(RegisterActivity registerActivity); void inject(FinderActivity finderActivity); void inject(QuestionActivity questionActivity); void inject(VersionActivity versionActivity); void inject(PasswdActivity passwdActivity); void inject(WaterfallActivity waterfallActivity); void inject(AboutMeActivity aboutMeActivity); void inject(InfoListActivity aboutMeActivity); void inject(PublishActivity aboutMeActivity); void inject(NewsActivity newsActivity); void inject(AboutActivity aboutActivity); void inject(ContactDetailActivity aboutActivity); void inject(SendMsgActivity aboutActivity); void inject(ContactsActivity aboutActivity); void inject(MessageDetailActivity aboutActivity); void inject(BabyInfoActivity aboutActivity); void inject(MsgCenterListFragment aboutActivity); void inject(MsgCenterListFragment_copy aboutActivity); void inject(HomeFragment2 contactsFragment); void inject(FinderFragment contactsFragment); void inject(ContactsFragment contactsFragment); void inject(FeedBackFragment feedBackFragment); void inject(SettingFragment settingFragment); void inject(UpAppDialogActivity upAppDialogActivity); void inject(VideoPlayActivity videoPlayActivity); void inject(FeedBackActivity feedBackActivity); void inject(PublishVideoActivity publishVideoActivity); void inject(AboutMeFragment aboutMeFragment); void inject(AssociationActivity associationActivity); void inject(AboutMeTeacherFragment aboutMeTeacherFragment); @ActivityContext Context context(); void inject(MsgCenterActivity msgCenterActivity); void inject(UnreadActivity unreadActivity); }
Java
CL
ab6c737fdbd214e68f424d8c8658a8bf217d369167656e27160ed1a52205998a
package pattern; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; @Slf4j public class Singleton { private Singleton() { } public static Singleton singleton; private static final ReentrantLock lock = new ReentrantLock(); public static Singleton getInstanceWithoutConcurrencyAvoid() { singleton = Optional.ofNullable(singleton).orElseGet(Singleton::new); return singleton; } public static Singleton getInstanceWithNestedReentrantLock() { singleton = Optional.ofNullable(singleton).orElseGet( () -> { lock.lock(); try { return Optional.ofNullable(singleton).orElseGet(Singleton::new); } finally { lock.unlock(); } } ); return singleton; } public static Singleton getInstanceWithConcurrencyNestedSyncrhronizedCheck() { // if (singleton == null) { // // synchronized (Singleton.class) { // if (singleton == null) // singleton = new Singleton(); // } // } singleton = Optional.ofNullable(singleton).orElseGet( () -> { synchronized (Singleton.class) { return Optional.ofNullable(singleton).orElseGet(Singleton::new); } }); return singleton; } public static synchronized Singleton getInstanceWithConcurrencyAvoidWholeSynchronized() { singleton = Optional.ofNullable(singleton).orElseGet(Singleton::new); // if (singleton == null) // singleton = new Singleton(); return singleton; } @Slf4j @Execution(ExecutionMode.CONCURRENT) public static class SingletonTest { private static final int POOL = 100; private static final int CURRENCY_COUNT = 100000; @BeforeEach public void beforeEachMethod() { Singleton.singleton = null; } @Test public void testWithoutConcurrencyAvoid() throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(POOL); AtomicReference<Set<String>> atomicSet = new AtomicReference<>(new HashSet<>()); long start = System.currentTimeMillis(); for (int i = 0; i < CURRENCY_COUNT; i++) { service.submit(() -> { Singleton singleton = Singleton.getInstanceWithoutConcurrencyAvoid(); Set<String> set = atomicSet.getAndUpdate(current -> { Set<String> newSet = new HashSet<>(current); newSet.add(singleton.toString()); return newSet; }); }); } service.shutdown(); service.awaitTermination(10, TimeUnit.SECONDS); long end = System.currentTimeMillis(); log.info("## ExecutionTime : {}, atomicSet : {}, {}", end - start, atomicSet.get().size(), atomicSet.get()); Assert.assertTrue(atomicSet.get().size() > 1); } @RepeatedTest(100) public void testWithConcurrencyNestedSynchronizedCheck() throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(POOL); AtomicReference<Set<String>> atomicSet = new AtomicReference<>(new HashSet<>()); long start = System.currentTimeMillis(); for (int i = 0; i < CURRENCY_COUNT; i++) { service.submit(() -> { Singleton singleton = Singleton.getInstanceWithConcurrencyNestedSyncrhronizedCheck(); atomicSet.getAndUpdate(current -> { Set<String> newSet = new HashSet<>(current); newSet.add(singleton.toString()); return newSet; }); }); } service.shutdown(); service.awaitTermination(10, TimeUnit.SECONDS); long end = System.currentTimeMillis(); log.info("## ExecutionTime : {}, atomicSet : {}, {}", end - start, atomicSet.get().size(), atomicSet.get()); Assert.assertEquals(1, atomicSet.get().size()); } @RepeatedTest(100) public void testWithConcurrencyAvoidWholeSynchronized() throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(POOL); AtomicReference<Set<String>> atomicSet = new AtomicReference<>(new HashSet<>()); long start = System.currentTimeMillis(); for (int i = 0; i < CURRENCY_COUNT; i++) { service.submit(() -> { Singleton singleton = Singleton.getInstanceWithConcurrencyAvoidWholeSynchronized(); atomicSet.getAndUpdate(current -> { Set<String> newSet = new HashSet<>(current); newSet.add(singleton.toString()); return newSet; }); }); } service.shutdown(); service.awaitTermination(1000, TimeUnit.MILLISECONDS); long end = System.currentTimeMillis(); log.info("## ExecutionTime : {}, atomicSet : {}, {}", end - start, atomicSet.get().size(), atomicSet.get()); Assert.assertEquals(1, atomicSet.get().size()); } @RepeatedTest(100) public void testWithConcurrencyNestedReentrantLock() throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(POOL); AtomicReference<Set<String>> atomicSet = new AtomicReference<>(new HashSet<>()); long start = System.currentTimeMillis(); for (int i = 0; i < CURRENCY_COUNT; i++) { service.submit(() -> { Singleton singleton = Singleton.getInstanceWithNestedReentrantLock(); atomicSet.getAndUpdate(current -> { Set<String> newSet = new HashSet<>(current); newSet.add(singleton.toString()); return newSet; }); }); } service.shutdown(); service.awaitTermination(1000, TimeUnit.MILLISECONDS); long end = System.currentTimeMillis(); log.info("## ExecutionTime : {}, atomicSet : {}, {}", end - start, atomicSet.get().size(), atomicSet.get()); Assert.assertEquals(1, atomicSet.get().size()); } } }
Java
CL
118c5e0228ded714c4e9f59c5b098df1d1b3a5060414248f65397c28c83cb93b
package org.alien4cloud.tosca.catalog.index; import static alien4cloud.dao.FilterUtil.fromKeyValueCouples; import static alien4cloud.dao.model.FetchContext.SUMMARY; import java.util.Map; import javax.inject.Inject; import alien4cloud.paas.wf.WorkflowsBuilderService; import alien4cloud.tosca.parser.ToscaParser; import org.alien4cloud.tosca.catalog.ArchiveDelegateType; import org.alien4cloud.tosca.model.Csar; import org.alien4cloud.tosca.model.templates.Topology; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import alien4cloud.dao.model.FacetedSearchResult; import alien4cloud.exception.NotFoundException; import alien4cloud.utils.AlienConstants; import alien4cloud.utils.NameValidationUtils; import alien4cloud.utils.VersionUtil; import lombok.extern.slf4j.Slf4j; /** * Service responsible for indexing and updating topologies. */ @Slf4j @Service public class TopologyCatalogService extends AbstractToscaIndexSearchService<Topology> implements ITopologyCatalogService { @Inject private ArchiveIndexer archiveIndexer; @Inject private WorkflowsBuilderService workflowBuilderService; @Override public Topology createTopologyAsTemplate(String name, String description, String version, String workspace, String fromTopologyId) { NameValidationUtils.validate("topologyTemplateName", name); // Every version of a topology template has a Cloud Service Archive Csar csar = new Csar(name, StringUtils.isNotBlank(version) ? version : VersionUtil.DEFAULT_VERSION_NAME); csar.setWorkspace(workspace); csar.setDelegateType(ArchiveDelegateType.CATALOG.toString()); csar.setToscaDefinitionsVersion(ToscaParser.LATEST_DSL); if (description == null) { csar.setDescription("This archive has been created with alien4cloud."); } else { csar.setDescription("Enclosing archive for topology " + description); } Topology topology; if (fromTopologyId != null) { // "cloning" the topology // TODO Currently, the fromTopologyId is always null. If this implementation needed, please think about initializing the workflow topology = alienDAO.findById(Topology.class, fromTopologyId); } else { topology = new Topology(); // Init the workflow if the topology is totally new workflowBuilderService.initWorkflows(workflowBuilderService.buildTopologyContext(topology, csar)); } topology.setDescription(description); topology.setArchiveName(csar.getName()); topology.setArchiveVersion(csar.getVersion()); topology.setWorkspace(csar.getWorkspace()); archiveIndexer.importNewArchive(csar, topology, null); return topology; } @Override protected Topology[] getArray(int size) { return new Topology[size]; } @Override protected String getAggregationField() { return "archiveName"; } // we need to override for aspect purpose @Override public FacetedSearchResult search(Class<? extends Topology> clazz, String query, Integer size, Map<String, String[]> filters) { return super.search(clazz, query, size, filters); } @Override public Topology[] getAll(Map<String, String[]> filters, String archiveName) { return alienDAO.buildQuery(Topology.class) .setFilters(fromKeyValueCouples(filters, "workspace", AlienConstants.GLOBAL_WORKSPACE_ID, "archiveName", archiveName)).prepareSearch() .setFetchContext(SUMMARY).search(0, 10000).getData(); } @Override public Topology getOrFail(String id) { Topology topology = get(id); if (topology == null) { throw new NotFoundException("Unable to find a topology with id <" + id + ">"); } return topology; } @Override public Topology get(String id) { return alienDAO.findById(Topology.class, id); } /** * Return true if the given id exists. * * @param id The id to check. * @return True if a topology with the given id exists, false if not. */ @Override public boolean exists(String id) { return alienDAO.exist(Topology.class, id); } }
Java
CL
d891fd0d9f7793adee2d5d3920960f849a0847f57eb92aeb41fc63428b1eb339
package com.kore.ai.widgetsdk.charts.charts; import android.content.Context; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import com.kore.ai.widgetsdk.charts.components.XAxis; import com.kore.ai.widgetsdk.charts.components.YAxis; import com.kore.ai.widgetsdk.charts.data.BarData; import com.kore.ai.widgetsdk.charts.data.BarEntry; import com.kore.ai.widgetsdk.charts.data.Entry; import com.kore.ai.widgetsdk.charts.highlight.Highlight; import com.kore.ai.widgetsdk.charts.highlight.HorizontalBarHighlighter; import com.kore.ai.widgetsdk.charts.interfaces.datasets.IBarDataSet; import com.kore.ai.widgetsdk.charts.renderer.HorizontalBarChartRenderer; import com.kore.ai.widgetsdk.charts.renderer.XAxisRendererHorizontalBarChart; import com.kore.ai.widgetsdk.charts.renderer.YAxisRendererHorizontalBarChart; import com.kore.ai.widgetsdk.charts.utils.HorizontalViewPortHandler; import com.kore.ai.widgetsdk.charts.utils.MPPointF; import com.kore.ai.widgetsdk.charts.utils.TransformerHorizontalBarChart; import com.kore.ai.widgetsdk.charts.utils.Utils; public class HorizontalBarChart extends BarChart { private final RectF mOffsetsBuffer = new RectF(); protected float[] mGetPositionBuffer = new float[2]; public HorizontalBarChart(Context context) { super(context); } public HorizontalBarChart(Context context, AttributeSet attrs) { super(context, attrs); } public HorizontalBarChart(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } protected void init() { this.mViewPortHandler = new HorizontalViewPortHandler(); super.init(); this.mLeftAxisTransformer = new TransformerHorizontalBarChart(this.mViewPortHandler); this.mRightAxisTransformer = new TransformerHorizontalBarChart(this.mViewPortHandler); this.mRenderer = new HorizontalBarChartRenderer(this, this.mAnimator, this.mViewPortHandler); this.setHighlighter(new HorizontalBarHighlighter(this)); this.mAxisRendererLeft = new YAxisRendererHorizontalBarChart(this.mViewPortHandler, this.mAxisLeft, this.mLeftAxisTransformer); this.mAxisRendererRight = new YAxisRendererHorizontalBarChart(this.mViewPortHandler, this.mAxisRight, this.mRightAxisTransformer); this.mXAxisRenderer = new XAxisRendererHorizontalBarChart(this.mViewPortHandler, this.mXAxis, this.mLeftAxisTransformer, this); } public void calculateOffsets() { float offsetLeft = 0.0F; float offsetRight = 0.0F; float offsetTop = 0.0F; float offsetBottom = 0.0F; this.calculateLegendOffsets(this.mOffsetsBuffer); offsetLeft += this.mOffsetsBuffer.left; offsetTop += this.mOffsetsBuffer.top; offsetRight += this.mOffsetsBuffer.right; offsetBottom += this.mOffsetsBuffer.bottom; if (this.mAxisLeft.needsOffset()) { offsetTop += this.mAxisLeft.getRequiredHeightSpace(this.mAxisRendererLeft.getPaintAxisLabels()); } if (this.mAxisRight.needsOffset()) { offsetBottom += this.mAxisRight.getRequiredHeightSpace(this.mAxisRendererRight.getPaintAxisLabels()); } float xlabelwidth = (float)this.mXAxis.mLabelRotatedWidth; if (this.mXAxis.isEnabled()) { if (this.mXAxis.getPosition() == XAxis.XAxisPosition.BOTTOM) { offsetLeft += xlabelwidth; } else if (this.mXAxis.getPosition() == XAxis.XAxisPosition.TOP) { offsetRight += xlabelwidth; } else if (this.mXAxis.getPosition() == XAxis.XAxisPosition.BOTH_SIDED) { offsetLeft += xlabelwidth; offsetRight += xlabelwidth; } } offsetTop += this.getExtraTopOffset(); offsetRight += this.getExtraRightOffset(); offsetBottom += this.getExtraBottomOffset(); offsetLeft += this.getExtraLeftOffset(); float minOffset = Utils.convertDpToPixel(this.mMinOffset); this.mViewPortHandler.restrainViewPort(Math.max(minOffset, offsetLeft), Math.max(minOffset, offsetTop), Math.max(minOffset, offsetRight), Math.max(minOffset, offsetBottom)); if (this.mLogEnabled) { Log.i("MPAndroidChart", "offsetLeft: " + offsetLeft + ", offsetTop: " + offsetTop + ", offsetRight: " + offsetRight + ", offsetBottom: " + offsetBottom); Log.i("MPAndroidChart", "Content: " + this.mViewPortHandler.getContentRect().toString()); } this.prepareOffsetMatrix(); this.prepareValuePxMatrix(); } protected void prepareValuePxMatrix() { this.mRightAxisTransformer.prepareMatrixValuePx(this.mAxisRight.mAxisMinimum, this.mAxisRight.mAxisRange, this.mXAxis.mAxisRange, this.mXAxis.mAxisMinimum); this.mLeftAxisTransformer.prepareMatrixValuePx(this.mAxisLeft.mAxisMinimum, this.mAxisLeft.mAxisRange, this.mXAxis.mAxisRange, this.mXAxis.mAxisMinimum); } protected float[] getMarkerPosition(Highlight high) { return new float[]{high.getDrawY(), high.getDrawX()}; } public void getBarBounds(BarEntry e, RectF outputRect) { IBarDataSet set = (IBarDataSet)((BarData)this.mData).getDataSetForEntry(e); if (set == null) { outputRect.set(1.4E-45F, 1.4E-45F, 1.4E-45F, 1.4E-45F); } else { float y = e.getY(); float x = e.getX(); float barWidth = ((BarData)this.mData).getBarWidth(); float top = x - barWidth / 2.0F; float bottom = x + barWidth / 2.0F; float left = y >= 0.0F ? y : 0.0F; float right = y <= 0.0F ? y : 0.0F; outputRect.set(left, top, right, bottom); this.getTransformer(set.getAxisDependency()).rectValueToPixel(outputRect); } } public MPPointF getPosition(Entry e, YAxis.AxisDependency axis) { if (e == null) { return null; } else { float[] vals = this.mGetPositionBuffer; vals[0] = e.getY(); vals[1] = e.getX(); this.getTransformer(axis).pointValuesToPixel(vals); return MPPointF.getInstance(vals[0], vals[1]); } } public Highlight getHighlightByTouchPoint(float x, float y) { if (this.mData == null) { if (this.mLogEnabled) { Log.e("MPAndroidChart", "Can't select by touch. No data set."); } return null; } else { return this.getHighlighter().getHighlight(y, x); } } public float getLowestVisibleX() { this.getTransformer(YAxis.AxisDependency.LEFT).getValuesByTouchPoint(this.mViewPortHandler.contentLeft(), this.mViewPortHandler.contentBottom(), this.posForGetLowestVisibleX); float result = (float)Math.max((double)this.mXAxis.mAxisMinimum, this.posForGetLowestVisibleX.y); return result; } public float getHighestVisibleX() { this.getTransformer(YAxis.AxisDependency.LEFT).getValuesByTouchPoint(this.mViewPortHandler.contentLeft(), this.mViewPortHandler.contentTop(), this.posForGetHighestVisibleX); float result = (float)Math.min((double)this.mXAxis.mAxisMaximum, this.posForGetHighestVisibleX.y); return result; } public void setVisibleXRangeMaximum(float maxXRange) { float xScale = this.mXAxis.mAxisRange / maxXRange; this.mViewPortHandler.setMinimumScaleY(xScale); } public void setVisibleXRangeMinimum(float minXRange) { float xScale = this.mXAxis.mAxisRange / minXRange; this.mViewPortHandler.setMaximumScaleY(xScale); } public void setVisibleXRange(float minXRange, float maxXRange) { float minScale = this.mXAxis.mAxisRange / minXRange; float maxScale = this.mXAxis.mAxisRange / maxXRange; this.mViewPortHandler.setMinMaxScaleY(minScale, maxScale); } public void setVisibleYRangeMaximum(float maxYRange, YAxis.AxisDependency axis) { float yScale = this.getAxisRange(axis) / maxYRange; this.mViewPortHandler.setMinimumScaleX(yScale); } public void setVisibleYRangeMinimum(float minYRange, YAxis.AxisDependency axis) { float yScale = this.getAxisRange(axis) / minYRange; this.mViewPortHandler.setMaximumScaleX(yScale); } public void setVisibleYRange(float minYRange, float maxYRange, YAxis.AxisDependency axis) { float minScale = this.getAxisRange(axis) / minYRange; float maxScale = this.getAxisRange(axis) / maxYRange; this.mViewPortHandler.setMinMaxScaleX(minScale, maxScale); } }
Java
CL
66556cc7476dded5a7f3200b58b4a5e2b889dda112f04fe7e151d978b4814dfa
package com.nmimo.common.configuration.exception; import com.nmimo.common.ServiceConstants; import com.nmimo.common.exception.NMimoAbstractException; @SuppressWarnings("serial") public class ConfigFileNotFoundException extends NMimoAbstractException { /** * * <pre> * 상위 클래스에 예외메세지를 전달한다. * </pre> * @param element message.properties 파일에 있는 예외메세지에 변수로 들어갈 문자열 */ public ConfigFileNotFoundException(String errorMessageParameter) { super(errorMessageParameter); } /** * Configuration 예외 발생시 message 파일에서 예외메세지를 가져오기 위한 키값 을 정의 */ public String getErrorCode() { return ServiceConstants.ConfigFileNotFound; } }
Java
CL
5e50ce3e8688bfe5ca86471cfc1020fbd46e18486f005fd0a03ea348f1f46aec
import android.os.Parcelable.Creator; import com.google.android.gms.common.stats.WakeLockEvent; public final class dis implements Parcelable.Creator<WakeLockEvent> { public dis() {} }
Java
CL
cc752c40c8231178a73105fae09e2a56c9f15547cb4e2922e2232d51a1d95e05
package com.cognizant.adminapi.controller; import com.cognizant.adminapi.exception.NotFoundException; import com.cognizant.adminapi.model.InvoiceViewModel; import com.cognizant.adminapi.service.ServiceLayer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RefreshScope @RequestMapping(value = "/invoices") public class InvoiceClientController { @Autowired ServiceLayer sl; @GetMapping(value = "/{invoiceId}") @ResponseStatus(HttpStatus.OK) public InvoiceViewModel getInvoice(@PathVariable(name="invoiceId") Integer invoiceId) { InvoiceViewModel ivm = sl.getInvoice(invoiceId); if (ivm == null) throw new NotFoundException("Invoice with ID " + invoiceId + " does not exist."); return ivm; } @GetMapping @ResponseStatus(HttpStatus.OK) public List<InvoiceViewModel> getAllInvoices() { List<InvoiceViewModel> invoiceList = sl.getAllInvoices(); if (invoiceList != null && invoiceList.size() == 0) { throw new NotFoundException("There are no invoices available."); } return invoiceList; } @GetMapping(value = "/customer/{customerId}") @ResponseStatus(HttpStatus.OK) public List<InvoiceViewModel> getAllInvoicesByCustomerId(@PathVariable(name="customerId") Integer customerId) { List<InvoiceViewModel> invoiceList = sl.getAllInvoicesByCustomerId(customerId); if (invoiceList != null && invoiceList.size() == 0) { throw new NotFoundException("There are no invoices with the customer ID " + customerId); } return invoiceList; } }
Java
CL
7c4daa60838f8d97eda68b0458521f8b032b29d83439f2a3881ec5b0aa77e968
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.09.07 at 08:01:35 PM IST // package com.mozu.qbintegration.model.qbmodel.allgen; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}TxnCoreMod"/> * &lt;element ref="{}TxnDate" minOccurs="0"/> * &lt;element ref="{}BankAccountRef" minOccurs="0"/> * &lt;choice minOccurs="0"> * &lt;element ref="{}IsToBePrinted"/> * &lt;element ref="{}RefNumber"/> * &lt;/choice> * &lt;element name="Memo" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{}STRTYPE"> * &lt;maxLength value="4095"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element ref="{}Address" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "txnID", "editSequence", "txnDate", "bankAccountRef", "isToBePrinted", "refNumber", "memo", "address" }) @XmlRootElement(name = "SalesTaxPaymentCheckMod") public class SalesTaxPaymentCheckMod { @XmlElement(name = "TxnID", required = true) protected String txnID; @XmlElement(name = "EditSequence", required = true) protected String editSequence; @XmlElement(name = "TxnDate") protected String txnDate; @XmlElement(name = "BankAccountRef") protected BankAccountRef bankAccountRef; @XmlElement(name = "IsToBePrinted") protected String isToBePrinted; @XmlElement(name = "RefNumber") protected String refNumber; @XmlElement(name = "Memo") protected String memo; @XmlElement(name = "Address") protected Address address; /** * Gets the value of the txnID property. * * @return * possible object is * {@link String } * */ public String getTxnID() { return txnID; } /** * Sets the value of the txnID property. * * @param value * allowed object is * {@link String } * */ public void setTxnID(String value) { this.txnID = value; } /** * Gets the value of the editSequence property. * * @return * possible object is * {@link String } * */ public String getEditSequence() { return editSequence; } /** * Sets the value of the editSequence property. * * @param value * allowed object is * {@link String } * */ public void setEditSequence(String value) { this.editSequence = value; } /** * Gets the value of the txnDate property. * * @return * possible object is * {@link String } * */ public String getTxnDate() { return txnDate; } /** * Sets the value of the txnDate property. * * @param value * allowed object is * {@link String } * */ public void setTxnDate(String value) { this.txnDate = value; } /** * Gets the value of the bankAccountRef property. * * @return * possible object is * {@link BankAccountRef } * */ public BankAccountRef getBankAccountRef() { return bankAccountRef; } /** * Sets the value of the bankAccountRef property. * * @param value * allowed object is * {@link BankAccountRef } * */ public void setBankAccountRef(BankAccountRef value) { this.bankAccountRef = value; } /** * Gets the value of the isToBePrinted property. * * @return * possible object is * {@link String } * */ public String getIsToBePrinted() { return isToBePrinted; } /** * Sets the value of the isToBePrinted property. * * @param value * allowed object is * {@link String } * */ public void setIsToBePrinted(String value) { this.isToBePrinted = value; } /** * Gets the value of the refNumber property. * * @return * possible object is * {@link String } * */ public String getRefNumber() { return refNumber; } /** * Sets the value of the refNumber property. * * @param value * allowed object is * {@link String } * */ public void setRefNumber(String value) { this.refNumber = value; } /** * Gets the value of the memo property. * * @return * possible object is * {@link String } * */ public String getMemo() { return memo; } /** * Sets the value of the memo property. * * @param value * allowed object is * {@link String } * */ public void setMemo(String value) { this.memo = value; } /** * Gets the value of the address property. * * @return * possible object is * {@link Address } * */ public Address getAddress() { return address; } /** * Sets the value of the address property. * * @param value * allowed object is * {@link Address } * */ public void setAddress(Address value) { this.address = value; } }
Java
CL
38031a5d13d87298419efe92d82bffe2193a396bfe9ea4989ff0e975d4391a5d
/* * ************************************************************ * 文件:HttpCacheDatabase.java 模块:http-core 项目:component * 当前修改时间:2019年05月22日 11:01:02 * 上次修改时间:2019年04月26日 22:46:37 * 作者:Cody.yi https://github.com/codyer * * 描述:http-core * Copyright (c) 2019 * ************************************************************ */ package com.cody.component.http.db; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import com.cody.component.http.db.data.ItemCacheData; import com.cody.component.lib.exception.NotInitializedException; /** * Created by xu.yi. on 2019/5/22. * HttpCacheDao */ @Database(entities = {ItemCacheData.class}, version = 1, exportSchema = false) @TypeConverters({Converters.class}) public abstract class HttpCacheDatabase extends RoomDatabase { private static final String DB_NAME = "HttpCacheDao.db"; private static volatile HttpCacheDatabase instance; public static HttpCacheDatabase getInstance() { if (instance == null) { throw new NotInitializedException("HttpCacheDatabase"); } return instance; } public static void init(Context context) { if (instance == null) { synchronized (HttpCacheDatabase.class) { if (instance == null) { instance = create(context); } } } } private static HttpCacheDatabase create(final Context context) { return Room.databaseBuilder(context, HttpCacheDatabase.class, DB_NAME).build(); } public abstract HttpCacheDao getCacheDao(); }
Java
CL
08875690c5d74ff3246308922609048bd8e0dc37f416c3a36c855b984bee91c4
/* * @(#)InterpreterTest.java * CubeTwister. Copyright © 2020 Werner Randelshofer, Switzerland. MIT License. */ package ch.randelshofer.rubik.parser; import ch.randelshofer.io.ParseException; import ch.randelshofer.rubik.cube.Cube; import ch.randelshofer.rubik.cube.Cubes; import ch.randelshofer.rubik.cube.RubiksCube; import ch.randelshofer.rubik.notation.DefaultNotation; import ch.randelshofer.rubik.notation.Move; import ch.randelshofer.rubik.notation.Notation; import org.jhotdraw.annotation.Nonnull; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.DynamicTest.dynamicTest; public class InterpreterTest { @Nonnull @TestFactory public List<DynamicTest> testMoves() { Notation defaultNotation = new DefaultNotation(); return Arrays.asList( dynamicTest("R", () -> doTestMove(defaultNotation, "R", buildRubik(Move.R))), dynamicTest("RI", () -> doTestMove(defaultNotation, "R'", buildRubik(Move.RI))), dynamicTest("R2", () -> doTestMove(defaultNotation, "R2", buildRubik(Move.R, Move.R))), dynamicTest("R U R' U'", () -> doTestMove(defaultNotation, "R U R' U'", buildRubik(Move.R, Move.U, Move.RI, Move.UI))), dynamicTest("[R,U]", () -> doTestMove(defaultNotation, "[R,U]", buildRubik(Move.R, Move.U, Move.RI, Move.UI))), dynamicTest("R U R'", () -> doTestMove(defaultNotation, "R U R'", buildRubik(Move.R, Move.U, Move.RI))), dynamicTest("<R>U", () -> doTestMove(defaultNotation, "<R>U", buildRubik(Move.R, Move.U, Move.RI))), dynamicTest("<R>'U", () -> doTestMove(defaultNotation, "<R>'U", buildRubik(Move.RI, Move.U, Move.R))) ); } @Nonnull private Cube buildRubik(@Nonnull Move... moves) { final RubiksCube cube = new RubiksCube(); for (Move m : moves) { cube.transform(m.getAxis(), m.getLayerMask(), m.getAngle()); } return cube; } private void doTestMove(@Nonnull Notation notation, String script, @Nonnull Cube expected) throws ParseException { ScriptParser instance = new ScriptParser(notation); final Node parsed = instance.parse(script); final RubiksCube actual = new RubiksCube(); parsed.applyTo(actual, false); System.err.println("expected: " + Cubes.toPermutationString(expected, notation)); System.err.println("actual: " + Cubes.toPermutationString(actual, notation)); assertEquals(expected, actual); } }
Java
CL
78b9883c8e6ab59ec67fa226c3b818af81d384e06bfe3a25186aa5ad52b1175b
package test.systemcatalog.components; import datastructures.relation.table.Table; import datastructures.rulegraph.types.RuleGraphTypes; import datastructures.user.User; import enums.InputType; import files.io.FileType; import files.io.IO; import files.io.Serializer; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import systemcatalog.components.Parser; import systemcatalog.components.Verifier; import utilities.Utilities; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test class for ensuring that the System Catalog's Verifier is operating as it should be. * This will focus on performing integrity checks with respect to what's available on the system. */ public class VerifierTest { private static Verifier verifier; private static List<Table> tables; private static List<User> users; @BeforeAll static void init() { verifier = new Verifier(); tables = Serializer.unSerializeTables(IO.readOriginalData(FileType.OriginalData.ORIGINAL_TABLES), false); users = Serializer.unSerializeUsers(IO.readOriginalData(FileType.OriginalData.ORIGINAL_USERS)); /*System.out.println("Tables ----------------------------------------------------------------------------------"); tables.forEach(System.out::println); System.out.println("Users -----------------------------------------------------------------------------------"); users.forEach(System.out::println);*/ } @ParameterizedTest @ValueSource(strings = { "SELECT CustomerID FROM Customers", // simple "SELECT * FROM Customers", "SELECT CustomerID, ProductID FROM Customers, Products", "SELECT Customers.CustomerID FROM Customers, CustomerPurchaseDetails WHERE Customers.CustomerID = CustomerPurchaseDetails.CustomerID", // join in where clause "SELECT Customers.CustomerID FROM Customers, CustomerPurchaseDetails WHERE Customers.CustomerID = CustomerPurchaseDetails.CustomerID and FirstName = \"Billy\"", "SELECT FirstName FROM Customers INNER JOIN CustomerPurchaseDetails ON Customers.CustomerID = CustomerPurchaseDetails.CustomerID", // prefixed join "SELECT Employees.FirstName FROM Customers INNER JOIN Employees ON CustomerID = EmployeeID", "SELECT Customers.CustomerID FROM Customers, CustomerPurchaseDetails", // prefixed columns in an ambiguous situation "SELECT CustomerPurchaseDetails.CustomerID FROM Customers, CustomerPurchaseDetails", "SELECT CustomerID FROM Customers WHERE FirstName = \"Blah\"", // where clause stuff "SELECT ProductName FROM Products WHERE Price > 1.20", "SELECT * FROM CustomerPurchaseDetails WHERE DatePurchased < \"2019-10-20\"", "SELECT State, COUNT(State) FROM Stores GROUP BY State", // group by stuff "SELECT State, COUNT(State) FROM Stores GROUP BY State HAVING COUNT(State) > 1", // having clause stuff "SELECT PaymentMethod, COUNT(PaymentMethod), AVG(Quantity) FROM CustomerPurchaseDetails GROUP BY PaymentMethod HAVING AVG(Quantity) > 1", }) void testValidQuery(String query) { System.out.println(query); String[] filtered = Utilities.filterInput(query); boolean isValid = verifier.isValid(InputType.QUERY, filtered, tables, users); System.out.println("Error Code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "SELECT CustomerID FROM Blah", // Blah table does not exist in system "SELECT CustomerID FROM Customers, Blah", "SELECT Blah FROM Customers", // column Blah does not exist within table (the table exists though) in select clause "SELECT CustomerID, FirstName, LastName, Blah FROM Customers", "SELECT CustomerID FROM Customers WHERE Blah = \"Blah\"", // in where clause "SELECT CustomerID FROM Customers WHERE CustomerID = 1 AND Blah = \"Blah\"", "SELECT CustomerID FROM Customers GROUP BY Blah", // in group by clause "SELECT CustomerID FROM Customers GROUP BY CustomerID HAVING COUNT(Blah) > 1", // in having clause "SELECT Customers.Blah FROM Customers", // prefixing a table that exists with a column that doesn't exist "SELECT CustomerID, Customers.Blah FROM Customers", "SELECT Blah.CustomerID FROM Customers", // column that exists but prefixed with a table that doesn't exist "SELECT CustomerID FROM Customers, CustomerPurchaseDetails", // ambiguous columns (columns that exist in multiple tables that are not prefixed) "SELECT CustomerID FROM Customers INNER JOIN CustomerPurchaseDetails ON Customers.CustomerID = CustomerPurchaseDetails.Blah", // column does not exist in join criteria (1st and 2nd table) "SELECT CustomerID FROM Customers INNER JOIN CustomerPurchaseDetails ON Customers.Blah = CustomerPurchaseDetails.CustomerID", "SELECT SUM(FirstName) FROM Customers", // only accept numeric values for aggregations, excluding count() in select/having clauses "SELECT COUNT(CustomerID), SUM(FirstName) FROM Customers", "SELECT COUNT(CustomerID) FROM Customers GROUP BY FirstName HAVING AVG(FirstName) > 1", "SELECT Customers.CustomerID FROM Customers INNER JOIN CustomerPurchaseDetails ON Customers.FirstName = CustomerPurchaseDetails.CustomerID", // make sure data types of columns match in join criteria "SELECT Customers.CustomerID FROM Customers INNER JOIN CustomerPurchaseDetails ON CustomerPurchaseDetails.PaymentMethod = Customers.CustomerID", "SELECT Customers.CustomerID FROM Customers INNER JOIN CustomerPurchaseDetails ON Customers.FirstName > CustomerPurchaseDetails.PaymentMethod", // if data types match, make sure that if >, <, >=, <= is used, that the values are numeric or dates "SELECT CustomerID FROM Customers WHERE CustomerID = \"Blah\"", // make sure data types of columns match in where clause "SELECT CustomerID FROM Customers WHERE FirstName = 1", "SELECT CustomerID FROM Customers WHERE CustomerID = \"2020-10-20\"", "SELECT COUNT(CustomerID) FROM Customers GROUP BY CustomerID HAVING SUM(FirstName) > 1", // make sure data types of columns match in having clause "SELECT CustomerID FROM CustomerPurchaseDetails WHERE DatePurchased = \"2020-99-20\"", // invalid dates for where and having clause "SELECT PaymentMethod, COUNT(PaymentMethod) FROM CustomerPurchaseDetails GROUP BY PaymentMethod HAVING AVG(DatePurchased) > \"Blah\"", "SELECT * FROM Customers GROUP BY CustomerID", // not allowed as there are no aggregate functions being used "SELECT PaymentMethod, COUNT(PaymentMethod) FROM CustomerPurchaseDetails GROUP BY PaymentMethod HAVING AVG(DatePurchased) > \"2020-10-17\"" // missing AVG(DatePurchased) in select clause }) void testInvalidQuery(String query) { System.out.println(query); String[] filtered = Utilities.filterInput(query); boolean isValid = verifier.isValid(InputType.QUERY, filtered, tables, users); System.out.println("Error Code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "CREATE TABLE Blah1(Col1 NUMBER(2, 1), Col2 CHAR(3), Col3 DATE, Col4 CHAR(10))" }) void validCreateTable(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.CREATE_TABLE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "CREATE TABLE 1(Col1 DATE)", // numeric table name "CREATE TABLE Blah(Col1 DATE, 2 CHAR(1), Col3 NUMBER(5))", // numeric column name "CREATE TABLE Customers(Col1 DATE)", // table already exists in system "CREATE TABLE Blah(Col1 CHAR(10.2))", // decimal size for size "CREATE TABLE Blah(Col1 NUMBER(10, 1.2))", // decimal size for decimal size "CREATE TABLE Blah(Col1 CHAR(10, 2))", // having a decimal size for char data type "CREATE TABLE Blah(Col1 CHAR(5), Col2 CHAR(10, 2))", "CREATE TABLE Blah(Col1 CHAR(-1))", // negative size "CREATE TABLE Blah(Col1 NUMBER(10, -1))", // negative decimal size "CREATE TABLE Blah(Col1 DATE, Col1 CHAR(3))" // duplicate columns }) void invalidCreateTable(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.CREATE_TABLE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "DROP TABLE Customers" // exists }) void validDropTable(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.DROP_TABLE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "DROP TABLE Blah" // table does not exist }) void invalidDropTable(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.DROP_TABLE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "ALTER TABLE Customers MODIFY CustomerID NUMBER(100)", // valid number change "ALTER TABLE Customers MODIFY CustomerID CHAR(5)", // valid number change "ALTER TABLE Customers ADD Blah NUMBER(5)", "ALTER TABLE Customers ADD FOREIGN KEY EmployeePurchaseDetails.EmployeeID", "ALTER TABLE Customers ADD PRIMARY KEY FirstName", }) void validAlterTable(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.ALTER_TABLE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "ALTER TABLE Blah ADD Col1 DATE", // table Blah does not exist "ALTER TABLE Customers MODIFY Blah NUMBER(2)", // column blah does not exist "ALTER TABLE Customers MODIFY Blah CHAR(2)", "ALTER TABLE Customers MODIFY Blah DATE", "ALTER TABLE Customers DROP FOREIGN KEY Blah.BlahID", // foreign key does not exist "ALTER TABLE Customers ADD FOREIGN KEY Employees.BlahID", "ALTER TABLE Customers DROP PRIMARY KEY Blah", // primary key does not exist "ALTER TABLE Customers ADD PRIMARY KEY Blah", "ALTER TABLE Customers ADD Col1 NUMBER(-1)", // negative size "ALTER TABLE Customers ADD Col1 NUMBER(1.1)", // decimal size "ALTER TABLE Customers ADD Col1 NUMBER(0)", // 0 size "ALTER TABLE Customers MODIFY CustomerID DATE", // invalid conversion "ALTER TABLE Customers MODIFY FirstName DATE", "ALTER TABLE Customers MODIFY FirstName NUMBER(20)" }) void invalidAlterTable(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.ALTER_TABLE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "INSERT INTO CustomerPurchaseDetails VALUES(1, 2, 3, \"Blah\", \"2020-10-10\")", "INSERT INTO CustomerPurchaseDetails VALUES(1)" // rest of the values will be null }) void validInsertCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.INSERT, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "INSERT INTO CustomerPurchaseDetails VALUES(\"Blah\", 2, 3, \"Blah\", \"2020-10-10\")", // mismatch data types "INSERT INTO CustomerPurchaseDetails VALUES(\"2020-10-10\", 2, 3, \"Blah\", \"2020-10-10\")", "INSERT INTO CustomerPurchaseDetails VALUES(1, 2, 3, \"Blah\", 1)", "INSERT INTO CustomerPurchaseDetails VALUES(1, 2, 3, 4, \"2020-10-10\")", "INSERT INTO CustomerPurchaseDetails VALUES(1, 2, 3, \"Blah\", \"2020-10-10\", 4)", // too many values }) void invalidInsertCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.INSERT, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "DELETE FROM Customers WHERE CustomerID = 1" }) void validDeleteCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.DELETE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "DELETE FROM Blah WHERE CustomerID = 1", // table does not exist "DELETE FROM Customers WHERE Blah = 1", // column does not exist "DELETE FROM Customers WHERE CustomerID = \"Blah\"", // mismatch data type "DELETE FROM Customers WHERE FirstName = 1", "DELETE FROM Customers WHERE FirstName = \"2020-10-10\"" }) void invalidDeleteCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.DELETE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "UPDATE Customers SET CustomerID = -1 WHERE CustomerID = 1", "UPDATE Customers SET FirstName = \"Blah\" WHERE CustomerID = 1" }) void validUpdateCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.UPDATE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); System.out.println(RuleGraphTypes.getUpdateRuleGraph()); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "UPDATE Blah SET Col1 = 1 WHERE Col1 = 1", // table does not exist "UPDATE Customers SET Blah = 1 WHERE Col1 = 1", // column does not exist "UPDATE Customers SET CustomerID = -1 WHERE Blah = \"Blah\"", "UPDATE Customers SET CustomerID = \"Blah\" WHERE FirstName = \"Blah\"", // mismatch data type "UPDATE Customers SET CustomerID = 1 WHERE FirstName = 1", // mismatch data type }) void invalidUpdateCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.UPDATE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "GRANT ALTER ON Customers TO Bob", // normal "GRANT ALTER, DELETE, INDEX ON Customers TO Bob", // multiple columns "GRANT UPDATE(CustomerID, FirstName, LastName) ON Customers TO Bob", // update, references "GRANT ALL PRIVILEGES ON Customers TO Bob", // all "GRANT ALTER ON Customers TO Bob, Sally, John", // multiple users "GRANT ALTER ON Customers TO Bob WITH GRANT OPTION", // grant option "GRANT ALTER, DELETE, INDEX, UPDATE(CustomerID, FirstName, LastName) ON Customers TO Bob, Sally, John" // mix of stuff }) void validGrantCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.GRANT, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "GRANT ALTER ON Blah TO Bob", // table doesn't exist "GRANT ALTER ON Customers TO Blah", // user doesn't exist "GRANT ALTER ON Customers TO Bob, Sally, Blah", // multiple "GRANT UPDATE(Blah) ON Customers TO Bob", // update, referenced columns don't exist in table "GRANT UPDATE(CustomerID, FirstName, LastName, Blah) ON Customers TO Bob", "GRANT REFERENCES(Blah) ON Customers TO Bob", "GRANT REFERENCES(CustomerID, FirstName, LastName, Blah) ON Customers TO Bob", }) void invalidGrantCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.GRANT, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "REVOKE ALTER ON Customers FROM Bob", // normal "REVOKE ALTER, DELETE, INDEX ON Customers FROM Bob", // multiple columns "REVOKE UPDATE(CustomerID, FirstName, LastName) ON Customers FROM Bob", // update, references "REVOKE ALL PRIVILEGES ON Customers FROM Bob", // all "REVOKE ALTER ON Customers FROM Bob, Sally, John", // multiple users "REVOKE ALTER, DELETE, INDEX, UPDATE(CustomerID, FirstName, LastName) ON Customers FROM Bob, Sally, John" // mix of stuff }) void validRevokeCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.REVOKE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "REVOKE ALTER ON Blah FROM Bob", // table doesn't exist "REVOKE ALTER ON Customers FROM Blah", // user doesn't exist "REVOKE ALTER ON Customers FROM Bob, Sally, Blah", // multiple "REVOKE UPDATE(Blah) ON Customers FROM Bob", // update, referenced columns don't exist in table "REVOKE UPDATE(CustomerID, FirstName, LastName, Blah) ON Customers FROM Bob", "REVOKE REFERENCES(Blah) ON Customers FROM Bob", "REVOKE REFERENCES(CustomerID, FirstName, LastName, Blah) ON Customers FROM Bob", }) void invalidRevokeCommand(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.REVOKE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "BUILD HASH TABLE ON CustomerID IN Customers", // normal "BUILD CLUSTERED FILE ON Customers AND CustomerPurchaseDetails" // clustered files }) void validBuildFileStructure(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.BUILD_FILE_STRUCTURE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "BUILD HASH TABLE ON CustomerID IN Blah", // table does not exist "BUILD CLUSTERED FILE ON Customers AND Blah", "BUILD CLUSTERED FILE ON Blah AND Customers", "BUILD HASH TABLE ON Blah IN Customers", // column does not exist }) void invalidBuildFileStructure(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.BUILD_FILE_STRUCTURE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "REMOVE FILE STRUCTURE ON CustomerID IN Customers", "REMOVE CLUSTERED FILE ON Customers AND CustomerPurchaseDetails" }) void validRemoveFileStructure(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.REMOVE_FILE_STRUCTURE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertTrue(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } @ParameterizedTest @ValueSource(strings = { "REMOVE FILE STRUCTURE ON CustomerID IN Blah", // table does not exist "REMOVE CLUSTERED FILE ON Customers AND Blah", "REMOVE CLUSTERED FILE ON Blah AND Customers", "REMOVE FILE STRUCTURE ON Blah IN Customers" // column does not exist }) void invalidRemoveFileStructure(String createTable) { System.out.println(createTable); String[] filtered = Utilities.filterInput(createTable); boolean isValid = verifier.isValid(InputType.REMOVE_FILE_STRUCTURE, filtered, tables, users); System.out.println("Error code: " + verifier.getErrorMessage()); verifier.resetErrorMessage(); assertFalse(isValid); System.out.println("-----------------------------------------------------------------------------------------"); } }
Java
CL
6550fba57e0a873a8b253cc565f1281235644ebd3eaac7faf2f3e426f0904ef5
package aml; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import aml.match.Alignment; import aml.match.Mapping; import aml.ontology.Individual; import aml.ontology.Lexicon; import aml.ontology.Ontology; import aml.ontology.Ontology2Match; import aml.ontology.Relationship; import aml.ontology.RelationshipMap; public class Test {/** * Implements algorithm to match instances in AML to be applied to Author Disambiguation Task (author­dis task) of OAEI 2015. * @authors Suriya Sundararaj, Roshna Ramesh * @version 1.0 * @since 2015-12-04 */ public static Ontology source; public static Ontology target; public static Lexicon sLex; public static Lexicon tLex; public static Map<Individual,String> sourceTitles=new HashMap<Individual,String>(); public static Map<Individual,String> targetTitles=new HashMap<Individual,String>(); public static Map<Individual,String> individualNames=new HashMap<Individual,String>(); public static Map<Individual,Set<Individual>> matchingPublication=new HashMap<Individual,Set<Individual>>(); public static Map<Individual,Set<Individual>> sourcePersons = new HashMap<Individual, Set<Individual>>(); public static Map<Individual,Set<String>> targetPersons = new HashMap<Individual, Set<String>>(); public static Map<String,Integer> sourceIndividuals=new HashMap<String, Integer>(); public static Map<String,Integer> targetIndividuals=new HashMap<String, Integer>(); public static Map<Individual,Set<Individual>> matchingNames = new HashMap<Individual, Set<Individual>>(); public static Map<Individual,Individual> alignments=new HashMap<Individual, Individual>(); public static Map<Set<Individual>,Integer> alignmentSet=new HashMap<Set<Individual>,Integer>(); public static Multimap<Individual, Individual> multiAlignmentMap = ArrayListMultimap.create(); //Main Method public static void main(String[] args) throws Exception { //Path to input ontology files (edit manually) String sourcePath = "/Users/roshnaramesh/Documents/AgreementMakerLight/store/author disambiguation sandbox/ontoA.owl"; String targetPath = "/Users/roshnaramesh/Documents/AgreementMakerLight/store/author disambiguation sandbox/ontoB.owl"; //Path to reference alignment (for evaluation / repair) String referencePath = "/Users/roshnaramesh/Documents/AgreementMakerLight/store/author disambiguation sandbox/refalign.rdf"; //Path to save output alignment (edit manually, or leave blank for no evaluation) String outputPath = "/Users/roshnaramesh/Documents/AgreementMakerLight/store/author disambiguation sandbox/output.rdf"; AML aml = AML.getInstance(); aml.openOntologies(sourcePath, targetPath); Ontology2Match ontObjA=new Ontology2Match(sourcePath); Ontology2Match ontObjB=new Ontology2Match(targetPath); RelationshipMap rm=aml.getRelationshipMap(); Alignment a=new Alignment(true); //Objects for Ontology2Match Set<Integer> individuals=ontObjA.getIndividuals(); Set<Integer> individualsB=ontObjB.getIndividuals(); //Data Property & Object Property String titleA=null; String titleB=null; /*Get the title for the publications and pre-process the title * Store it in map: sourceTitles and targetTitles */ for (int i : individuals) { Individual ind=ontObjA.getIndividual(i); if(ind.getDataValue(3)!=null); Set<String> title=ind.getDataValue(3); if(title != null) for(String s:title) { titleA=s; sourceTitles.put(ind, preprocess(titleA)); } } for (int i : individualsB) { Individual ind=ontObjB.getIndividual(i); if(ind.getDataValue(3)!=null); Set<String> title=ind.getDataValue(3); if(title != null) for(String t:title) { titleB=t; targetTitles.put(ind,preprocess(titleB)); } } /* Finding the names of the Individuals of person class * Storing it in the map: individualNames (for both the source and target ontologies) */ for(int i:individuals) { Individual indA=ontObjA.getIndividual(i); String nameA=""; if(indA.getDataValue(9) != null) for(String s:indA.getDataValue(9)) { String[] temp=s.split(" "); for(String t: temp) { if(t.length()!=1) nameA=nameA+t+" "; } nameA=nameA.trim(); } individualNames.put(indA, nameA); } for(int j:individualsB) { Individual indB=ontObjB.getIndividual(j); String nameB=""; if(indB.getDataValue(9) != null) for(String s:indB.getDataValue(9)) { String[] temp=s.split(" "); for(String t: temp) { if(t.length()!=1) nameB=nameB+t+" "; } nameB=nameB.trim(); } individualNames.put(indB, nameB);} //Matching the Publication class /*Obtain the individuals of the publication class and their corresponding titles *Clean the title strings to get rid of HTML tags,special characters and multiple spaces * */ for(Map.Entry<Individual, String> entry:sourceTitles.entrySet()){ Individual pubA=entry.getKey(); Individual authorA=null; Set<Integer> authorASet=rm.getChildrenIndividuals(pubA.getIndex(), 14);//get the author names of each individual for(int auth:authorASet){ authorA=ontObjA.getIndividual(auth);} String srcTitle=entry.getValue(); for(Map.Entry<Individual,String> entry2:targetTitles.entrySet()){ Individual pubB=entry2.getKey(); Individual authorB=null; Set<Integer> authorBSet=rm.getChildrenIndividuals(pubB.getIndex(), 14); for(int auth:authorBSet){ authorB=ontObjB.getIndividual(auth);} String targetTitle=entry2.getValue(); if(srcTitle.equalsIgnoreCase(targetTitle))//get matched publications { if(individualNames.get(authorA).equals(individualNames.get(authorB)))//Match the authors of the mapped publications { if(!matchingPublication.containsKey(pubA)) { Set<Individual> val=new HashSet<Individual>(); val.add(pubB); matchingPublication.put(pubA, val); } else { Set<Individual> val=matchingPublication.get(pubA); val.add(pubB); matchingPublication.put(pubA, val); } multiAlignmentMap.put(authorA, authorB);//add matched authors to a multimap } } } } /* * To handle cases where each each publication in source ontology has multiple publications with same * author name and title i.e a person in ontology A has multiple mappings with a persons in ontology B */ for(Individual indA : multiAlignmentMap.keySet()) { List<Individual> listOfIndB = (List<Individual>) multiAlignmentMap.get(indA); float weight=0.0f; Individual finalIndB = null; for(int i = 0; i < listOfIndB.size(); i++) { Individual tempInd=listOfIndB.get(i); int pubCountB=rm.getParentIndividuals(tempInd.getIndex(), 14).size(); //For every author in ontology A, find the number of common publications for author in ontology B int freq=Collections.frequency(listOfIndB, tempInd); //Calculate weight for an alignment as ((No.of.Matching Publication)/TotalPublicationsofB) *100 float totweight=((float)freq/(float)pubCountB)*100; if(totweight>weight) { weight=totweight; finalIndB=tempInd; } } if(finalIndB != null) //assign similarity score of 1.0 to the alignment containing the matched author names a.add(new Mapping(indA.getIndex(),finalIndB.getIndex(),1.0)); } aml.setAlignment(a); if(!referencePath.equals("")) { aml.openReferenceAlignment(referencePath); aml.getReferenceAlignment(); aml.evaluate(); System.out.println(aml.getEvaluation()); } if(!outputPath.equals("")) aml.saveAlignmentRDF(outputPath); } public static String preprocess(String label) { /** * This is the method to pre-process a given string * @param publication title * @return pre-processed string */ label=label.replaceAll("\\<[^>]*>", "");//remove HTML tags label=label.replaceAll("[^A-Za-z0-9]", " ");//remove special characters label=label.replaceAll("\\s+", " ");//remove multiple spaces return label.trim(); } }
Java
CL
60cd55320059ab83b95533fd439aa18776b51003da102f30f91eb63bbb3de521
package com.csc.fsg.nba.business.process; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import com.csc.dip.jvpms.runtime.base.VpmsComputeResult; import com.csc.fs.logging.LogHandler; import com.csc.fsg.nba.access.contract.NbaContractAccess; import com.csc.fsg.nba.access.contract.NbaServerUtility; import com.csc.fsg.nba.datamanipulation.NbaOinkDataAccess; import com.csc.fsg.nba.datamanipulation.NbaOinkFormatter; import com.csc.fsg.nba.datamanipulation.NbaOinkRequest; import com.csc.fsg.nba.exception.NbaBaseException; import com.csc.fsg.nba.exception.NbaDataAccessException; import com.csc.fsg.nba.foundation.NbaConstants; import com.csc.fsg.nba.foundation.NbaOliConstants; import com.csc.fsg.nba.foundation.NbaStringTokenizer; import com.csc.fsg.nba.foundation.NbaUtils; import com.csc.fsg.nba.vo.NbaDst; import com.csc.fsg.nba.vo.NbaLob; import com.csc.fsg.nba.vo.NbaTXLife; import com.csc.fsg.nba.vo.NbaTXRequestVO; import com.csc.fsg.nba.vo.NbaUserVO; import com.csc.fsg.nba.vpms.NbaVpmsAdaptor; import com.csc.fsg.nba.vpms.NbaVpmsConstants; /** * The NbaProcessWorkItemProvider services the <code>NbaAutomatedProcess<code> by calling * VPMS to retrieve the work type and status for a work item created in the process. * <p> * <b>Modifications:</b><br> * <table border=0 cellspacing=5 cellpadding=5> * <thead> * <th align=left>Project</th><th align=left>Release</th><th align=left>Description</th> * </thead> * <tr><td>NBA004</td><td>Version 2</td><td>Automated Process Model Support for Work Items</td></tr> * <tr><td>NBA021</td><td>Version 2</td><td>Data Resolver</td></tr> * <tr><td>NBA020</td><td>Version 2</td><td>AWD Priority</td></tr> * <tr><td>NBA009</td><td>Version 2</td><td>Cashiering</td></tr> * <tr><td>NBA058</td><td>Version 3</td><td>Upgrade to J-VPMS version 1.5.0</td></tr> * <tr><td>NBA035</td><td>Version 3</td><td>App submit to Pending DB</td></tr> * <tr><td>NBA050</td><td>Version 3</td><td>Pending Database</td></tr> * <tr><td>NBA073</td><td>Version 3</td><td>Agent Validation/Retrieve Contract Info</td></tr> * <tr><td>ACN012</td><td>Version 4</td><td>Architecture Changes</td></tr> * <tr><td>NBA077</td><td>Version 4</td><td>Reissues and Complex Change etc.</td></tr> * <tr><td>ACN014</td><td>Version 3</td><td>121/1122 Migration</td></tr> * <tr><td>SPR2639</td><td>Version 5</td><td>Automated process status should be based business function</td></tr> * <tr><td>NBA130</td><td>Version 6</td><td>Requirement/Reinsurance Changes</td></tr> * <tr><td>NBA213</td><td>Version 7</td><td>Unified User Interface</td></tr> * <tr><td>SPR3362</td><td>Version 7</td><td>Exceptions in Automated Processes and Logon Service Due to VP/MS Memory Leak</td></tr> * <tr><td>SPR3290</td><td>Version 7</td><td>General source code clean up during version 7</td></tr> * <tr><td>APSL3881</td><td>Discretionary</td><td>Follow The Sun</td></tr> * </table> * <p> * @author CSC FSG Developer * @version 7.0.0 * @see com.csc.fsg.nba.business.process.NbaAutomatedProcess * @since New Business Accelerator - Version 2 */ public class NbaProcessWorkItemProvider { /** * Provides additional initialization support by setting the * case and user objects to the passed in parameters and by * creating a reference to the NbaNetServerAccessor EJB. * @param newUser the AWD User for the process * @param newWork the NbaDst value object to be processed * @return <code>true</code> indicates the statuses were successfully * retrieved while <code>false</code> indicates failure. * @throws NbaBaseException */ // NBA050 NEW METHOD public NbaTXLife retrieveContract(NbaUserVO newUser, NbaDst newWork) throws NbaBaseException { try { return NbaContractAccess.doContractInquiry(createRequestObject(newWork, newUser)); //NBA213 } catch (NbaBaseException nbe) { if (nbe instanceof NbaDataAccessException) { return null; } else { throw nbe; } } catch (Exception re) { throw new NbaBaseException(re); } } /** The string representing the work type */ public java.lang.String workType; /** The string representing the initial status */ public java.lang.String initialStatus; /** The string representing the work item priority */ public java.lang.String wiPriority;//NBA020 /** The string representing the work item action */ public java.lang.String wiAction;//NBA020 /** * NbaProcessWorkItemProvider constructor comment. */ public NbaProcessWorkItemProvider() { super(); } /** * NbaProcessWorkItemProvider constructor. * * @param user com.csc.fsg.nba.vo.NbaUserVO * @throws NbaBaseException */ public NbaProcessWorkItemProvider(com.csc.fsg.nba.vo.NbaUserVO user) throws NbaBaseException { initializeFields(user, (NbaDst)null,"-"); //NBA077 } /** * NbaProcessWorkItemProvider constructor. * * @param user com.csc.fsg.nba.vo.NbaUserVO * @param sourceType java.lang.String * @throws NbaBaseException */ // NBA021 NEW METHOD public NbaProcessWorkItemProvider(com.csc.fsg.nba.vo.NbaUserVO user, NbaDst aNbaDst) throws NbaBaseException { initializeFields(user, aNbaDst); } /** * NbaProcessWorkItemProvider constructor. * * @param user com.csc.fsg.nba.vo.NbaUserVO * @param sourceType java.lang.String * @param aNbaDst user com.csc.fsg.nba.vo.NbaDst * @throws NbaBaseException */ //NBA020 change method signature public NbaProcessWorkItemProvider(com.csc.fsg.nba.vo.NbaUserVO user, NbaDst aNbaDst, String sourceType) throws NbaBaseException { initializeFields(user, aNbaDst, sourceType); } /** * NbaProcessWorkItemProvider constructor. * * @param user com.csc.fsg.nba.vo.NbaUserVO * @param aNbaDst user com.csc.fsg.nba.vo.NbaDst * @param deOink Map * @throws NbaBaseException */ //NBA073 New Method public NbaProcessWorkItemProvider(com.csc.fsg.nba.vo.NbaUserVO user, NbaDst aNbaDst, Map deOink) throws NbaBaseException { initializeFields(user, aNbaDst, deOink, null); //SPR2639 } /** * NbaProcessWorkItemProvider constructor. * @param user the user value object * @param aNbaDst the workitem * @param nbaTXLife the holding inquiry object. * @param deOink the deOink Map * @throws NbaBaseException */ //SPR2639 New Method public NbaProcessWorkItemProvider(NbaUserVO user, NbaDst aNbaDst, NbaTXLife nbaTXLife, Map deOink) throws NbaBaseException { initializeFields(user, aNbaDst, deOink, nbaTXLife); //SPR2639 } /** * * NbaProcessWorkItemProvider constructor. * * @param user the user value object * @param aNbaDst work item representing contract information * @param sourceType source type * @param nbaMoney whether its nbA Money or not * @throws NbaBaseException */ //NBA009 new method public NbaProcessWorkItemProvider(NbaUserVO user, NbaDst aNbaDst, String sourceType, String nbaMoney) throws NbaBaseException { initializeFields(user, aNbaDst, sourceType, nbaMoney); } /** * NbaProcessWorkItemProvider constructor. * * @param user com.csc.fsg.nba.vo.NbaUserVO * @param sourceType java.lang.String * @throws NbaBaseException */ // NBA021 NEW METHOD public NbaProcessWorkItemProvider(com.csc.fsg.nba.vo.NbaUserVO user, NbaLob aNbaLob) throws NbaBaseException { initializeFields(user, aNbaLob, "-"); //NBA077 } /** * NbaProcessWorkItemProvider constructor. * * @param user com.csc.fsg.nba.vo.NbaUserVO * @param aNbaLob the NbaLob object * @param sourceType java.lang.String * @throws NbaBaseException */ // NBA077 NEW METHOD public NbaProcessWorkItemProvider(NbaUserVO user, NbaLob aNbaLob, String sourceType) throws NbaBaseException { initializeFields(user, aNbaLob, sourceType); } /** * Returns the initial status of a work item. * * @return java.lang.String */ public String getInitialStatus() { return initialStatus; } /** * Answers the priorityAction * @return the work item priority action */ //NBA020 New Method public java.lang.String getWIAction() { return wiAction; } /** * Answers the workPriority * @return the work item priority */ //NBA020 New Method public java.lang.String getWIPriority() { return wiPriority; } /** * Returns the work type of the work item. * * @return java.lang.String */ public String getWorkType() { return workType; } /** * This method sets up and performs the call to VP/MS to determine the * aNbaDst type and status for a aNbaDst item based on the user ID and source * type. (The user ID is used to get business function for an automated process.) * Using an NbaVpmsAdaptor object, VP/MS is called passing in an NbaVpmsVO * object. The result is then used to populate the member variables in the * updateFields method. * * @param user the process ID * @param sourceType java.lang.String * @throws NbaBaseException */ // NBA021 NEW METHOD public void initializeFields(NbaUserVO user, NbaDst aNbaDst) throws NbaBaseException { NbaOinkDataAccess oink = new NbaOinkDataAccess(aNbaDst.getNbaLob()); //NBA050 BEGIN NbaTXLife aNbaTXLife = retrieveContract(user, aNbaDst); //NBA050 END //NBA050 CODE DELETED //NBA035 code deleted //NBA050 CODE DELETED if (aNbaTXLife != null) { oink.setContractSource(aNbaTXLife); oink.setLobSource(aNbaDst.getNbaLob()); //NBA050 } Map deOink = new HashMap(); deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); //SPR2639 deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaDst.getNbaLob(), null)); //NBA130 NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); vpmsProxy.setSkipAttributesMap(deOink); try { VpmsComputeResult result = vpmsProxy.getResults(); if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); //SPR3362 code deleted } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); //begin SPR3362 } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } //end SPR3362 } /** * This method sets up and performs the call to VP/MS to determine the * work type and status for a work item based on the user ID and source * type. (The user ID is used to get business function for an automated process.) * @param user the process ID * @param aNbaDst A work item representing contract information * @param source A Correspondence Source * @throws NbaBaseException */ // ACN012 Change signature public void initializeFields(NbaUserVO user, NbaDst aNbaDst, com.csc.fsg.nba.vo.nbaschema.Correspondence source) throws NbaBaseException { // NBA021 Code deleted // NBA021 BEGIN NbaOinkDataAccess oink = new NbaOinkDataAccess(); oink.setLobSource(aNbaDst.getNbaLob()); Map deOink = new HashMap(); deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); //SPR2639 deOink.put("A_LETTERTYPE", source.getLetterType()); // NBA021 END deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaDst.getNbaLob(), null)); //NBA130 NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); // NBA021 vpmsProxy.setSkipAttributesMap(deOink); // NBA021 vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); // NBA021 try { VpmsComputeResult result = vpmsProxy.getResults(); // did we get a bad return code from VP/MS? if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); //SPR3362 code deleted } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); // begin SPR3362 } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } //end SPR3362 } /** * This method sets up and performs the call to VP/MS to determine the * work type and status for a work item based on the user ID and source * type. (The user ID is used to get business function for an automated process.) * Using an NbaVpmsAdaptor object, VP/MS is called passing in an NbaVpmsVO * object. The result is then used to populate the member variables in the * updateFields method. * * @param user the process ID * @param sourceType java.lang.String * @param aNbaDst user com.csc.fsg.nba.vo.NbaDst * @throws NbaBaseException */ //NBA020 change method signature public void initializeFields(NbaUserVO user, NbaDst aNbaDst, String sourceType) throws NbaBaseException { // NBA021 Code deleted // NBA021 BEGIN // NBA050 BEGIN NbaTXLife aNbaTXLife = retrieveContract(user, aNbaDst); // NBA050 CODE DELETED NbaOinkDataAccess oink = new NbaOinkDataAccess(); oink.setContractSource(aNbaTXLife); oink.setLobSource(aNbaDst.getNbaLob()); // NBA050 END Map deOink = new HashMap(); deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); //SPR2639 deOink.put("A_SourceTypeLOB", sourceType); // NBA021 END deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaDst.getNbaLob(), null)); //NBA130 NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); // NBA021 vpmsProxy.setSkipAttributesMap(deOink); // NBA021 vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); // NBA021 try { VpmsComputeResult result = vpmsProxy.getResults(); // did we get a bad return code from VP/MS? if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); //SPR3362 code deleted } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); //begin SPR3362 } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } //end SPR3362 } /** * This method sets up and performs the call to VP/MS to determine the * work type and status for a work item based on the user ID and source * type. (The user ID is used to get business function for an automated process.) * Using an NbaVpmsAdaptor object, VP/MS is called passing in an NbaVpmsVO * object. The result is then used to populate the member variables in the * updateFields method. * * @param user the user value object * @param aNbaDst work item representing contract information * @param sourceType source type * @param nbaMoney whether its nbA Money or not * @throws NbaBaseException */ //NBA009 new method public void initializeFields(NbaUserVO user, NbaDst aNbaDst, String sourceType, String nbaMoney) throws NbaBaseException { NbaOinkDataAccess oink = new NbaOinkDataAccess(aNbaDst.getNbaLob()); //NBA020 initialize with NbaDst Map deOink = new HashMap(); deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); //SPR2639 deOink.put("A_SOURCETYPELOB", sourceType); deOink.put("A_NBAMONEY", nbaMoney); deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaDst.getNbaLob(), null)); //NBA130 NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); vpmsProxy.setSkipAttributesMap(deOink); vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); try { VpmsComputeResult result = vpmsProxy.getResults(); // did we get a bad return code from VP/MS? if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); //SPR3362 code deleted } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); //begin SPR3362 } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } //end SPR3362 } /** * This method sets up and performs the call to VP/MS to determine the * work type and status for a work item based on the user ID and source * type. (The user ID is used to get business function for an automated process.) * Using an NbaVpmsAdaptor object, VP/MS is called passing in an NbaVpmsVO * object. The result is then used to populate the member variables in the * updateFields method. * * @param user the user value object * @param aNbaDst work item representing contract information * @param deOink Map the deOink map * @param nbaTXLife the holding inquiry * @throws NbaBaseException */ //NBA073 new method //SPR2639 Added parameter nbaTXLife public void initializeFields(NbaUserVO user, NbaDst aNbaDst, Map deOink, NbaTXLife nbaTXLife) throws NbaBaseException { NbaOinkDataAccess oink = new NbaOinkDataAccess(aNbaDst.getNbaLob()); //NBA020 initialize with NbaDst if (null != nbaTXLife) { //SPR2639 oink.setContractSource(nbaTXLife); //SPR2639 } //SPR2639 oink.getFormatter().setDateSeparator(NbaOinkFormatter.DATE_SEPARATOR_DASH);//ALS5777 deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); //SPR2639 deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaDst.getNbaLob(), null)); //NBA130 NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); vpmsProxy.setSkipAttributesMap(deOink); vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); try { VpmsComputeResult result = vpmsProxy.getResults(); // did we get a bad return code from VP/MS? if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); //SPR362 code deleted } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); //begin SPR3362 } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } //end SPR3362 } //NBLXA-1696 new method public NbaProcessWorkItemProvider(com.csc.fsg.nba.vo.NbaUserVO user, NbaDst aNbaDst,NbaOinkRequest oinkRequest,Map deOink) throws NbaBaseException { initializeFields(user, aNbaDst,oinkRequest,deOink); } //NBLXA- 1696 new method start public void initializeFields(NbaUserVO user, NbaDst aNbaDst, NbaOinkRequest oinkRequest , Map deOink ) throws NbaBaseException { NbaOinkDataAccess oink = new NbaOinkDataAccess(aNbaDst.getNbaLob()); NbaTXLife aNbaTXLife = retrieveContract(user, aNbaDst); if (aNbaTXLife != null) { oink.setContractSource(aNbaTXLife); oink.setLobSource(aNbaDst.getNbaLob()); } deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaDst.getNbaLob(), null)); NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); vpmsProxy.setSkipAttributesMap(deOink); if(oinkRequest != null){ vpmsProxy.setANbaOinkRequest(oinkRequest); } try { VpmsComputeResult result = vpmsProxy.getResults(); if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } } //NBLXA-1696 end /** * This method sets up and performs the call to VP/MS to determine the * work type and status for a work item based on the user ID and source * type. (The user ID is used to get business function for an automated process.) * Using an NbaVpmsAdaptor object, VP/MS is called passing in an NbaVpmsVO * object. The result is then used to populate the member variables in the * updateFields method. * * @param user the process ID * @param aNbaLob the NbaLob object * @param sourceType java.lang.String * @throws NbaBaseException */ //NBA021 NEW METHOD // NBA077 added new parameter sourceType public void initializeFields(NbaUserVO user, NbaLob aNbaLob, String sourceType) throws NbaBaseException { NbaOinkDataAccess oink = new NbaOinkDataAccess(aNbaLob); Map deOink = new HashMap(); deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); //SPR2639 deOink.put("A_SourceTypeLOB", sourceType); deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaLob, null)); //NBA130 NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); vpmsProxy.setSkipAttributesMap(deOink); try { VpmsComputeResult result = vpmsProxy.getResults(); if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); //SPR3362 code deleted } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); //begin SPR3362 } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } //end SPR3362 } /** * Sets the initial status of the work item. * * @param newInitialStatus */ public void setInitialStatus(String newInitialStatus) { initialStatus = newInitialStatus; } /** * Sets the new work type priority action flag. * * @param newPriorityAction */ //NBA020 New Method public void setWIAction(String newPriorityAction) { wiAction = newPriorityAction; } /** * Sets the new work type priority. * * @param newWorkPriority */ //NBA020 New Method public void setWIPriority(String newWorkPriority) { wiPriority = newWorkPriority; } /** * Sets the new work type for the work item. * * @param newWorkType */ public void setWorkType(String newWorkType) { workType = newWorkType; } /** * The results from the VPMS model are parsed. The work type and status * are retrieved and used to update the field members. * * @param result the result from the VPMS call * @param aDelimiter the delimiter used by the VPMS model to separate status fields */ public void updateFields(VpmsComputeResult result) { if (result.getReturnCode() == 0) { // SPR3290 code deleted NbaStringTokenizer tokens = new NbaStringTokenizer(result.getResult().trim(), NbaVpmsAdaptor.VPMS_DELIMITER[0]); // NBA021 Code Deleted setWorkType(tokens.nextToken()); setInitialStatus(tokens.nextToken()); setWIAction(tokens.nextToken()); //NBA020 setWIPriority(tokens.nextToken()); //NBA020 } } /** * The results from the VPMS model are parsed. The work type and status * are retrieved and used to update the field members. * * @param result the result from the VPMS call * @param aDelimiter the delimiter used by the VPMS model to separate status fields */ public void updateFields(VpmsComputeResult result, String aDelimiter) { // SPR3290 code deleted NbaStringTokenizer tokens = new NbaStringTokenizer(result.getResult().trim(), aDelimiter); String aToken = tokens.nextToken(); // First token is empty - don't need it. while (tokens.hasMoreTokens()) { aToken = tokens.nextToken(); StringTokenizer bToken = new StringTokenizer(aToken, ":"); String statusType = bToken.nextToken(); String statusValue = bToken.nextToken(); if (statusType.equals("TYPE")) setWorkType(statusValue); else if (statusType.equals("STAT")) setInitialStatus(statusValue); } } /** * Create a TX Request value object that will be used to retrieve the contract. * @param work the workitem object for that holding request is required * @param user the user value object * @return a value object that is the request */ public NbaTXRequestVO createRequestObject(NbaDst work, NbaUserVO user) { NbaTXRequestVO nbaTXRequest = new NbaTXRequestVO(); nbaTXRequest.setTransType(NbaOliConstants.TC_TYPE_HOLDINGINQ); nbaTXRequest.setTransMode(NbaOliConstants.TC_MODE_ORIGINAL); nbaTXRequest.setInquiryLevel(NbaOliConstants.TC_INQLVL_OBJECTALL); nbaTXRequest.setNbaLob(work.getNbaLob()); nbaTXRequest.setNbaUser(user); nbaTXRequest.setWorkitemId(work.getID()); nbaTXRequest.setCaseInd(work.isCase()); //ACN014 nbaTXRequest.setAccessIntent(NbaConstants.READ); nbaTXRequest.setBusinessProcess(NbaUtils.getBusinessProcessId(user)); //SPR2639 return nbaTXRequest; } // APSL3381 New method public NbaProcessWorkItemProvider(com.csc.fsg.nba.vo.NbaUserVO user, NbaDst aNbaDst, NbaOinkRequest oinkRequest) throws NbaBaseException { initializeFields(user, aNbaDst, oinkRequest); } // APSL3381 New method public void initializeFields(NbaUserVO user, NbaDst aNbaDst, NbaOinkRequest oinkRequest) throws NbaBaseException { NbaOinkDataAccess oink = new NbaOinkDataAccess(aNbaDst.getNbaLob()); NbaTXLife aNbaTXLife = retrieveContract(user, aNbaDst); if (aNbaTXLife != null) { oink.setContractSource(aNbaTXLife); oink.setLobSource(aNbaDst.getNbaLob()); } Map deOink = new HashMap(); deOink.put(NbaVpmsAdaptor.A_PROCESS_ID, NbaUtils.getBusinessProcessId(user)); deOink.put(NbaVpmsConstants.A_DATASTORE_MODE, NbaServerUtility.getDataStore(aNbaDst.getNbaLob(), null)); NbaVpmsAdaptor vpmsProxy = new NbaVpmsAdaptor(oink, NbaVpmsAdaptor.AUTO_PROCESS_STATUS); vpmsProxy.setVpmsEntryPoint(NbaVpmsAdaptor.EP_GET_WORKTYPE_AND_STATUS); vpmsProxy.setSkipAttributesMap(deOink); if(oinkRequest != null){ vpmsProxy.setANbaOinkRequest(oinkRequest); } try { VpmsComputeResult result = vpmsProxy.getResults(); if (result.getReturnCode() != 0 && result.getReturnCode() != 1) { throw new Throwable(result.getMessage()); } updateFields(result); } catch (java.rmi.RemoteException re) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, re); } catch (Throwable t) { throw new NbaBaseException(NbaBaseException.VPMS_AUTOMATED_PROCESS_WORKITEM, t); } finally { try { if (vpmsProxy != null) { vpmsProxy.remove(); } } catch (Throwable th) { LogHandler.Factory.LogError(this, NbaBaseException.VPMS_REMOVAL_FAILED); } } } }
Java
CL
6007d3c15c0e434c9b95b29624f2bd6dd05b80b3972bdba6ff7948d119264657
package com.baayso.springcloud.common.core.exception.handler; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.ObjectError; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import com.baayso.commons.exception.ApiException; import com.baayso.commons.tool.BasicResponseStatus; import com.baayso.commons.tool.ResponseStatus; import com.baayso.commons.utils.JsonUtils; import com.baayso.commons.web.WebUtils; import com.baayso.springcloud.common.core.domain.ResultVO; import lombok.extern.slf4j.Slf4j; /** * 全局异常处理器。 * * @author ChenFangjie * @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler * @since 0.1 */ @Slf4j @RestControllerAdvice public final class CustomExceptionHandler { /** * 处理ApiException异常。 * * @since 0.1 */ @ExceptionHandler(value = {ApiException.class}) public ResultVO<String> handleApiServiceException(ApiException ex, HttpServletRequest request) { return this.handleException(ex.getResponseStatus(), ex, request); } /** * 处理Exception异常。 * * @since 0.1 */ @ExceptionHandler(value = {Exception.class}) public ResultVO<String> handleGeneralException(Exception ex, HttpServletRequest request) { return this.handleException(BasicResponseStatus.SERVER_INTERNAL_ERROR, ex, request); } /** * 处理缺少请求参数异常。 * * @since 0.1 */ @ExceptionHandler({MissingServletRequestParameterException.class}) public ResultVO<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex, HttpServletRequest request) { return this.handleException(BasicResponseStatus.PARAMETER_MISSING, ex, request); } /** * 处理请求参数类型不匹配异常。 * * @since 0.1 */ @ExceptionHandler({MethodArgumentTypeMismatchException.class}) public ResultVO<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex, HttpServletRequest request) { return this.handleException(BasicResponseStatus.PARAMETER_TYPE_ERROR, ex, request); } /** * 处理请求method不匹配异常。 * * @since 0.1 */ @ExceptionHandler({HttpRequestMethodNotSupportedException.class}) public ResultVO<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex, HttpServletRequest request) { return this.handleException(BasicResponseStatus.METHOD_NOT_ALLOWED, ex, request); } /** * 处理请求头Content-Type属性不匹配异常。 * * @since 0.1 */ @ExceptionHandler({HttpMediaTypeNotSupportedException.class}) public ResultVO<String> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException ex, HttpServletRequest request) { return this.handleException(BasicResponseStatus.CONTENT_TYPE_NOT_SUPPORTED, ex, request); } /** * 处理Controller方法中@RequestBody类型参数数据类型转换异常。 * * @since 0.1 */ @ExceptionHandler({HttpMessageNotReadableException.class}) public ResultVO<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex, HttpServletRequest request) { return this.handleException(BasicResponseStatus.REQUEST_BODY_DATA_CONVERT_ERROR, ex, request); } /** * 处理Controller方法参数校验异常。 * * @since 0.1 */ @ExceptionHandler(value = {MethodArgumentNotValidException.class}) public ResultVO<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) { // 注入ServletRequest,用于出错时打印请求URL与来源地址 this.logError(ex, request); // 从异常对象中拿到ObjectError对象 ObjectError objectError = ex.getBindingResult().getAllErrors().get(0); ResultVO<String> result = new ResultVO<>(); result.setSuccess(false); result.setCode(BasicResponseStatus.PARAMETER_CHECK_FAILED.value()); result.setMessage(BasicResponseStatus.PARAMETER_CHECK_FAILED.getReason()); result.setData(objectError.getDefaultMessage()); // 错误提示信息 return result; } private ResultVO<String> handleException(ResponseStatus responseStatus, Exception ex, HttpServletRequest request) { // 注入ServletRequest,用于出错时打印请求URL与来源地址 this.logError(ex, request); ResultVO<String> result = new ResultVO<>(); result.setSuccess(false); result.setCode(responseStatus.value()); result.setMessage(responseStatus.getReason()); result.setData(ex.getMessage()); // 错误提示信息 return result; } /** * 记录错误日志。 * * @since 0.1 */ public void logError(Exception ex) { Map<String, String> map = new HashMap<>(1); map.put("message", ex.getMessage()); log.error(JsonUtils.INSTANCE.toJson(map), ex); } /** * 记录与http相关的错误日志。 * * @since 0.1 */ public void logError(Exception ex, HttpServletRequest request) { String queryString = request.getQueryString(); Map<String, String> map = new HashMap<>(3); map.put("message", ex.getMessage()); map.put("from", WebUtils.getRealIp(request)); map.put("path", StringUtils.isNotBlank(queryString) ? (request.getRequestURI() + "?" + queryString) : request.getRequestURI()); log.error(JsonUtils.INSTANCE.toJson(map), ex); } }
Java
CL
1e39697ad3a9f9dff80dd30eb635f92f7c0fcfbe6c2356872771764a7f1893b3
package pl.ukaszapps.fairbid_flutter; import android.util.Log; import androidx.annotation.NonNull; import com.fyber.fairbid.ads.ImpressionData; import com.fyber.fairbid.ads.banner.BannerError; import com.fyber.fairbid.ads.banner.BannerListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import io.flutter.plugin.common.MethodChannel; import static pl.ukaszapps.fairbid_flutter.FairBidFlutterPlugin.runOnMain; class BannerCreationResultListener implements BannerListener { private Map<String, MethodChannel.Result> resultCallbacks = new HashMap<>(); @Override public void onError(@NonNull String s, final BannerError bannerError) { } @Override public void onLoad(@NonNull String s) { if (FairBidFlutterPlugin.debugLogging) { Log.d("BannerCreationL", "onLoad: " + s); } final MethodChannel.Result callback = resultCallbacks.remove(s); if (callback != null) { runOnMain(() -> callback.success(s)); } } @Override public void onShow(@NonNull String s, @NonNull ImpressionData impressionData) { } @Override public void onClick(@NonNull String s) { } @Override public void onRequestStart(@NonNull String s) { } public void registerCallback(String placement, MethodChannel.Result result) { resultCallbacks.put(placement, result); } public void unregisterCallback(String placement) { resultCallbacks.remove(placement); } }
Java
CL
2e354314367d310fd4d22a6a46037bd0f6ea74efb55fd808c368470897d7d447
package ru.mail.parking.widget; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.SystemClock; import java.util.Calendar; import ru.mail.parking.App; import ru.mail.parking.R; import ru.mail.parking.utils.NetworkAwaiter; import static java.util.Calendar.DAY_OF_WEEK; import static java.util.Calendar.DAY_OF_YEAR; import static java.util.Calendar.HOUR_OF_DAY; import static java.util.Calendar.MINUTE; import static java.util.Calendar.SATURDAY; import static java.util.Calendar.SECOND; import static java.util.Calendar.SUNDAY; import static java.util.Calendar.getInstance; import static ru.mail.parking.App.app; public final class SmartUpdate { private static final AlarmManager sAlarmManager; static { sAlarmManager = (AlarmManager)app().getSystemService(Context.ALARM_SERVICE); } private SmartUpdate() {} @SuppressWarnings("UnusedDeclaration") public enum Policy { auto { @Override public void schedule() { schedule(REGULAR_INTERVAL); } }, manual { @Override public void schedule() { // Do nothing here } }, smart { private static final int WORKDAY_HOT_START = 9; // Hour at which the `hot` period starts… private static final int WORKDAY_HOT_END = 12; // …and ends private static final int WORKDAY_HOT_INTERVAL = 15 * 60000; // Update interval within `hot` period private static final int WORKDAY_INTERVAL = REGULAR_INTERVAL; private Calendar newZero(Calendar c) { Calendar res = (Calendar)c.clone(); res.set(HOUR_OF_DAY, 0); res.set(MINUTE, 0); res.set(SECOND, 0); return res; } @Override public void schedule() { final Calendar now = getInstance(); Calendar next = newZero(now); int weekday = now.get(DAY_OF_WEEK); int hour = now.get(HOUR_OF_DAY); // Holiday? if (weekday == SATURDAY || weekday == SUNDAY) { next.add(DAY_OF_YEAR, 1); if (next.get(DAY_OF_WEEK) == SUNDAY) next.add(DAY_OF_YEAR, 1); next.add(HOUR_OF_DAY, WORKDAY_HOT_START); schedule(next.getTimeInMillis() - now.getTimeInMillis()); return; } // Before `hot` time? if (hour < WORKDAY_HOT_START) { next.set(HOUR_OF_DAY, WORKDAY_HOT_START); schedule(next.getTimeInMillis() - now.getTimeInMillis()); return; } // Within `hot` time? if (hour < WORKDAY_HOT_END) { schedule(WORKDAY_HOT_INTERVAL); return; } // Past `hot time?` schedule(WORKDAY_INTERVAL); } }; private static final int REGULAR_INTERVAL = 60 * 60000; private static Policy sDefault; public static Policy getDefault() { if (sDefault == null) sDefault = valueOf(app().getString(R.string.prefs_config_update_mode_default)); return sDefault; } protected void schedule(long delay) { sAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + delay, createActionIntent()); } public abstract void schedule(); } private static PendingIntent createActionIntent() { Intent it = new Intent(app(), MainReceiver.class) .setAction(MainReceiver.ACTION_UPDATE); return PendingIntent.getBroadcast(app(), 0, it, PendingIntent.FLAG_CANCEL_CURRENT); } private static void execute(final boolean force) { NetworkAwaiter.getInstance().start(SmartUpdate.class.getSimpleName(), new Runnable() { @Override public void run() { UpdateService.start(force); schedule(); } }); } private static void schedule() { App.prefs().getUpdatePolicy().schedule(); } public static void force() { abort(); execute(true); } public static void abort() { PendingIntent pi = createActionIntent(); sAlarmManager.cancel(pi); pi.cancel(); NetworkAwaiter.getInstance().cancelAll(); } public static void restart() { abort(); schedule(); } public static void onAlarm() { execute(false); } public static void onTimeChanged() { restart(); } }
Java
CL
f15f6221b392cefa1c756e0f95e8c077f9e43ee37fa698a6fc2dbf343c96f7d1
/** * Created on Feb 17, 2006 * */ package edu.uoregon.tau.perfexplorer.common; import java.io.Serializable; /** * This class is used as a typesafe enumeration. * * <P>CVS $Id: AnalysisType.java,v 1.5 2009/11/18 17:45:41 khuck Exp $</P> * @author Kevin Huck * @version 0.2 * @since 0.2 */ public final class AnalysisType implements Serializable { /** * */ private static final long serialVersionUID = -5829378530524627781L; /** * One attribute, the name - it is transient so it is not serialized */ private final transient String _name; /** * Static instances of the engine. */ public final static AnalysisType K_MEANS = new AnalysisType("K Means"); public final static AnalysisType K_HARMONIC_MEANS = new AnalysisType("K Harmonic Means"); public final static AnalysisType GEM = new AnalysisType("Gaussian Expectation-Maximization"); public final static AnalysisType FUZZY_K_MEANS = new AnalysisType("Fuzzy K Means"); public final static AnalysisType CORRELATION_ANALYSIS = new AnalysisType("Correlation Analysis"); public final static AnalysisType HIERARCHICAL = new AnalysisType("Hierarchical"); public final static AnalysisType DBSCAN = new AnalysisType("Density Based (DBSCAN)"); /** * The constructor is private, so this class cannot be instantiated. * @param name */ private AnalysisType(String name) { this._name = name; } /** * Only one public method, to return the name of the engine * @return */ public String toString() { return this._name; } /** * Returns the AnalysisType specified by the String. * * @param typeString * @return */ public static AnalysisType fromString(String typeString) { for (int i = 0 ; i < VALUES.length ; i++) { if (typeString.equals(VALUES[i]._name)) return VALUES[i]; } return null; } // The following declarations are necessary for serialization private static int nextOrdinal = 0; private final int ordinal = nextOrdinal++; private static final AnalysisType[] VALUES = {K_MEANS, K_HARMONIC_MEANS, GEM, FUZZY_K_MEANS, CORRELATION_ANALYSIS, HIERARCHICAL, DBSCAN}; /** * This method is necessary, because we are serializing the object. * When the object is serialized, a NEW INSTANCE is created, and we * can't compare reference pointers. When that is the case, replace the * newly instantiated object with a static reference. * * @return * @throws java.io.ObjectStreamException */ Object readResolve () throws java.io.ObjectStreamException { return VALUES[ordinal]; // Canonicalize } /** * Method to return the cluster methods. * @return */ public static Object[] getClusterMethods() { //Object[] options = {K_MEANS, K_HARMONIC_MEANS, GEM, FUZZY_K_MEANS, HIERARCHICAL, DBASE}; Object[] options = {K_MEANS, HIERARCHICAL, DBSCAN}; return options; } }
Java
CL
2ee5f408b5e75af4b79879fe1296ae925e7ac542a1c9a184e8777e2ab6e08fb6
package edu.phystech.vkurse; import java.util.Vector; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import edu.phystech.vkurse.model.*; public class Groups implements GroupsTable { //ключевые переменные для доступа к сервисам private static String NAMESPACE = "http://DefaultNamespace"; private static String URL = "http://nebula.innolab.net.ru:8180/axis/GroupService.jws"; private static String SOAP_ACTION = ""; @Override public Vector<Group> get(int[] arg0) throws TableException { String METHOD_NAME = "get"; Vector<Group> lects = null; Vector<String> res = null; try { Vector<Integer> zed = new Vector<Integer>(); for ( int i = 0; i < arg0.length; i++) { zed.add(arg0[i]); } SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("ids", zed); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); //если пришел пустой массив if (result != null ) { //прочитали данные res = (Vector<String>)result; lects = new Vector<Group>(); //инициализация объектов Group for ( int j = 0; j < res.size(); j++ ) { Group lect = new Group(); if ( res.elementAt(j) != null ) { lect.readData( res.elementAt(j)); } lects.add(lect); } } } catch (Exception e) { throw new TableException("Ошибка при получений данных"); } return lects; } @Override public Group get(int ID) throws TableException { String METHOD_NAME = "get"; Group lect = null; try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("ID", ID); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); //если пршила пустая строка if (result != null ) { lect = new Group(); lect.readData(result.toString()); } } catch ( Exception e) { throw new TableException("Ошибка при получений данных"); } return lect; } @Override public Vector<Group> getAll() throws TableException { String METHOD_NAME = "getAll"; Vector<Group> lects = null; Vector<String> res = null; try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); //если пришел пустой массив if (result != null ) { //прочитали данные res = (Vector<String>)result; lects = new Vector<Group>(); //инициализация объектов Group for ( int j = 0; j < res.size(); j++ ) { Group lect = new Group(); if ( res.elementAt(j) != null ) { lect.readData( res.elementAt(j)); } lects.add(lect); } } } catch (Exception e) { throw new TableException("Ошибка при получений данных"); } return lects; } @Override public int insert(Group item) throws TableException { String METHOD_NAME = "insert"; int res = -1; try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("group", item.toStringData()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); if (result != null) { res = (Integer)result; } } catch ( Exception e) { throw new TableException("Ошибка при получений данных"); } return res; } @Override public boolean remove(int ID) throws TableException { String METHOD_NAME = "remove"; boolean res = false; try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("ID", ID); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); if (result != null) { res = (Boolean)result; } } catch ( Exception e) { throw new TableException("Ошибка при получений данных"); } return res; } @Override public boolean update(Group item) throws TableException { String METHOD_NAME = "update"; boolean res = false; try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("group", item.toStringData()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); if (result != null) { res = (Boolean)result; } } catch ( Exception e) { e.printStackTrace(); } return res; } }
Java
CL
0590b4b0a0958573bbe78847221a19c82eac8b8f3de1a508c7524a8201c600e2
/* * 作者:钟勋 (e-mail:zhongxunking@163.com) */ /* * 修订记录: * @author 钟勋 2017-09-20 11:29 创建 */ package org.antframework.configcenter.web.manager.facade.api; import org.antframework.common.util.facade.EmptyResult; import org.antframework.configcenter.web.manager.facade.order.*; import org.antframework.configcenter.web.manager.facade.result.FindManagerAppResult; import org.antframework.configcenter.web.manager.facade.result.QueryManagedAppResult; import org.antframework.configcenter.web.manager.facade.result.QueryManagerAppResult; /** * 管理员关联应用管理服务 */ public interface ManagerAppManageService { /** * 添加管理员与应用关联 */ EmptyResult addManagerApp(AddManagerAppOrder order); /** * 删除管理员与应用关联 */ EmptyResult deleteManagerApp(DeleteManagerAppOrder order); /** * 删除所有管理员与指定应用的关联 */ EmptyResult deleteManagerAppByApp(DeleteManagerAppByAppOrder order); /** * 查找管理员与应用关联 */ FindManagerAppResult findManagerApp(FindManagerAppOrder order); /** * 查询被管理员管理的应用 */ QueryManagedAppResult queryManagedApp(QueryManagedAppOrder order); /** * 查询管理员和应用关联 */ QueryManagerAppResult queryManagerApp(QueryManagerAppOrder order); }
Java
CL
25c56211742dbffe5e5d9bb5a6f089abcac7366f295d1bc4eddaafb6adbe88aa
package com.rfb.repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; /** * Created by jt on 10/21/17. */ abstract class AbstractRepositoryTest { @Autowired RfbLocationRepository rfbLocationRepository; @Autowired RfbEventRepository rfbEventRepository; @Autowired RfbEventAttendanceRepository rfbEventAttendanceRepository; @Autowired UserRepository userRepository; @Autowired PasswordEncoder passwordEncoder; @Autowired AuthorityRepository authorityRepository; }
Java
CL
f70d2124871a5bf03d198e084bafdf4154efdb809b4e50f8f9dfb802dc2b17cc
package symtable; import java.util.*; import ast.node.*; import exceptions.InternalException; /** * SymTable * .... * The symbol table also keeps a mapping of expression nodes to * types because that information is needed elsewhere especially * when looking up method call information. * * @author mstrout * WB: Simplified to only expression types */ public class SymTable { private final HashMap<Node,Type> mExpType = new HashMap<Node,Type>(); private Scope mGlobalScope; private Stack<Scope> mScopeStack; public static final int maxParamNum = 12; // 12 formal parameters at most public static final String classVarBase = "Z"; // for future use public static final String methodVarBase = "Y"; // for future use public SymTable() { mGlobalScope = new Scope("global", Scope.globalScope); // Global Scope don't need name, maybe? mScopeStack = new Stack<>(); mScopeStack.push(mGlobalScope); } public void setExpType(Node exp, Type t) { if (t == null) { System.err.println("Cannot set type to null"); } this.mExpType.put(exp, t); } public Type getExpType(Node exp) { return this.mExpType.get(exp); } public HashMap<Node, Type> getMap() { return mExpType; } /* */ /** * Lookup a symbol in this symbol table. * Starts looking in innermost scope and then * look in enclosing scopes. * Returns null if the symbol is not found. */ public STE lookup (String sym) { Stack<Scope> copy = (Stack<Scope>)mScopeStack.clone(); STE result = null; while (!copy.empty()) { Scope scope = copy.pop(); result = scope.lookup(sym); if (result != null) { return result; } } return null; } /*public STE lookupOther(String sym, String classScope) { Stack<Scope> copy = (Stack<Scope>)mScopeStack.clone(); STE result = null; while (!copy.empty()) { Scope scope = copy.pop(); result = scope.lookup(sym); //if (sym.equals("PA4noDef")) //System.out.println(result.getClass().getName()); //STE STEtest = scope.lookup() if (result != null) { if ( ("var").equals(classScope) && result instanceof VarSTE) { System.out.println(result.getClass().getName()); return result; } else if ( ("method").equals(classScope) && result instanceof MethodSTE) { System.out.println(result.getClass().getName()); return result; } else if ( ("class").equals(classScope) && result instanceof ClassSTE) { return result; } } } return null; }*/ public STE lookupOther(String sym, String typesOfSTE) { Stack<Scope> copy = (Stack<Scope>)mScopeStack.clone(); STE result = null; while (!copy.empty()) { Scope scope = copy.pop(); result = scope.lookup(sym); if (result != null ) { if (typesOfSTE.equals("var") && result instanceof VarSTE) { return result; } else if (typesOfSTE.equals("method") && result instanceof MethodSTE) { return result; } else if (typesOfSTE.equals("class") && result instanceof ClassSTE) { return result; } } } return null; } /** * When inserting an STE will just insert * it into the scope at the top of the scope stack. */ public boolean insert(STE ste) { Scope currentScope = mScopeStack.peek(); return currentScope.insert(ste); } /** * Lookup a symbol in innermost scope only. * return null if the symbol is not found */ public STE lookupInnermost(String sym) { Scope currentScope = mScopeStack.peek(); return currentScope.lookup(sym); } public String getInnermostClassName() { Stack<Scope> copy = (Stack<Scope>)mScopeStack.clone(); while (!copy.empty()) { Scope currentScope = copy.pop(); if (currentScope.getScopeType() == Scope.classScope) { return currentScope.getName(); } } return null; } /** * Lookup the given method scope and make it the innermost * scope. That is, make it the top of the scope stack. */ public void pushScope(Scope scope) { mScopeStack.push(scope); } public void popScope() { mScopeStack.pop(); } public Scope getCurrentScope() { return mScopeStack.peek(); } public Scope getGlobalScope() { return mGlobalScope; } public String genMethodName(String methodName) { return mScopeStack.peek().getName() + "_" + methodName; } }
Java
CL
eb4b415a53743b34cfb530a237c624a7d7cae1cb44483e7237a886c70ea80909
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.fabric.integration.rei; import me.shedaniel.math.FloatingPoint; import me.shedaniel.math.Point; import me.shedaniel.math.Rectangle; import me.shedaniel.rei.api.client.gui.Renderer; import me.shedaniel.rei.api.client.gui.widgets.Widget; import me.shedaniel.rei.api.client.gui.widgets.Widgets; import me.shedaniel.rei.api.client.registry.display.DisplayCategory; import me.shedaniel.rei.api.common.category.CategoryIdentifier; import me.shedaniel.rei.api.common.entry.EntryIngredient; import me.shedaniel.rei.api.common.entry.EntryStack; import me.shedaniel.rei.api.common.util.EntryStacks; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.NotNull; import vazkii.botania.common.block.BotaniaBlocks; import vazkii.botania.common.lib.ResourceLocationHelper; import java.util.ArrayList; import java.util.List; public class PetalApothecaryREICategory implements DisplayCategory<PetalApothecaryREIDisplay> { private final EntryStack<ItemStack> apothecary = EntryStacks.of(new ItemStack(BotaniaBlocks.defaultAltar)); private final ResourceLocation PETAL_OVERLAY = ResourceLocationHelper.prefix("textures/gui/petal_overlay.png"); @Override public @NotNull CategoryIdentifier<PetalApothecaryREIDisplay> getCategoryIdentifier() { return BotaniaREICategoryIdentifiers.PETAL_APOTHECARY; } @Override public @NotNull Renderer getIcon() { return this.apothecary; } @Override public @NotNull Component getTitle() { return Component.translatable("botania.nei.petalApothecary"); } @Override public @NotNull List<Widget> setupDisplay(PetalApothecaryREIDisplay display, Rectangle bounds) { List<Widget> widgets = new ArrayList<>(); List<EntryIngredient> inputs = display.getInputEntries(); EntryStack<?> output = display.getOutputEntries().get(0).get(0); double angleBetweenEach = 360.0 / inputs.size(); FloatingPoint point = new FloatingPoint(bounds.getCenterX() - 8, bounds.getCenterY() - 34); Point center = new Point(bounds.getCenterX() - 8, bounds.getCenterY() - 2); widgets.add(Widgets.createRecipeBase(bounds)); widgets.add(Widgets.createDrawableWidget(((gui, mouseX, mouseY, delta) -> CategoryUtils.drawOverlay(gui, PETAL_OVERLAY, center.x - 24, center.y - 42, 42, 11, 85, 82)))); for (EntryIngredient o : inputs) { widgets.add(Widgets.createSlot(point.getLocation()).entries(o).disableBackground()); point = CategoryUtils.rotatePointAbout(point, center, angleBetweenEach); } widgets.add(Widgets.createSlot(center).entry(this.apothecary).disableBackground()); widgets.add(Widgets.createSlot(new Point(center.x + 38, center.y - 35)).entry(output).disableBackground()); return widgets; } @Override public int getDisplayHeight() { return 107; } }
Java
CL
91025734f0c350fb6adbf7c3f529985063504493db05c38465c25156d47d7aaa
package com.example.soundoffear.capstoneorderingapp; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import com.example.soundoffear.capstoneorderingapp.databases.FavoritesDatabase; import com.example.soundoffear.capstoneorderingapp.fragments.CouponsAndPromosFragment; import com.example.soundoffear.capstoneorderingapp.fragments.DeliveryAddressEntryFragment; import com.example.soundoffear.capstoneorderingapp.fragments.FavoritesFragment; import com.example.soundoffear.capstoneorderingapp.fragments.MainPageFragment; import com.example.soundoffear.capstoneorderingapp.fragments.OrderHistoryFragment; import com.example.soundoffear.capstoneorderingapp.fragments.OrderStatusFragment; import com.example.soundoffear.capstoneorderingapp.fragments.RedeemRewardsFragment; import com.example.soundoffear.capstoneorderingapp.fragments.SettingsFragment; import com.example.soundoffear.capstoneorderingapp.fragments.UserDataOutputFragment; import com.example.soundoffear.capstoneorderingapp.models.FinalSandwichModel; import com.example.soundoffear.capstoneorderingapp.models.UserDataModel; import com.example.soundoffear.capstoneorderingapp.utilities.Constants; import com.example.soundoffear.capstoneorderingapp.widget.FavoritesWidget; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.Map; public class MainActivity extends AppCompatActivity { public static final String USER_DATA_BUNDLE = "user_data_bundle"; public static final String DATA_FAV = "start_fav_fragment"; public static final String SAVING_FRAGMENT = "saving_fragment_state"; private DrawerLayout drawerLayout; private NavigationView navigationView; private String intentString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); android.support.v7.widget.Toolbar toolbar = findViewById(R.id.main_toolbar); setSupportActionBar(toolbar); final ActionBar actionBar = getSupportActionBar(); assert actionBar != null; actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_menu); drawerLayout = findViewById(R.id.nav_drawer_layout); Log.d("TEST TEST TEST", "==============================================="); FavoritesDatabase favoritesDatabase = new FavoritesDatabase(getApplicationContext()); favoritesDatabase.deleteAll(); if(FavoritesFragment.isAddingFav) { FavoritesFragment.isAddingFav = false; } else { updateFavorites(); } FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if(savedInstanceState != null) { Fragment mFragment = fragmentManager.getFragment(savedInstanceState, SAVING_FRAGMENT); getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, mFragment).commit(); } else { Intent intent = getIntent(); if (intent != null) { intentString = intent.getStringExtra(DATA_FAV); if (!TextUtils.isEmpty(intentString)) { if (intentString.equals(Constants.DATABASE_FAVORITES)) { fragmentTransaction.add(R.id.main_frameLayout, new FavoritesFragment()); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } else { fragmentTransaction.add(R.id.main_frameLayout, new MainPageFragment()); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } } navigationView = findViewById(R.id.main_navigationView); setSelectedNavDrawerItem(R.id.main_screen); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { item.setChecked(true); drawerLayout.closeDrawers(); switch (item.getItemId()) { case R.id.main_screen: getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new MainPageFragment()).addToBackStack(null).commit(); actionBar.setTitle("New Order"); break; case R.id.coupons_and_promo: getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new CouponsAndPromosFragment()).addToBackStack(null).commit(); actionBar.setTitle("Coupons and Promo"); break; case R.id.order_history: getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new OrderHistoryFragment()).addToBackStack(null).commit(); actionBar.setTitle("Order History"); break; case R.id.favorites: getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new FavoritesFragment()).addToBackStack(null).commit(); actionBar.setTitle("Favorites"); break; case R.id.redeem_rewards: getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new RedeemRewardsFragment()).addToBackStack(null).commit(); actionBar.setTitle("Redeem Rewards"); break; case R.id.order_status: getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new OrderStatusFragment()).addToBackStack(null).commit(); actionBar.setTitle("Order Status"); break; case R.id.delivery_address: FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); assert firebaseUser != null; final String userID = firebaseUser.getUid(); actionBar.setTitle("User Data"); DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.DATABASE_USERS).child(userID).child("user_data"); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { Map<String, Object> userData = (Map<String, Object>) dataSnapshot.getValue(); UserDataModel userDataModel; if (String.valueOf(userData.get("userAddressStreet2")).equals("null")) { userDataModel = new UserDataModel(userData.get("userName").toString(), userData.get("userSurname").toString(), userData.get("userPhone").toString(), userData.get("userEmail").toString(), userData.get("userAddressStreet").toString(), userData.get("userAddressNumber").toString(), userData.get("userAddressCity").toString()); } else { userDataModel = new UserDataModel(userData.get("userName").toString(), userData.get("userSurname").toString(), userData.get("userPhone").toString(), userData.get("userEmail").toString(), userData.get("userAddressStreet").toString(), userData.get("userAddressNumber").toString(), userData.get("userAddressCity").toString(), userData.get("userAddressStreet2").toString(), userData.get("userAddressNumber2").toString(), userData.get("userAddressCity2").toString()); } Bundle userBundle = new Bundle(); userBundle.putParcelable(USER_DATA_BUNDLE, userDataModel); UserDataOutputFragment userDataOutputFragment = new UserDataOutputFragment(); userDataOutputFragment.setArguments(userBundle); getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, userDataOutputFragment).addToBackStack(null).commit(); } else { getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new DeliveryAddressEntryFragment()).addToBackStack(null).commit(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); break; case R.id.settings: getSupportFragmentManager().beginTransaction().replace(R.id.main_frameLayout, new SettingsFragment()).addToBackStack(null).commit(); actionBar.setTitle("Settings"); break; } return true; } }); fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { Fragment f = getSupportFragmentManager().findFragmentById(R.id.main_frameLayout); if (f instanceof MainPageFragment) { setSelectedNavDrawerItem(R.id.main_screen); } else if (f instanceof CouponsAndPromosFragment) { setSelectedNavDrawerItem(R.id.coupons_and_promo); } else if (f instanceof OrderHistoryFragment) { setSelectedNavDrawerItem(R.id.order_history); } else if (f instanceof FavoritesFragment) { setSelectedNavDrawerItem(R.id.favorites); } else if (f instanceof RedeemRewardsFragment) { setSelectedNavDrawerItem(R.id.redeem_rewards); } else if (f instanceof OrderStatusFragment) { setSelectedNavDrawerItem(R.id.order_status); } else if (f instanceof DeliveryAddressEntryFragment) { setSelectedNavDrawerItem(R.id.delivery_address); } else if (f instanceof SettingsFragment) { setSelectedNavDrawerItem(R.id.settings); } } }); } // method to update favorites widget in order to make sure latest data is being loaded private void updateFavorites() { Log.d("Update DB", "update database" + ";;;;;;4;;4;4;4;4;;42;34;23;2;35;23;;23;tw;;f;sg;w;egw;"); final FavoritesDatabase favoritesDatabase = new FavoritesDatabase(getApplicationContext()); String userID = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.DATABASE_USERS).child(userID).child(Constants.DATABASE_FAVORITES); databaseReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.getValue() != null) { Map<String, Object> favMap = (Map<String, Object>) dataSnapshot.getValue(); for(Map.Entry<String, Object> favData: favMap.entrySet()) { Log.d("KEY ???", favData.getKey()); Map<String, Object> finalSandwichModel = (Map<String, Object>) favData.getValue(); favoritesDatabase.insertToFavoritesDB(finalSandwichModel.get("sandwich").toString()); Log.d("Instert to DB", "inserting to DB: " + finalSandwichModel.get("sandwich").toString()); } updateWidget(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); updateWidget(); } private void updateWidget() { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext()); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, FavoritesWidget.class)); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.appwidget_listView); } void setSelectedNavDrawerItem(int id) { navigationView.setCheckedItem(id); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { drawerLayout.openDrawer(Gravity.START); return true; } } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Fragment lastOpenFragment = getSupportFragmentManager().findFragmentById(R.id.main_frameLayout); getSupportFragmentManager().putFragment(outState, SAVING_FRAGMENT, lastOpenFragment); } }
Java
CL
4e30029666da5655350412e6cb489c1e61a3e78d7804cdc55661d7e63d9078b3
// *************************************************************************************************************************** // * 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.juneau.cp; import static org.apache.juneau.common.internal.ArgUtils.*; import static org.apache.juneau.internal.CollectionUtils.*; import java.util.*; /** * A list of default implementation classes. * * <h5 class='section'>Notes:</h5><ul> * <li class='warn'>This class is not thread safe. * </ul> * * <h5 class='section'>See Also:</h5><ul> * </ul> */ public class DefaultClassList { //----------------------------------------------------------------------------------------------------------------- // Static //----------------------------------------------------------------------------------------------------------------- /** * Static creator. * * @return A new object. */ public static DefaultClassList create() { return new DefaultClassList(); } /** * Static creator. * * @param values Initial entries in this list. * @return A new object initialized with the specified values. */ public static DefaultClassList of(Class<?>...values) { return new DefaultClassList().add(values); } //----------------------------------------------------------------------------------------------------------------- // Instance //----------------------------------------------------------------------------------------------------------------- private final List<Class<?>> entries; /** * Constructor. */ protected DefaultClassList() { entries = list(); } /** * Copy constructor * * @param value The object to copy. */ public DefaultClassList(DefaultClassList value) { entries = copyOf(value.entries); } /** * Prepends the specified values to the beginning of this list. * * @param values The values to prepend to this list. * @return This object. */ public DefaultClassList add(Class<?>...values) { prependAll(entries, values); return this; } /** * Returns the first class in this list which is a subclass of (or same as) the specified type. * * @param <T> The parent type. * @param type The parent type to check for. * @return The first class in this list which is a subclass of the specified type. */ @SuppressWarnings("unchecked") public <T> Optional<Class<? extends T>> get(Class<T> type) { assertArgNotNull("type", type); for (Class<?> e : entries) if (e != null && type.isAssignableFrom(e)) return optional((Class<? extends T>)e); return empty(); } /** * Creates a copy of this list. * * @return A copy of this list. */ public DefaultClassList copy() { return new DefaultClassList(this); } }
Java
CL
612d9e1e6511be6b934dad24d64a576e85433823d64d0ddda38accad6788d631
package com.usher.diboson; import android.app.Activity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.Button; import android.widget.EditText; public class LocationActionsActivity extends Activity { // ============================================================================= EditText actions; EditText altitude; EditText latitude; LocationActions locationActions; int locationActionsIndex; EditText longitude; EditText marker; // ============================================================================= @Override protected void onCreate (Bundle savedInstanceState) { // ------------------------------------------------------------------------- super.onCreate (savedInstanceState); // ------------------------------------------------------------------------- Utilities.SetUpActivity (this,StaticData.ACTIVITY_FULL_SCREEN); // ------------------------------------------------------------------------- setContentView (R.layout.location_marker_edit); // ------------------------------------------------------------------------- Bundle extras = getIntent().getExtras(); if (extras != null) { // ----------------------------------------------------------------- // 06/07/2019 ECU check for activity restart // ----------------------------------------------------------------- locationActionsIndex = extras.getInt(StaticData.PARAMETER_DATA,StaticData.NOT_SET); // ----------------------------------------------------------------- } // ------------------------------------------------------------------------- actions = (EditText) findViewById (R.id.input_actions); altitude = (EditText) findViewById (R.id.input_altitude); latitude = (EditText) findViewById (R.id.input_latitude); longitude = (EditText) findViewById (R.id.input_longitude); marker = (EditText) findViewById (R.id.input_location_marker); // ------------------------------------------------------------------------- // 16/10/2020 ECU set the 'actions' field to be scrollable // ------------------------------------------------------------------------- actions.setMovementMethod (new ScrollingMovementMethod()); // ------------------------------------------------------------------------- locationActions = new LocationActions (); // ------------------------------------------------------------------------- if (locationActionsIndex != StaticData.NOT_SET) { // --------------------------------------------------------------------- locationActions = PublicData.storedData.locationActions.get (locationActionsIndex); // --------------------------------------------------------------------- actions.setText (locationActions.actions); latitude.setText (Double.toString (locationActions.latitude)); longitude.setText (Double.toString (locationActions.longitude)); marker.setText (locationActions.marker); // --------------------------------------------------------------------- } // ------------------------------------------------------------------------- ((Button) findViewById (R.id.confirm_button)).setOnClickListener (new View.OnClickListener() { // --------------------------------------------------------------------- @Override public void onClick (View view) { // ----------------------------------------------------------------- // 15/10/2020 ECU set the data from the input information // ----------------------------------------------------------------- PublicData.storedData.locationActions.set (locationActionsIndex,getScreenData ()); // ----------------------------------------------------------------- finish (); // ----------------------------------------------------------------- } // --------------------------------------------------------------------- }); // ------------------------------------------------------------------------- ((Button) findViewById (R.id.new_entry_button)).setOnClickListener (new View.OnClickListener() { // --------------------------------------------------------------------- @Override public void onClick (View view) { // ----------------------------------------------------------------- // 15/10/2020 ECU set the data from the input information // ----------------------------------------------------------------- PublicData.storedData.locationActions.add (getScreenData()); // ----------------------------------------------------------------- finish (); // ----------------------------------------------------------------- } // --------------------------------------------------------------------- }); // ------------------------------------------------------------------------- ((Button) findViewById (R.id.actions_button)).setOnClickListener (new View.OnClickListener() { // --------------------------------------------------------------------- @Override public void onClick (View view) { // ----------------------------------------------------------------- // 15/10/2020 ECU set the data from the input information // ----------------------------------------------------------------- DialogueUtilitiesNonStatic.multilineTextInput (LocationActionsActivity.this, LocationActionsActivity.this, getString (R.string.location_marker_actions_title), getString (R.string.action_command_summary), 5, locationActions.actions, Utilities.createAMethod (LocationActionsActivity.class,"LocationActionsActions",StaticData.BLANK_STRING), null, StaticData.NO_RESULT, getString (R.string.press_to_define_command)); // ----------------------------------------------------------------- } // --------------------------------------------------------------------- }); // ------------------------------------------------------------------------- } // ============================================================================= @Override protected void onDestroy () { // ------------------------------------------------------------------------- super.onDestroy(); // ------------------------------------------------------------------------- } // ============================================================================= LocationActions getScreenData () { // ------------------------------------------------------------------------- // 15/10/2020 ECU create a record from the data entered on the screen // ------------------------------------------------------------------------- return (new LocationActions ( Double.parseDouble (latitude.getText().toString()), Double.parseDouble (longitude.getText().toString()), marker.getText().toString (), actions.getText().toString () )); // ------------------------------------------------------------------------ } // ============================================================================= public void LocationActionsActions (String theActions) { // ------------------------------------------------------------------------- // 16/10/2020 ECU created to store commands that are required for the selected // selection // ------------------------------------------------------------------------- actions.setText (theActions); // ------------------------------------------------------------------------- } // ============================================================================= }
Java
CL
e28700c215b1b9bb3206cb6719405ff247fe37ced7cfe602efdd7892590d4267
package org.candango.carcara.engine; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.candango.carcara.model.database.Field; import org.candango.carcara.model.database.Table; import org.candango.carcara.util.CodeHandler; import org.candango.carcara.util.VelocityHandler; /** * * @author Flavio Garcia */ public abstract class AbstractDaoBuilder implements DaoBuilder { private String path; public String getPath() { return path; } public void setPath( String path ) { this.path = path; } public void build( DatabaseConfiguration configuration, DatabaseLoader loader ) { preparePath(); buildFactories( configuration, loader ); for( Table table : loader.getTables() ) { prepareTablePath( table ); buildDto( configuration, table ); buildDao( configuration, table ); } } protected String getTablePath( Table table ) { return getDaoPath() + "/" + table.getName(); } protected String getDaoPath() { return getPath() + "lib/dao"; } private void buildFactories( DatabaseConfiguration configuration, DatabaseLoader loader ) { String abstractDaoFileName = getDaoPath() + "/" + CodeHandler.upperCaseFirst( configuration.getIdentifier() ) + "AbstractDaoFactory.php"; File abstractDaoFile = new File( abstractDaoFileName ); try { if( !abstractDaoFile.exists() ) { abstractDaoFile.createNewFile(); } BufferedWriter out = new BufferedWriter( new FileWriter( abstractDaoFile ) ); out.write( getAbstractDaoFactoryCode( configuration, loader ) ); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } buildConcreteDaoFactory( configuration, loader ); } protected abstract void buildConcreteDaoFactory( DatabaseConfiguration configuration, DatabaseLoader loader ); private void prepareTablePath( Table table ) { File dtoDir = new File( getTablePath( table ) ); if( !dtoDir.exists() ) { dtoDir.mkdirs(); } } private void preparePath() { File dir = new File( getPath() ); if( dir.exists() ) { File libDir = new File( getDaoPath() ); if( !libDir.exists() ) { libDir.mkdirs(); } } } protected void buildDao( DatabaseConfiguration configuration, Table table ) { String daoFileName = getTablePath( table ) + "/" + getEntitySufix( configuration, table ) + "Dao.php"; File daoFile = new File( daoFileName ); try { if( !daoFile.exists() ) { daoFile.createNewFile(); } BufferedWriter out = new BufferedWriter( new FileWriter( daoFileName ) ); out.write( getDaoCode( configuration, table ) ); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } buildConcreteDao( configuration, table ); } protected abstract void buildConcreteDao( DatabaseConfiguration configuration, Table table ); protected void buildDto( DatabaseConfiguration configuration, Table table ) { String dtoFileName = getTablePath( table ) + "/" + getEntitySufix( configuration, table ) + "Dto.php"; String abstactDtoFileName = getTablePath( table ) + "/" + getEntitySufix( configuration, table ) + "AbstractDto.php"; File dtoFile = new File( dtoFileName ); File abstractDtoFile = new File( abstactDtoFileName ); try { // creating dto only it doesn't exists if( !dtoFile.exists() ) { dtoFile.createNewFile(); BufferedWriter out = new BufferedWriter( new FileWriter( dtoFile ) ); out.write( getDtoCode( configuration, table ) ); out.close(); } if( !abstractDtoFile.exists() ) { abstractDtoFile.createNewFile(); } BufferedWriter out = new BufferedWriter( new FileWriter( abstactDtoFileName ) ); out.write( getAbstractDtoCode( configuration, table ) ); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected String getAbstractDaoFactoryCode( DatabaseConfiguration configuration, DatabaseLoader loader ) { // Creating the velocity context VelocityContext context = new VelocityContext(); // adding variables to context context.put("identifier-name", CodeHandler.upperCaseFirst( configuration.getIdentifier() ) ); context.put( "tables", loader.getTables() ); String out = VelocityHandler.getTemplateString( context, "template/common/dao/abstract_dao_factory.vm" ); return out; } protected String getDaoCode( DatabaseConfiguration configuration, Table table ) { // Creating the velocity context VelocityContext context = new VelocityContext(); // adding variables to context context.put("identifier-name", CodeHandler.upperCaseFirst( configuration.getIdentifier() ) ); context.put( "table", table ); String out = VelocityHandler.getTemplateString( context, "template/common/dao/dao.vm" ); return out; } protected String getAbstractDtoCode( DatabaseConfiguration configuration, Table table ) { // Creating the velocity context VelocityContext context = new VelocityContext(); // adding variables to context context.put("identifier-name", CodeHandler.upperCaseFirst( configuration.getIdentifier() ) ); context.put( "table", table ); String out = VelocityHandler.getTemplateString( context, "template/common/dao/abstract_dto.vm" ); return out; } protected String getDtoCode( DatabaseConfiguration configuration, Table table ) { // Creating the velocity context VelocityContext context = new VelocityContext(); // adding variables to context context.put("identifier-name", CodeHandler.upperCaseFirst( configuration.getIdentifier() ) ); context.put( "table", table ); String out = VelocityHandler.getTemplateString( context, "template/common/dao/dto.vm" ); return out; } protected String getEntitySufix( DatabaseConfiguration configuration, Table table ) { return CodeHandler.getEntityName( configuration.getIdentifier() ) + CodeHandler.getEntityName( table.getName() ); } }
Java
CL
eb310aa87c93b41a1ca6559b9508a884f69450cdfe28a2d58c03708f3d97a5b2
package com.example.demo.model.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * <p> * 角色权限关联表 * </p> * * @author tsl * @since 2020-08-18 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("sys_role_permission") public class RolePermission implements Serializable { private static final long serialVersionUID=1L; /** * 编号 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 角色编号 */ @TableField("role_id") private Long roleId; /** * 权限编号 */ @TableField("permission_id") private Long permissionId; }
Java
CL
b1e164fe193c55efa50cb27865068a835b1b7b17c287f586f6f122d3321941e2
package Offer66; /** * Title:矩阵中的路径 * Description:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始 * ,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c * s a d e e * 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后, * 路径不能再次进入该格子。 * * 空间复杂度:辅助空间O(rows*cols) + 递归调用栈 * * @author rico * @created 2017年7月9日 下午12:09:59 */ public class Solution { /** * @description 尝试所有的入口,寻找与str相匹配的路径 * @author rico * @created 2017年7月9日 下午3:25:35 * @param matrix * 矩阵 * @param rows * 矩阵行数 * @param cols * 矩阵列数 * @param str * 待匹配路径 */ public boolean hasPath(char[] matrix, int rows, int cols, char[] str) { if (matrix == null || matrix.length == 0 || str == null || str.length == 0) { // 边界条件 return false; } else { boolean result = false; int index = 0; char target = str[index]; // 搜寻并尝试从所有入口位置开始查找,直到有路径与str匹配或没有对应的入口可以使路径与str匹配 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i * cols + j] == target) { // 入口处 boolean[] flag = new boolean[matrix.length]; result = hasPathCore(matrix, rows, cols, i, j, str, index, flag); if (result) { // 若成功,则直接返回;否则,从下一个入口处尝试 return result; } } } } return result; } } /** * @description 递归算法,穷举思路 * @author rico * @created 2017年7月9日 下午3:24:06 * @param matrix * 给定矩阵 * @param rows * 矩阵行数 * @param cols * 矩阵列数 * @param i * 当前所在行数 * @param j * 当前所在列数 * @param str * 目标串 * @param index * 当前字符的位置 * @param flag * 记录格子是否被经过 */ public boolean hasPathCore(char[] matrix, int rows, int cols, int i, int j, char[] str, int index, boolean[] flag) { if (index == str.length - 1) { return true; } else { boolean result = false; int k = i; int m = j; System.out.println("K : " + k + ", M : " + m); System.out.println("index : " + index); flag[k * cols + m] = true; // 穷举四种可能 boolean r1 = false; boolean r2 = false; boolean r3 = false; boolean r4 = false; // 向右 if (m + 1 < cols && !flag[k * cols + m + 1] && str[index + 1] == matrix[k * cols + m + 1]) { flag[k * cols + m + 1] = true; r1 = hasPathCore(matrix, rows, cols, i, j + 1, str, index + 1, flag); } // 向下 if (k + 1 < rows && !flag[k * cols + m + cols] && str[index + 1] == matrix[k * cols + m + cols]) { flag[k * cols + m + cols] = true; r2 = hasPathCore(matrix, rows, cols, i + 1, j, str, index + 1, flag); } // 向左 if (m - 1 >= 0 && !flag[k * cols + m - 1] && str[index + 1] == matrix[k * cols + m - 1]) { flag[k * cols + m - 1] = true; r3 = hasPathCore(matrix, rows, cols, i, j - 1, str, index + 1, flag); } // 向上 if (k - 1 >= 0 && !flag[k * cols + m - cols] && str[index + 1] == matrix[k * cols + m - cols]) { flag[k * cols + m - cols] = true; r4 = hasPathCore(matrix, rows, cols, i - 1, j, str, index + 1, flag); } result = r1 || r2 || r3 || r4; // 穷举 if (!result) { --index; flag[k * cols + m] = false; } return result; } } public static void main(String[] args) { Solution s = new Solution(); // char[] matrix = { 'A', 'B', 'C', 'E', 'H', 'J', 'I', 'G', 'S', 'F', // 'C', 'S', 'L', 'O', 'P', 'Q', 'A', 'D', 'E', 'E', 'M', 'N', // 'O', 'E', 'A', 'D', 'I', 'D', 'E', 'J', 'F', 'M', 'V', 'C', // 'E', 'I', 'F', 'G', 'G', 'S' }; char[] matrix = { 'A', 'B', 'D', 'B', 'C', 'O' }; int rows = 2; int cols = 3; // char[] str = { 'S', 'G', 'G', 'F', 'I', 'E', 'C', 'V', 'A', 'A', 'S', // 'A', 'B', 'C', 'E', 'H', 'J', 'I', 'G', 'Q', 'E', 'M' }; char[] str = { 'A', 'B', 'C', 'B', 'D' }; System.out.println(s.hasPath(matrix, rows, cols, str)); } }
Java
CL
7900d5906e48ce8b88c725c15f35da6b1be1ad47c5c55b011f075bb6bd26cce8
/** Joe Canero. CSC 230. Project 2 3/30/12 This class handles the functionality of the Message objects. It stores all relevant data. Important headers receive their own reference while those less integral to the program are placed into a LinkedSet. This class also includes getters, methods for checking if the message is cross posted, if the message contains a certain word, if the message is equal to another message, and a message that returns a String representation. */ import javafoundations.*; public class Message implements Comparable<Message> { private String Newsg; private String From; private String Subject; private String Date; private String Message; private LinkedSet<String> set; public Message (String Newsg, String From, String Subject, String Date, String Message, LinkedSet<String> set) { this.Newsg = Newsg; this.From = From; this.Subject = Subject; this.Date = Date; this.Message = Message; this.set = set; } public String getMessage () { return Message; } public String getFrom () { return From; } public String getDate () { return Date; } public String getSubject () { return Subject; } public boolean foundInMessage (String str) { boolean found = false; if(Message.toLowerCase().contains(str)) found = true; return found; } public boolean checkPost () { boolean crossPost; if(Newsg.contains(",")) crossPost = true; else crossPost = false; return crossPost; } public int compareTo(Message object) { int compareResult = 1; String date = object.getDate(); String from = object.getFrom(); String subject = object.getSubject(); if((this.getMessage()).compareTo (date) == 0) { if((this.getMessage()).compareTo (subject) < 0) { if((this.getMessage()).compareTo (from) > 0) compareResult = 0; } } else compareResult = 1; return compareResult; } public String toString () { //Prints a summary of the Message Object String information = From + "\n" + Subject + "\n" + Date; information += "\n------------------------\n"; return information; } }
Java
CL
5cb2351ef9e1dca0b6eab91559cdf35cfc054851b6e162bedd82fcc52a69abb0
package com.microwise.orion.dao; import com.microwise.common.sys.hibernate.BaseDao; import com.microwise.orion.bean.OutEvent; import com.microwise.orion.vo.OutEventVo; import com.microwise.orion.vo.RelicVo; import java.util.Date; import java.util.List; /** * 出库记录 dao * * @author xubaoji * @date 2013-5-29 */ public interface OutEventDao extends BaseDao<OutEvent> { /** * 出库申请表填写 * * @param outEvent 出库事件记录(出库单) 实体 */ public void saveOutEventInfo(OutEvent outEvent); /** * 根据站点编号查询出库事件 * * @param siteId 站点编号 * @param start 分页开始位置 * @param size 分页每页条数 * @return 站点编号查询出库事件 */ public List<OutEvent> findOutEventsBySiteId(String siteId, int start, int size); /** * 根据id查询出库事件编号 * * @param id 出库事件编号 * @return */ public OutEvent findById(String id); /** * 根据站点编号查询出库事件条数 * * @param siteId 站点编号 * @return */ public int findOutEventCountBySiteId(String siteId); /** * 查询指定时间范围内的外出借展事件 * * @param siteId 站点ID * @param begin 开始日期 * @param end 结束日期 * @return */ List<OutEvent> findExhibitions(String siteId, Date begin, Date end); /** * 修改出库事件 * * @param outEvent 出库事件 */ public void updateOutEvent(OutEvent outEvent); /** * 根据出库单编号列表 查询出库单 信息(不带有出库单文物信息) * * @param eventIds 出库单号列表 * @return * @author 许保吉 * @date 2013-5-31 */ public List<OutEventVo> findOutEventVo(List<String> eventIds); /** * 根据出库单 号 查询出库单文物信息 * * @param eventId 出库单号 * @return * @author 许保吉 * @date 2013-5-31 */ public List<RelicVo> findOutEventRelicVo(String eventId); /** * 根据出库单状态查询对应出库单 * * @param siteId * @param state * @return */ List<OutEventVo> findOutEventVoByState(String siteId, int state); }
Java
CL
2b06f5d661773aafb2b4ec7cf26f824f568383dce1aaf552aaf8b5bc888b2b76
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.snapchat.android.fragments.addfriends; import Jo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.snapchat.android.LeftSwipeViewPager; import com.snapchat.android.util.debug.ReleaseManager; import com.snapchat.android.util.fragment.SnapchatFragment; import kw; // Referenced classes of package com.snapchat.android.fragments.addfriends: // LeftSwipeContentFragment public class LeftSwipeContainerFragment extends SnapchatFragment { static interface a { public abstract void K(); } public LeftSwipeViewPager a; private LeftSwipeContentFragment b; private Bundle c; private kw d; public LeftSwipeContainerFragment() { } public static LeftSwipeContainerFragment a(LeftSwipeContentFragment leftswipecontentfragment, Bundle bundle) { LeftSwipeContainerFragment leftswipecontainerfragment = new LeftSwipeContainerFragment(); Bundle bundle1 = new Bundle(); bundle1.putSerializable("content_fragment", leftswipecontentfragment); if (bundle != null) { bundle1.putBundle("content_fragment_arguments", bundle); } leftswipecontainerfragment.setArguments(bundle1); return leftswipecontainerfragment; } static kw a(LeftSwipeContainerFragment leftswipecontainerfragment) { return leftswipecontainerfragment.d; } static View b(LeftSwipeContainerFragment leftswipecontainerfragment) { return leftswipecontainerfragment.mFragmentLayout; } protected final com.snapchat.android.ui.window.WindowConfiguration.StatusBarDrawMode b() { return com.snapchat.android.ui.window.WindowConfiguration.StatusBarDrawMode.DRAW_BEHIND; } public final SnapchatFragment h() { return (SnapchatFragment)d.a; } public void onCreate(Bundle bundle) { super.onCreate(bundle); bundle = getArguments(); if (bundle != null) { b = (LeftSwipeContentFragment)bundle.getSerializable("content_fragment"); c = bundle.getBundle("content_fragment_arguments"); } if (ReleaseManager.f() && b == null) { throw new IllegalArgumentException("Cannot create LeftSwipeContainerFragment with null ContentFragment!"); } else { return; } } public View onCreateView(LayoutInflater layoutinflater, ViewGroup viewgroup, Bundle bundle) { mFragmentLayout = layoutinflater.inflate(0x7f040093, viewgroup, false); a = (LeftSwipeViewPager)d(0x7f0d031c); d = new kw(getChildFragmentManager(), b, c); a.setAdapter(d); a.setCurrentItem(1); a.setOnPageChangeListener(new android.support.v4.view.ViewPager.e() { private LeftSwipeContainerFragment a; public final void a(int i) { } public final void a(int i, float f, int j) { android.support.v4.app.Fragment fragment = LeftSwipeContainerFragment.a(a).a; if (i == 0 && f <= 0.05F) { Jo.a(a.getActivity(), LeftSwipeContainerFragment.b(a)); a.getActivity().onBackPressed(); if (fragment instanceof a) { ((a)fragment).K(); } } } public final void b(int i) { } { a = LeftSwipeContainerFragment.this; super(); } }); return mFragmentLayout; } protected void onVisible() { super.onVisible(); j(false); SnapchatFragment snapchatfragment = h(); if (snapchatfragment != null) { snapchatfragment.j(true); } a.setLeftSwipeEnable(true); } }
Java
CL
efc7e9b615acc43a75916293e5089f6c26d3a1214e878bf5f77b05689bde73c8
package cn.edu.nju.swan.monitor; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.Vector; import cn.edu.nju.swan.cfg.ControlFlowGraph; import cn.edu.nju.swan.cfg.MD5; import cn.edu.nju.swan.cfg.UnitNode; import cn.edu.nju.swan.model.SwanEvent; import edu.hkust.leap.tracer.TraceReader; public class SwanControl { public static Vector<SwanEvent> trace; public static final Object G = new Object(); public static void control(long curTid, String stmtSig) { if (trace.isEmpty()) return; SwanEvent e = trace.firstElement(); int counter = 0; while (curTid != e.ti) { int originalRecordSize = trace.size(); synchronized (G) { try { G.wait(50); } catch (InterruptedException e1) { e1.printStackTrace(); } } // after wait if trace is empty, return if (trace.isEmpty()) { return; } // a naive implementation, after waiting, if the record size is not // changed, a block is detected; // then remove the first element. FIXME if (originalRecordSize == trace.size()) { if (counter < 5) { counter++; } else { trace.remove(0); } } if (trace.isEmpty()) { return; } e = trace.get(0); } // if they belong to the same thread... if (stmtSig.equals(e.si)) { // if the two statements are the same. if (trace.isEmpty()) { return; } trace.remove(0); } else { // same thread but not the same statement // the head stmt in trace can be reached from curr? boolean currCanReachHeadStmt = true; // sig = method;stmt String[] currStmtSigSplit = stmtSig.split(";"); String[] headStmtSplit = e.si.split(";"); // unit node in cfg structure UnitNode toExe = null; UnitNode sdExe = null; if (currStmtSigSplit[0].equals(headStmtSplit[0])) { // in the same thread and the same method ControlFlowGraph cfg = tidcfgMap.get(curTid).peek(); toExe = cfg.getUnitNodeBySignature(currStmtSigSplit[1]); sdExe = cfg.getUnitNodeBySignature(headStmtSplit[1]); currCanReachHeadStmt = toExe.canReach(sdExe); } else { // // if in different method, here is a naive implementation // TODO } if (!currCanReachHeadStmt) { // if sdExe is not reachable, execute toExe and do remove // sdExe from record. if (trace.isEmpty()) { return; } trace.remove(0); // check whether toExe is in the record FIXME int i = 0; boolean findIt = false; for (; i < trace.size(); i++) { if (stmtSig.equals(trace.get(i))) { findIt = true; break; } } if (findIt) { while (i >= 0) { if (trace.isEmpty()) { break; } trace.remove(0); i--; } } } } } private final static Map<Long, Stack<ControlFlowGraph>> tidcfgMap = new HashMap<Long, Stack<ControlFlowGraph>>(); private final static Map<String, ControlFlowGraph> namecfgMap = new HashMap<String, ControlFlowGraph>(); public static void startMethod(String cn, String mn) { ControlFlowGraph cfg = namecfgMap.get(mn); if (cfg == null) { cfg = (ControlFlowGraph) TraceReader.readTrace("./cfgs/" + MD5.encode(cn) + "/" + MD5.encode(mn) + ".gz"); namecfgMap.put(mn, cfg); } long currentThreadId = Thread.currentThread().getId(); Stack<ControlFlowGraph> cfgStack = tidcfgMap.get(currentThreadId); if (cfgStack == null) { cfgStack = new Stack<ControlFlowGraph>(); tidcfgMap.put(currentThreadId, cfgStack); } cfgStack.push(cfg); } public static void endMethodBeforeThrow(String cn, String mn) { long currentThreadId = Thread.currentThread().getId(); tidcfgMap.get(currentThreadId).pop(); } public static void endMethodBeforeReturn(String cn, String mn) { long currentThreadId = Thread.currentThread().getId(); tidcfgMap.get(currentThreadId).pop(); } }
Java
CL
79c508720695ed15e31018c51e2531368e9b8b048e7f4169ab24429139ae3dd5
package org.ihtsdo.rvf.service; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import org.hibernate.ObjectNotFoundException; import org.ihtsdo.rvf.dao.AssertionDao; import org.ihtsdo.rvf.entity.Assertion; import org.ihtsdo.rvf.entity.AssertionGroup; import org.ihtsdo.rvf.entity.AssertionTest; import org.ihtsdo.rvf.entity.Test; import org.ihtsdo.rvf.helper.MissingEntityException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class AssertionServiceImpl extends EntityServiceImpl<Assertion> implements AssertionService { @Autowired private AssertionDao assertionDao; @Autowired private EntityService entityService; @Autowired public AssertionServiceImpl(final AssertionDao assertionDao) { super(assertionDao); } @Override public Assertion create(final Map<String, String> properties) { final Assertion assertion = new Assertion(); setProperties(assertion, properties); assertionDao.save(assertion); return assertion; } @Override public Assertion update(final Long id, final Map<String, String> newValues) { final Assertion assertion = find(id); setProperties(assertion, newValues); assertionDao.save(assertion); return assertion; } @Override public void delete(final Assertion assertion) { // first get all associated AssertionTests and delete them for(final AssertionTest assertionTest : getAssertionTests(assertion)) { entityService.delete(assertionTest); } // then delete assertion, but first merge assertion, in case it has been detached from session try { final Object merged = assertionDao.getCurrentSession().merge(assertion); assertionDao.getCurrentSession().delete(merged); } catch (ObjectNotFoundException | org.hibernate.ObjectDeletedException e) { // disappeared already due to cascade } } @Override public List<Assertion> findAll() { return assertionDao.findAll(); } @Override public Assertion find(final Long id) { final Assertion assertion = assertionDao.load(Assertion.class, id); if(assertion != null){ return assertion; } else{ throw new MissingEntityException(id); } } @Override public Collection <Assertion> find(final List<Long> ids) { final Collection <Assertion>assertionsFound = new ArrayList<Assertion>(); for (final Long id : ids) { assertionsFound.add(find(id)); } return assertionsFound; } @Override public Assertion find(final UUID uuid) { final Assertion assertion = assertionDao.findByUuid(Assertion.class, uuid); if(assertion != null){ return assertion; } else{ throw new MissingEntityException(uuid); } } // todo use beanUtils/propertyUtils reflection for each of the properties private void setProperties(final Assertion assertion, final Map<String, String> properties) { assertion.setName(properties.get("name")); assertion.setDescription(properties.get("description")); assertion.setDocLink(properties.get("docLink")); assertion.setKeywords(properties.get("keywords")); assertion.setStatement(properties.get("statement")); if(properties.get("uuid") != null ){ assertion.setUuid(UUID.fromString(properties.get("statement"))); } } @Override public List<AssertionTest> getAssertionTests(final Assertion assertion){ return assertionDao.getAssertionTests(assertion); } @Override public List<AssertionTest> getAssertionTests(final Long assertionId){ return assertionDao.getAssertionTests(assertionId); } @Override public List<AssertionTest> getAssertionTests(final UUID uuid){ return assertionDao.getAssertionTests(uuid); } @Override public List<Test> getTests(final Assertion assertion){ return assertionDao.getTests(assertion); } @Override public List<Test> getTests(final Long assertionId){ return assertionDao.getTests(assertionId); } @Override public List<Test> getTests(final UUID uuid){ return assertionDao.getTests(uuid); } @Override public Assertion addTest(final Assertion assertion, final Test test){ // see if matching assertion test already exists AssertionTest assertionTest = assertionDao.getAssertionTests(assertion, test); if(assertionTest == null) { assertionTest = new AssertionTest(); // verify if assertion has been saved - otherwise save it if(assertion.getId() == null){ assertionDao.save(assertion); } // verify if test has been saved - otherwise save first if(test.getId() == null){ entityService.create(test); } assertionTest.setTest(test); assertionTest.setInactive(false); assertionTest.setAssertion(assertion); entityService.create(assertionTest); } else{ assertionTest.setTest(test); assertionTest.setInactive(false); assertionTest.setAssertion(assertion); entityService.update(assertionTest); } return assertion; } @Override public Assertion addTests(final Assertion assertion, final Collection<Test> tests){ for(final Test test : tests) { addTest(assertion, test); } return assertion; } @Override public Assertion deleteTest(final Assertion assertion, final Test test){ // get assertion tests for assertion final AssertionTest assertionTest = assertionDao.getAssertionTests(assertion, test); // delete assertion test if (assertionTest != null) { entityService.delete(assertionTest); } return assertion; } @Override public Assertion deleteTests(final Assertion assertion, final Collection<Test> tests){ for(final Test test : tests) { deleteTest(assertion, test); } return assertion; } @Override public Long count() { return super.count(Assertion.class); } @Override public List<AssertionGroup> getGroupsForAssertion(final Assertion assertion) { return assertionDao.getGroupsForAssertion(assertion); } @Override public List<AssertionGroup> getGroupsForAssertion(final Long assertionId) { return assertionDao.getGroupsForAssertion(assertionId); } @Override public List<Assertion> getAssertionsForGroup(final AssertionGroup group) { return assertionDao.getAssertionsForGroup(group); } @Override public List<Assertion> getAssertionsForGroup(final Long groupId) { return assertionDao.getAssertionsForGroup(groupId); } @Override public AssertionGroup addAssertionToGroup(final Assertion assertion, final AssertionGroup group){ /* see if group already exists. We get groups for assertion, instead of assertions for group since getting assertions is likely to return a large number of entites. It is likely that a group might have a large number of assertions */ final List<AssertionGroup> assertionGroups = getGroupsForAssertion(assertion); if(! assertionGroups.contains(group)) { group.getAssertions().add(assertion); assertion.getGroups().add(group); assertionDao.update(assertion); } return (AssertionGroup) entityService.update(group); } @Override public AssertionGroup removeAssertionFromGroup(final Assertion assertion, final AssertionGroup group){ /* see if group already exists. We get groups for assertion, instead of assertions for group since getting assertions is likely to return a large number of entites. It is likely that a group might have a large number of assertions */ final List<AssertionGroup> assertionGroups = getGroupsForAssertion(assertion); if(assertionGroups.contains(group)) { group.getAssertions().remove(assertion); assertion.getGroups().remove(group); assertionDao.update(assertion); } return (AssertionGroup) entityService.update(group); } @Override public List<Assertion> getResourceAssertions() { return assertionDao.getAssertionsByKeywords("resource"); } }
Java
CL
f2fe9b719f9b576a4332e12095b32d50360e0735871d378760cd22354b154c18
/* * 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.bcel.verifier.structurals; import java.util.Arrays; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import org.apache.bcel.verifier.exc.AssertionViolatedException; import org.apache.bcel.verifier.exc.StructuralCodeConstraintException; /** * This class implements an array of local variables used for symbolic JVM simulation. */ public class LocalVariables implements Cloneable { /** The Type[] containing the local variable slots. */ private final Type[] locals; /** * Creates a new LocalVariables object. * * @param localVariableCount local variable count. */ public LocalVariables(final int localVariableCount) { locals = new Type[localVariableCount]; Arrays.fill(locals, Type.UNKNOWN); } /** * Returns a deep copy of this object; i.e. the clone operates on a new local variable array. However, the Type objects * in the array are shared. */ @Override public Object clone() { final LocalVariables lvs = new LocalVariables(locals.length); System.arraycopy(this.locals, 0, lvs.locals, 0, locals.length); return lvs; } /* * Fulfills the general contract of Object.equals(). */ @Override public boolean equals(final Object o) { if (!(o instanceof LocalVariables)) { return false; } final LocalVariables lv = (LocalVariables) o; if (this.locals.length != lv.locals.length) { return false; } for (int i = 0; i < this.locals.length; i++) { if (!this.locals[i].equals(lv.locals[i])) { // System.out.println(this.locals[i]+" is not "+lv.locals[i]); return false; } } return true; } /** * Returns the type of the local variable slot index. * * @param slotIndex Slot to look up. * @return the type of the local variable slot index. */ public Type get(final int slotIndex) { return locals[slotIndex]; } /** * Returns a (correctly typed) clone of this object. This is equivalent to ((LocalVariables) this.clone()). * * @return a (correctly typed) clone of this object. */ public LocalVariables getClone() { return (LocalVariables) this.clone(); } /** * @return a hash code value for the object. */ @Override public int hashCode() { return locals.length; } /** * Replaces all occurrences of {@code uninitializedObjectType} in this local variables set with an "initialized" * ObjectType. * * @param uninitializedObjectType the object to match. */ public void initializeObject(final UninitializedObjectType uninitializedObjectType) { for (int i = 0; i < locals.length; i++) { if (locals[i] == uninitializedObjectType) { locals[i] = uninitializedObjectType.getInitialized(); } } } /** * Returns the number of local variable slots. * * @return the number of local variable slots. */ public int maxLocals() { return locals.length; } /** * Merges two local variables sets as described in the Java Virtual Machine Specification, Second Edition, section * 4.9.2, page 146. * * @param localVariable other local variable. */ public void merge(final LocalVariables localVariable) { if (this.locals.length != localVariable.locals.length) { throw new AssertionViolatedException("Merging LocalVariables of different size?!? From different methods or what?!?"); } for (int i = 0; i < locals.length; i++) { merge(localVariable, i); } } /** * Merges a single local variable. * * @see #merge(LocalVariables) */ private void merge(final LocalVariables lv, final int i) { try { // We won't accept an unitialized object if we know it was initialized; // compare vmspec2, 4.9.4, last paragraph. if (!(locals[i] instanceof UninitializedObjectType) && lv.locals[i] instanceof UninitializedObjectType) { throw new StructuralCodeConstraintException("Backwards branch with an uninitialized object in the local variables detected."); } // Even harder, what about _different_ uninitialized object types?! if (!locals[i].equals(lv.locals[i]) && locals[i] instanceof UninitializedObjectType && lv.locals[i] instanceof UninitializedObjectType) { throw new StructuralCodeConstraintException("Backwards branch with an uninitialized object in the local variables detected."); } // If we just didn't know that it was initialized, we have now learned. if (locals[i] instanceof UninitializedObjectType && !(lv.locals[i] instanceof UninitializedObjectType)) { locals[i] = ((UninitializedObjectType) locals[i]).getInitialized(); } if (locals[i] instanceof ReferenceType && lv.locals[i] instanceof ReferenceType) { if (!locals[i].equals(lv.locals[i])) { // needed in case of two UninitializedObjectType instances final Type sup = ((ReferenceType) locals[i]).getFirstCommonSuperclass((ReferenceType) lv.locals[i]); if (sup == null) { // We should have checked this in Pass2! throw new AssertionViolatedException("Could not load all the super classes of '" + locals[i] + "' and '" + lv.locals[i] + "'."); } locals[i] = sup; } } else if (!locals[i].equals(lv.locals[i])) { /* * TODO if ((locals[i] instanceof org.apache.bcel.generic.ReturnaddressType) && (lv.locals[i] instanceof * org.apache.bcel.generic.ReturnaddressType)) { //System.err.println("merging "+locals[i]+" and "+lv.locals[i]); throw * new AssertionViolatedException("Merging different ReturnAddresses: '"+locals[i]+"' and '"+lv.locals[i]+"'."); } */ locals[i] = Type.UNKNOWN; } } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } } /** * Sets a new Type for the given local variable slot. * * @param slotIndex Target slot index. * @param type Type to save at the given slot index. */ public void set(final int slotIndex, final Type type) { // TODO could be package-protected? if (type == Type.BYTE || type == Type.SHORT || type == Type.BOOLEAN || type == Type.CHAR) { throw new AssertionViolatedException("LocalVariables do not know about '" + type + "'. Use Type.INT instead."); } locals[slotIndex] = type; } /** * Returns a String representation of this object. */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < locals.length; i++) { sb.append(Integer.toString(i)); sb.append(": "); sb.append(locals[i]); sb.append("\n"); } return sb.toString(); } }
Java
CL
9af2e383f441553a683fe7f80721a93ffb92ae9c60a28256419bdc094e701b8e
/**************************************************************** * 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.james.utils; import java.io.Closeable; import java.io.IOException; import java.util.List; import org.apache.commons.net.imap.IMAPClient; import com.google.common.base.Splitter; public class IMAPMessageReader implements Closeable { private static final String INBOX = "INBOX"; private final IMAPClient imapClient; public IMAPMessageReader(String host, int port) throws IOException { imapClient = new IMAPClient(); imapClient.connect(host, port); } public void connectAndSelect(String user, String password, String mailbox) throws IOException{ imapClient.login(user, password); imapClient.select(mailbox); } public boolean userReceivedMessage(String user, String password) throws IOException { return userReceivedMessageInMailbox(user, password, INBOX); } public boolean userReceivedMessageInMailbox(String user, String password, String mailbox) throws IOException { connectAndSelect(user, password, mailbox); imapClient.fetch("1:1", "ALL"); return imapClient.getReplyString() .contains("OK FETCH completed"); } public boolean userGetNotifiedForNewMessagesWhenSelectingMailbox(String user, String password, int numOfNewMessage, String mailboxName) throws IOException { connectAndSelect(user, password, mailboxName); return imapClient.getReplyString().contains("OK [UNSEEN " + numOfNewMessage +"]"); } public boolean userDoesNotReceiveMessage(String user, String password) throws IOException { return userDoesNotReceiveMessageInMailbox(user, password, INBOX); } public boolean userDoesNotReceiveMessageInMailbox(String user, String password, String mailboxName) throws IOException { connectAndSelect(user, password, mailboxName); imapClient.fetch("1:1", "ALL"); return imapClient.getReplyString() .contains("BAD FETCH failed. Invalid messageset"); } public String readFirstMessageInInbox(String user, String password) throws IOException { return readFirstMessageInMailbox(user, password, "(BODY[])", INBOX); } public String readFirstMessageHeadersInMailbox(String user, String password, String mailboxName) throws IOException { return readFirstMessageInMailbox(user, password, "(RFC822.HEADER)", mailboxName); } public String readFirstMessageHeadersInInbox(String user, String password) throws IOException { return readFirstMessageInMailbox(user, password, "(RFC822.HEADER)", INBOX); } private String readFirstMessageInMailbox(String user, String password, String parameters, String mailboxName) throws IOException { imapClient.login(user, password); imapClient.select(mailboxName); imapClient.fetch("1:1", parameters); return imapClient.getReplyString(); } public boolean userGetNotifiedForNewMessages(int numberOfMessages) throws IOException { imapClient.noop(); String replyString = imapClient.getReplyString(); List<String> parts = Splitter.on('\n') .trimResults() .omitEmptyStrings() .splitToList(replyString); return parts.size() == 3 && parts.get(2).contains("OK NOOP completed.") && parts.contains("* " + numberOfMessages + " EXISTS") && parts.contains("* " + numberOfMessages + " RECENT"); } public boolean userGetNotifiedForDeletion(int msn) throws IOException { imapClient.noop(); String replyString = imapClient.getReplyString(); List<String> parts = Splitter.on('\n') .trimResults() .omitEmptyStrings() .splitToList(replyString); return parts.size() == 2 && parts.get(1).contains("OK NOOP completed.") && parts.contains("* " + msn + " EXPUNGE"); } @Override public void close() throws IOException { imapClient.close(); } public void copyFirstMessage(String destMailbox) throws IOException { imapClient.copy("1", destMailbox); } }
Java
CL
3770bedb0513ca2942b1d40236bf0dcdc736e572ec15009ce89f3baf8e39f406
/* * Copyright (c) 2016-2022 chronicle.software * * https://chronicle.software * * 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.openhft.chronicle.bytes.internal; import net.openhft.chronicle.bytes.*; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.Memory; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.annotation.NonNegative; import net.openhft.chronicle.core.io.*; import net.openhft.chronicle.core.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import static net.openhft.chronicle.core.util.Ints.requireNonNegative; import static net.openhft.chronicle.core.util.Longs.requireNonNegative; import static net.openhft.chronicle.core.util.ObjectUtils.requireNonNull; import static net.openhft.chronicle.core.util.StringUtils.*; import static net.openhft.chronicle.bytes.algo.OptimisedBytesStoreHash.IS_LITTLE_ENDIAN; /** * Bytes to wrap memory mapped data. * <p> * NOTE These Bytes are single Threaded as are all Bytes. */ @SuppressWarnings({"unchecked"}) public abstract class CommonMappedBytes extends MappedBytes { private final AbstractCloseable closeable = new AbstractCloseable() { @Override protected void performClose() throws ClosedIllegalStateException { CommonMappedBytes.this.performClose(); } }; protected final MappedFile mappedFile; private final boolean backingFileIsReadOnly; private final long capacity; protected long lastActualSize = 0; private boolean initReleased; // assume the mapped file is reserved already. protected CommonMappedBytes(@NotNull final MappedFile mappedFile) throws ClosedIllegalStateException { this(mappedFile, ""); } protected CommonMappedBytes(@NotNull final MappedFile mappedFile, final String name) throws ClosedIllegalStateException, ClosedIllegalStateException, ThreadingIllegalStateException { super(name); assert mappedFile != null; this.mappedFile = mappedFile; mappedFile.reserve(this); this.backingFileIsReadOnly = mappedFile.readOnly(); assert !mappedFile.isClosed(); clear(); capacity = mappedFile.capacity(); } @Override public void singleThreadedCheckReset() { super.singleThreadedCheckReset(); closeable.singleThreadedCheckReset(); } @Override public @NotNull CommonMappedBytes write(final byte[] byteArray, @NonNegative final int offset, @NonNegative final int length) throws ClosedIllegalStateException, BufferOverflowException { requireNonNull(byteArray); requireNonNegative(offset); requireNonNegative(length); throwExceptionIfClosed(); write(writePosition(), byteArray, offset, length); uncheckedWritePosition(writePosition() + Math.min(length, byteArray.length - offset)); return this; } @NotNull @Override public CommonMappedBytes write(@NotNull final RandomDataInput bytes) throws ClosedIllegalStateException, BufferOverflowException { requireNonNull(bytes); throwExceptionIfClosed(); assert bytes != this : "you should not write to yourself !"; final long remaining = bytes.readRemaining(); write(writePosition(), bytes); uncheckedWritePosition(writePosition() + remaining); return this; } @NotNull public CommonMappedBytes write(@NonNegative final long offsetInRDO, @NotNull final RandomDataInput bytes) throws BufferOverflowException, ClosedIllegalStateException { requireNonNegative(offsetInRDO); requireNonNull(bytes); throwExceptionIfClosed(); write(offsetInRDO, bytes, bytes.readPosition(), bytes.readRemaining()); return this; } @NotNull public MappedFile mappedFile() { return mappedFile; } @Override public BytesStore<Bytes<Void>, Void> copy() throws ClosedIllegalStateException { return BytesUtil.copyOf(this); } @Override public @NonNegative long capacity() { return capacity; } @Override public Bytes<Void> readLimitToCapacity() { uncheckedWritePosition(capacity); return this; } @Override public long realReadRemaining() { long limit = readLimit(); if (limit > lastActualSize) limit = Math.min(realCapacity(), limit); return limit - readPosition(); } @Override public long realWriteRemaining() { long limit = writeLimit(); if (limit > lastActualSize) limit = Math.min(realCapacity(), limit); return limit - writePosition(); } @Override public @NonNegative long realCapacity() { try { lastActualSize = mappedFile.actualSize(); return lastActualSize; } catch (Exception e) { Jvm.warn().on(getClass(), "Unable to obtain the real size for " + mappedFile.file(), e); lastActualSize = 0; return lastActualSize; } } @Nullable @Override public String read8bit() throws IORuntimeException, BufferUnderflowException, ClosedIllegalStateException, ArithmeticException { return BytesInternal.read8bit(this); } @Override public @NotNull Bytes<Void> writeSkip(long bytesToSkip) throws BufferOverflowException, ClosedIllegalStateException, ClosedIllegalStateException, ThreadingIllegalStateException { // only check up to 128 bytes are real. writeCheckOffset(writePosition(), Math.min(128, bytesToSkip)); // the rest can be lazily allocated. uncheckedWritePosition(writePosition() + bytesToSkip); return this; } @Override public @NonNegative long start() { return 0L; } @NotNull @Override public Bytes<Void> writePosition(@NonNegative final long position) throws BufferOverflowException { // throwExceptionIfClosed if (position > writeLimit) throw new BufferOverflowException(); if (position < 0L) throw new BufferOverflowException(); if (position < readPosition) this.readPosition = position; uncheckedWritePosition(position); return this; } @NotNull @Override public Bytes<Void> clear() throws ClosedIllegalStateException, ClosedIllegalStateException { // Typically, only used at the start of an operation so reject if closed. throwExceptionIfClosed(); long start = 0L; readPosition = start; uncheckedWritePosition(start); writeLimit = capacity; return this; } @Override protected void performRelease() throws ClosedIllegalStateException { super.performRelease(); mappedFile.release(this); } @Override @NotNull public Bytes<Void> write(@NotNull final RandomDataInput bytes, @NonNegative final long offset, @NonNegative final long length) throws BufferUnderflowException, BufferOverflowException, ClosedIllegalStateException, ThreadingIllegalStateException { requireNonNull(bytes); requireNonNegative(offset); requireNonNegative(length); throwExceptionIfClosed(); if (bytes instanceof BytesStore) write(bytes, offset, length); else if (length == 8) writeLong(bytes.readLong(offset)); else if (length > 0) BytesInternal.writeFully(bytes, offset, length, this); return this; } @NotNull @Override public Bytes<Void> append8bit(@NotNull CharSequence text, @NonNegative int start, @NonNegative int end) throws IllegalArgumentException, BufferOverflowException, BufferUnderflowException, IndexOutOfBoundsException, ClosedIllegalStateException, ThreadingIllegalStateException { requireNonNull(text); throwExceptionIfClosed(); // check the start. long pos = writePosition(); writeCheckOffset(pos, 0); if (!(text instanceof String) || pos + (end - start) * 3L + 5 >= safeLimit()) { return super.append8bit(text, start, end); } return append8bit0((String) text, start, end - start); } @Override @NotNull public CommonMappedBytes write8bit(@NotNull CharSequence text, @NonNegative int start, @NonNegative int length) throws ClosedIllegalStateException, BufferUnderflowException, BufferOverflowException, ArithmeticException, IndexOutOfBoundsException, ThreadingIllegalStateException { requireNonNull(text); throwExceptionIfClosed(); ObjectUtils.requireNonNull(text); // check the start. long pos = writePosition(); writeCheckOffset(pos, 0); if (!(text instanceof String) || pos + length * 3L + 5 >= safeLimit()) { super.write8bit(text, start, length); return this; } writeStopBit(length); return append8bit0((String) text, start, length); } @NotNull private CommonMappedBytes append8bit0(@NotNull String s, @NonNegative int start, @NonNegative int length) throws BufferOverflowException, ClosedIllegalStateException, ThreadingIllegalStateException { requireNonNull(s); ensureCapacity(writePosition() + length); long address = addressForWritePosition(); Memory memory = ((MappedBytesStore) bytesStore()).memory; if (Jvm.isJava9Plus()) { byte[] bytes = extractBytes(s); int i = 0; for (; i < length - 3; i += 4) { int c0 = bytes[i + start] & 0xff; int c1 = bytes[i + start + 1] & 0xff; int c2 = bytes[i + start + 2] & 0xff; int c3 = bytes[i + start + 3] & 0xff; if (IS_LITTLE_ENDIAN) { memory.writeInt(address, (c3 << 24) | (c2 << 16) | (c1 << 8) | c0); } else { memory.writeInt(address, (c0 << 24) | (c1 << 16) | (c2 << 8) | c3); } address += 4; } for (; i < length; i++) { byte c = bytes[i + start]; memory.writeByte(address++, c); } writeSkip(length); } else { char[] chars = extractChars(s); int i = 0; for (; i < length - 3; i += 4) { int c0 = chars[i + start] & 0xff; int c1 = chars[i + start + 1] & 0xff; int c2 = chars[i + start + 2] & 0xff; int c3 = chars[i + start + 3] & 0xff; if (IS_LITTLE_ENDIAN) { memory.writeInt(address, (c3 << 24) | (c2 << 16) | (c1 << 8) | c0); } else { memory.writeInt(address, (c0 << 24) | (c1 << 16) | (c2 << 8) | c3); } address += 4; } for (; i < length; i++) { char c = chars[i + start]; memory.writeByte(address++, (byte) c); } writeSkip(length); } return this; } @NotNull @Override public Bytes<Void> appendUtf8(@NotNull CharSequence cs, @NonNegative int start, @NonNegative int length) throws BufferOverflowException, ClosedIllegalStateException, BufferUnderflowException, IndexOutOfBoundsException, ThreadingIllegalStateException { requireNonNull(cs); throwExceptionIfClosed(); // check the start. long pos = writePosition(); writeCheckOffset(pos, 0); if (!(cs instanceof String) || pos + length * 3L + 5 >= safeLimit()) { super.appendUtf8(cs, start, length); return this; } if (Jvm.isJava9Plus()) { final String str = (String) cs; long address = addressForWrite(pos); Memory memory = OS.memory(); int i = 0; non_ascii: { for (; i < length; i++) { char c = str.charAt(i + start); if (c > 127) { writeSkip(i); break non_ascii; } memory.writeByte(address++, (byte) c); } writeSkip(length); return this; } for (; i < length; i++) { char c = str.charAt(i + start); appendUtf8(c); } } else { char[] chars = extractChars((String) cs); long address = addressForWrite(pos); Memory memory = OS.memory(); int i = 0; non_ascii: { for (; i < length; i++) { char c = chars[i + start]; if (c > 127) { writeSkip(i); break non_ascii; } memory.writeByte(address++, (byte) c); } writeSkip(length); return this; } for (; i < length; i++) { char c = chars[i + start]; appendUtf8(c); } } return this; } @Override public void release(ReferenceOwner id) throws ClosedIllegalStateException { try { super.release(id); } catch (ClosedIllegalStateException ignored) { // ignored } initReleased |= id == INIT; if (refCount() <= 0) closeable.close(); } @Override public void releaseLast(ReferenceOwner id) throws ClosedIllegalStateException { super.releaseLast(id); initReleased |= id == INIT; closeable.close(); } @Override public void close() { closeable.close(); } void performClose() throws ClosedIllegalStateException { if (!initReleased) release(INIT); } @Override public boolean isClosed() { return closeable.isClosed(); } @Override public void warnAndCloseIfNotClosed() { closeable.warnAndCloseIfNotClosed(); } @Override public void throwExceptionIfClosed() throws ClosedIllegalStateException, ThreadingIllegalStateException { closeable.throwExceptionIfClosed(); } @NotNull @Override public Bytes<Void> writeUtf8(@Nullable CharSequence text) throws BufferOverflowException, ClosedIllegalStateException, ThreadingIllegalStateException { throwExceptionIfClosed(); if (text instanceof String) { writeUtf8((String) text); return this; } if (text == null) { BytesInternal.writeStopBitNeg1(this); } else { long utfLength = AppendableUtil.findUtf8Length(text); this.writeStopBit(utfLength); BytesInternal.appendUtf8(this, text, 0, text.length()); } return this; } @Override public @NotNull Bytes<Void> writeUtf8(@Nullable String text) throws BufferOverflowException, ClosedIllegalStateException, ThreadingIllegalStateException { throwExceptionIfClosed(); if (text == null) { BytesInternal.writeStopBitNeg1(this); return this; } if (Jvm.isJava9Plus()) { byte[] strBytes = extractBytes(text); byte coder = getStringCoder(text); long utfLength = AppendableUtil.findUtf8Length(strBytes, coder); writeStopBit(utfLength); appendUtf8(strBytes, 0, text.length(), coder); } else { char[] chars = extractChars(text); long utfLength = AppendableUtil.findUtf8Length(chars); writeStopBit(utfLength); appendUtf8(chars, 0, chars.length); } return this; } @Override public long readStopBit() throws IORuntimeException, ClosedIllegalStateException, BufferUnderflowException { throwExceptionIfClosed(); long offset = readOffsetPositionMoved(1); byte l = bytesStore.readByte(offset); if (l >= 0) return l; return BytesInternal.readStopBit0(this, l); } @Override public char readStopBitChar() throws IORuntimeException, ClosedIllegalStateException, BufferUnderflowException { throwExceptionIfClosed(); long offset = readOffsetPositionMoved(1); byte l = bytesStore.readByte(offset); if (l >= 0) return (char) l; return (char) BytesInternal.readStopBit0(this, l); } @NotNull @Override public Bytes<Void> writeStopBit(long n) throws BufferOverflowException, ClosedIllegalStateException, ThreadingIllegalStateException { throwExceptionIfClosed(); if ((n & ~0x7F) == 0) { writeByte((byte) (n & 0x7f)); return this; } if ((~n & ~0x7F) == 0) { writeByte((byte) (0x80L | ~n)); writeByte((byte) 0); return this; } if ((n & ~0x3FFF) == 0) { writeByte((byte) ((n & 0x7f) | 0x80)); writeByte((byte) (n >> 7)); return this; } BytesInternal.writeStopBit0(this, n); return this; } @NotNull @Override public Bytes<Void> writeStopBit(char n) throws BufferOverflowException, ClosedIllegalStateException, ThreadingIllegalStateException { throwExceptionIfClosed(); if ((n & ~0x7F) == 0) { writeByte((byte) (n & 0x7f)); return this; } if ((n & ~0x3FFF) == 0) { writeByte((byte) ((n & 0x7f) | 0x80)); writeByte((byte) (n >> 7)); return this; } BytesInternal.writeStopBit0(this, n); return this; } @Override public boolean isBackingFileReadOnly() { return backingFileIsReadOnly; } @Override public boolean isDirectMemory() { return true; } @Deprecated(/* to be removed in x.25 */) public CommonMappedBytes disableThreadSafetyCheck(boolean disableThreadSafetyCheck) { singleThreadedCheckDisabled(disableThreadSafetyCheck); return this; } public void singleThreadedCheckDisabled(boolean singleThreadedCheckDisabled) { super.singleThreadedCheckDisabled(singleThreadedCheckDisabled); closeable.singleThreadedCheckDisabled(singleThreadedCheckDisabled); } @NotNull @Override public String toString() { if (!TRACE) return super.toString(); return getClass().getSimpleName() + "{" + "\n" + "refCount=" + refCount() + ",\n" + "mappedFile=" + mappedFile.file().getAbsolutePath() + ",\n" + "mappedFileRefCount=" + mappedFile.refCount() + ",\n" + "mappedFileIsClosed=" + mappedFile.isClosed() + ",\n" + "mappedFileRafIsClosed=" + Jvm.getValue(mappedFile.raf(), "closed") + ",\n" + "mappedFileRafChannelIsClosed=" + !mappedFile.raf().getChannel().isOpen() + ",\n" + "isClosed=" + isClosed() + '}'; } @Override public void chunkCount(long[] chunkCount) { mappedFile.chunkCount(chunkCount); } @Override public boolean readWrite() { return !mappedFile.readOnly(); } }
Java
CL
6664e825c4ee960209d9e66b1a551cd05b32713f8ac9fcb895b0cefdad841dba
package com.imcode.sys.mapper; import org.apache.ibatis.annotations.Param; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.imcode.sys.entity.DeptRole; import com.imcode.sys.entity.Role; /** * <p> * 角色 Mapper 接口 * </p> * * @author jack * @since 2019-11-04 */ public interface RoleMapper extends BaseMapper<Role> { /** * 自定义多表联合查询并分页 * @param page * @param state * @return */ IPage<DeptRole> selectPageVo(IPage<DeptRole> page, @Param("role") Role role); }
Java
CL
187dbb60cd7eaa4e146840d572de4d12cd29c8b2ee7cd0d0b7802be9b2a0bb7a
package com.venkat.resume.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.venkat.resume.model.AcademicDetails; import com.venkat.resume.model.Resume; import com.venkat.resume.model.WorkExperienceDetails; import com.venkat.resume.repository.ResumeRepository; import com.venkat.resume.repository.WorkExperienceDetailsRepository; @CrossOrigin(origins ="*") @RestController public class WorkExperienceDetailsController { @Autowired private ResumeRepository resumeRepository; @Autowired private WorkExperienceDetailsRepository workExperienceDetailsRepository; @PostMapping("resumes/{resumeId}/workExperienceDetails") public String addWorkExperienceDetails(@PathVariable int resumeId,@RequestBody WorkExperienceDetails workExperienceDetails) { String message=""; int id=workExperienceDetails.getId(); if(id==-1) { Resume resume=resumeRepository.getOne(resumeId); resume.getWorkExperienceDetailsList().add(workExperienceDetails); resumeRepository.save(resume); message="New Educational Details are added"; } else { workExperienceDetailsRepository.save(workExperienceDetails); message="Work Experience details are updated"; } //academicDetailsRepository.save(academicDetails); return message; } @GetMapping("resumes/{resumeId}/workExperienceDetails") public List<WorkExperienceDetails> getWorkExperienceDetailsList(@PathVariable int resumeId) { return workExperienceDetailsRepository.findByResumeId(resumeId); } @GetMapping("resumes/{resumeId}/workExperienceDetails/{workExperienceDetailsId}") public WorkExperienceDetails getWorkExperienceDetails(@PathVariable int workExperienceDetailsId) { WorkExperienceDetails workExperienceDetails = workExperienceDetailsRepository.findById(workExperienceDetailsId).get(); return workExperienceDetails; } @DeleteMapping("resumes/{resumeId}/workExperienceDetails/{workExperienceDetailsId}") public WorkExperienceDetails deleteWorkExperienceDetails(@PathVariable int workExperienceDetailsId) { WorkExperienceDetails workExperienceDetails = workExperienceDetailsRepository.findById(workExperienceDetailsId).get(); workExperienceDetailsRepository.deleteById(workExperienceDetailsId); return workExperienceDetails; } @PutMapping("resumes/{resumeId}/workExperienceDetails/{workExperienceDetailsId}") public void updateWorkExperienceDetails(@RequestBody WorkExperienceDetails workExperienceDetails) { workExperienceDetailsRepository.save(workExperienceDetails); } }
Java
CL
e25e9a938dbcf7b899cc2fd6359d707f23892cb24066605444c769bf27706a64
package com.bazaarvoice.intentexample; import java.io.File; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; /** * MainActivity.java <br> * IntentExample<br> * * <p> * A simple view that shows you the image that will be shared, and allows you to * set the caption and the story information associated with the submission.<br> * * This uses the Instagram model of uploading the photo while the user inputs * the submission info. This way the amount of time spent waiting by the user is * significantly decreased. <br> * * Two different methods of uploading are implemented. If you set uploadType to * DIALOG, the Activity will stay open and show a dialog while uploading. If you * set uploadType to NOTIFICATION, the Activity will close when the user clicks * "Submit Photo" and progress will be shown in the notification bar. * * <p> * OOM Issue:<br> * There is a known issue with running out of memory with an app that has a * large bitmap when it is rotated a few times. There are a lot of discussions * and recommendations about what to do about it on StackOverflow and other * sites. This example is not meant to show you the best practice for handling * such a situation but our recommendation is to force portrait mode (which is * what we do here) in the manifest file and to consider scaling the bitmap * down. Forcing portrait mode is not a flawless solution, though, because when * a physical keyboard is pulled out, the system will force the phone into * landscape. * * <p> * Created on 7/19/12. Copyright (c) 2012 BazaarVoice. All rights reserved. * * @author Bazaarvoice Engineering */ public class MainActivity extends Activity { private final int DIALOG = 0; private final int NOTIFICATION = 1; private int uploadType = NOTIFICATION; protected final int STORY_FIELDS = 1337; protected Button addStory; protected Button submit; private ProgressDialog dialog; private Notification notification; private NotificationManager notificationManager; /** * Called when the activity is first created. This pulls in the photo from * wherever it is being shared and sets up the UI. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = getIntent(); final Bundle extras = intent.getExtras(); String action = intent.getAction(); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // if this is from the share menu if (Intent.ACTION_SEND.equals(action)) { if (extras.containsKey(Intent.EXTRA_STREAM)) { // Get resource path from intent callee Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM); File file = new File(CameraUtils.getRealPathFromURI(uri, this)); final ImageView img = (ImageView) findViewById(R.id.imagePreview); Bitmap image; try { image = CameraUtils.getOrientedBitmap(uri, getApplicationContext(), img.getHeight(), img.getWidth()); img.setImageBitmap(image); image = null; } catch (Exception e) { Log.e(this.getClass().getName(), e.toString()); e.printStackTrace(); } /* * Go ahead and submit the photo. If the user actually clicks * submit, then we'll submit the story. */ BazaarFunctions.doPhotoSubmission(file); initializeUI(); } } } /** * Puts listeners on the "Add Story" and "Submit Photo" buttons. */ private void initializeUI() { submit = (Button) findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") public void onClick(View v) { EditText caption = (EditText) findViewById(R.id.caption); caption.setEnabled(false); BazaarFunctions.setStoryCaption(caption.getText().toString()); BazaarFunctions.setSubmissionResponse(new SubmissionResponseHandler(MainActivity.this)); BazaarFunctions.doStorySubmission(); if (uploadType == NOTIFICATION) { notification = new Notification(R.drawable.notif_icon, "Uploading photo...", System.currentTimeMillis()); PendingIntent intent = PendingIntent.getActivity( getApplicationContext(), 0, new Intent(), 0); notification.setLatestEventInfo(getApplicationContext(), "BV Photo Share", "Your photo is being uploaded.", intent); notificationManager.notify(1, notification); finish(); } else if (uploadType == DIALOG) { dialog = new ProgressDialog(MainActivity.this); dialog.setCancelable(false); dialog.setMessage("Submitting..."); dialog.show(); } } }); addStory = (Button) findViewById(R.id.addStory); addStory.setOnClickListener(new View.OnClickListener() { /* * The preferred method here is now to use DialogFragment with * FragmentManager. */ @SuppressWarnings("deprecation") @Override public void onClick(View v) { showDialog(STORY_FIELDS); addStory.setText("Edit Story"); } }); } /** * Creates our custom dialog that has the forms to input story content. */ @SuppressWarnings("deprecation") @Override protected Dialog onCreateDialog(int id) { if (id == STORY_FIELDS) { LayoutInflater factory = LayoutInflater .from(getApplicationContext()); final View textEntryView = factory.inflate( R.layout.alert_dialog_story_fields, null); return new AlertDialog.Builder(MainActivity.this) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { verifyStoryInput(textEntryView); } }).setTitle("Add a Story").setView(textEntryView) .create(); } else { return super.onCreateDialog(id); } } /** * Verifies that the story content inputed in the given View is valid and * then sets the content with the corresponding BazaarFunctions calls and * updates the UI. * * Does both client-side and server-side validation. * * @param textEntryView * the View associated with the story content submission dialog */ protected void verifyStoryInput(View textEntryView) { final EditText title = (EditText) textEntryView .findViewById(R.id.title); final EditText story = (EditText) textEntryView .findViewById(R.id.story); /* * Client-side validation */ if ("".equals(title.getText().toString())) { Toast.makeText(getApplicationContext(), "You must enter a title.", Toast.LENGTH_LONG).show(); } else if ("".equals(story.getText().toString())) { Toast.makeText(getApplicationContext(), "You must enter a story.", Toast.LENGTH_LONG).show(); } else { /* * Server-side validation */ final ProgressDialog verifyDialog = new ProgressDialog( MainActivity.this); verifyDialog.setCancelable(false); verifyDialog.setMessage("Verifying story requirements."); verifyDialog.show(); BazaarFunctions.doStoryPreview(story.getText().toString(), title .getText().toString(), new BazaarUIThreadResponse(this) { @Override public void onUiResponse(JSONObject json) { /* * Basic error checking for form errors. This does not * consider any other kinds of errors and should be more * robust. */ try { if (json.getBoolean("HasErrors")) { JSONObject formErrors = json .getJSONObject("FormErrors"); String error = formErrors.getJSONArray( "FieldErrorsOrder").getString(0); String message = formErrors .getJSONObject("FieldErrors") .getJSONObject(error).getString("Message"); Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); addStory.setEnabled(true); submit.setEnabled(false); } else { addStory.setEnabled(false); submit.setEnabled(true); BazaarFunctions.setStoryTitle(title.getText() .toString()); BazaarFunctions.setStoryText(story.getText() .toString()); } } catch (JSONException e) { Log.e("Preview Submission", "Error = " + e.getMessage() + "/n" + Log.getStackTraceString(e)); } verifyDialog.dismiss(); } }); } } @SuppressWarnings("deprecation") public void notifyError() { /* * With the NOTIFICATION method, the Activity has been closed, so we * need to alert the user through notifications. Depending on your case, * you may want the PendingIntent to take the user somewhere useful. */ if (uploadType == NOTIFICATION) { notification = new Notification(R.drawable.notif_icon, "Error in upload.", System.currentTimeMillis()); PendingIntent intent = PendingIntent.getActivity( getApplicationContext(), 0, new Intent(), 0); notification.setLatestEventInfo(getApplicationContext(), "BV Photo Share", "Your photo failed to upload. Please try again.", intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(1, notification); } /* * With the DIALOG method, we can just dismiss the dialog and alert the * user, letting them click "Submit" again. */ else if (uploadType == DIALOG) { runOnUiThread(new Runnable() { public void run() { dialog.dismiss(); Toast.makeText(getApplicationContext(), "Upload failed. Try again.", Toast.LENGTH_LONG) .show(); } }); } } /** * An implementation of OnBazaarResponse used for handling story submission. * It checks the response to see if there are errors and alerts the user of * them. If there are no errors, it closes the Activity. * */ private class SubmissionResponseHandler extends BazaarUIThreadResponse { public SubmissionResponseHandler(Activity context) { super(context); } private String TAG = "Submission response"; @SuppressWarnings("deprecation") public void onUiResponse(JSONObject json) { Log.i(TAG, json.toString()); try { if (json.getBoolean("HasErrors")) { /* * Do further error checking here but note that when this * code executes the Activity will not be active if * (uploadType == NOTIFICATION). */ notifyError(); } else { if (uploadType == DIALOG) { dialog.dismiss(); finish(); } /* * Update the notification if we are using NOTIFICATION * style, or display a new notification if we are using * DIALOG style to show the user that the photo was uploaded * when the Activity closes. */ notification = new Notification(R.drawable.notif_icon, "Photo Uploaded.", System.currentTimeMillis()); PendingIntent intent = PendingIntent.getActivity( getApplicationContext(), 0, new Intent(), 0); notification.setLatestEventInfo(getApplicationContext(), "BV Photo Share", "Your photo has been uploaded.", intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(1, notification); } } catch (JSONException e) { Log.e(TAG, "Error = " + e.getMessage() + "/n" + Log.getStackTraceString(e)); } } public void onException(String message, Throwable exception) { Log.e(TAG, "Error = " + message + "\n" + Log.getStackTraceString(exception)); notifyError(); } } }
Java
CL
5d1d9105b7f8443c6ccfaeefd0bd9ac6d2bbf547a2ae58f036b7c42bcf2b5a7d
package com.bitnationcode.topflies.repository; import com.bitnationcode.topflies.model.Fly; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface IFlyRepository extends JpaRepository<Fly, Long>, QuerydslPredicateExecutor<Fly> { /** * Uses Spring's built-in projections, returning an interface consisting of id and name columsn * @return list of row Id and name columns from the Fly repository */ List<FlyIdAndName> findAllProjectedBy(); }
Java
CL
d7fbc9f5b2605ebaf3285522cb2801caa35495ba6a6fc38155e6ae159d7a9d98
package eu.cessar.ct.core.platform.ui.events; import java.util.EventObject; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.Viewer; /** * Event for menu drop down selection triggered from the breadcrumb viewer. * * @see IMenuSelectionListener */ public class MenuSelectionEvent extends EventObject { /** * The selection. */ protected ISelection selection; /** * Creates a new event for the given source and selection. * */ public MenuSelectionEvent(final Viewer source, final ISelection selection) { super(source); Assert.isNotNull(selection); this.selection = selection; } /** * Returns the selection. */ public ISelection getSelection() { return selection; } /** * Returns the viewer that is the source of this event. */ public Viewer getViewer() { return (Viewer) getSource(); } }
Java
CL
9c7e9adb4241e87af8c5ef9f974c8992efc7569d2e4b1788664e89d0c7695fd5
package com.concurrentperformance.throughput.apps; import com.concurrentperformance.throughput.ringbuffer.impl.MutatorHandler; /** * TODO comments??? * * @author Steve Lake */ public class GetDataspaceMutatorHandler implements MutatorHandler<MyBucket> { @Override public void handle(MyBucket bucket, long sequence) { } }
Java
CL
b8ef76a17d7446167b9574d1b8df64edbb53d868bebbdf6668253606aa6860f8
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. 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. */ package cn.aws.cognitobjs.model; public class AuthenticationRequestModel { @com.google.gson.annotations.SerializedName("userName") private String userName = null; @com.google.gson.annotations.SerializedName("passwordHash") private String passwordHash = null; /** * Gets userName * * @return userName **/ public String getUserName() { return userName; } /** * Sets the value of userName. * * @param userName the new value */ public void setUserName(String userName) { this.userName = userName; } /** * Gets passwordHash * * @return passwordHash **/ public String getPasswordHash() { return passwordHash; } /** * Sets the value of passwordHash. * * @param passwordHash the new value */ public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } }
Java
CL
6d7a015d84b5f26447a37dd0141c8d910c040fc0f6a3ac54511d5b21a7b87ba1
package com.wuxue.api.mapper; import com.wuxue.api.interfaces.*; import com.wuxue.model.ScheduleConstraint; import java.util.List; public interface ScheduleConstraintMapper extends IInsertMapper<ScheduleConstraint>,ICountMapper<ScheduleConstraint,Integer>, IUpdateMapper<ScheduleConstraint>,IDeleteByPrimaryKeyMapper<Long>, ISelectByPrimaryKeyMapper<Long,ScheduleConstraint>,ISelectMapper<ScheduleConstraint,List<ScheduleConstraint>> { }
Java
CL
d265daf285320d07aaeacb05011ac85e558cd0ca008b476170b848d705727ea2
/** * <copyright> * </copyright> * * $Id$ */ package org.ptolemy.ecore.kernel.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import org.ptolemy.ecore.kernel.Attribute; import org.ptolemy.ecore.kernel.KernelPackage; import org.ptolemy.ecore.kernel.Nameable; import org.ptolemy.ecore.kernel.NamedObj; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Named Obj</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.ptolemy.ecore.kernel.impl.NamedObjImpl#getName <em>Name</em>}</li> * <li>{@link org.ptolemy.ecore.kernel.impl.NamedObjImpl#getDisplayName <em>Display Name</em>}</li> * <li>{@link org.ptolemy.ecore.kernel.impl.NamedObjImpl#getAttributes <em>Attributes</em>}</li> * <li>{@link org.ptolemy.ecore.kernel.impl.NamedObjImpl#getInheritsFrom <em>Inherits From</em>}</li> * </ul> * </p> * * @generated */ public abstract class NamedObjImpl extends EObjectImpl implements NamedObj { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getDisplayName() <em>Display Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDisplayName() * @generated * @ordered */ protected static final String DISPLAY_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getDisplayName() <em>Display Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDisplayName() * @generated * @ordered */ protected String displayName = DISPLAY_NAME_EDEFAULT; /** * The cached value of the '{@link #getAttributes() <em>Attributes</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAttributes() * @generated * @ordered */ protected EList<Attribute> attributes; /** * The cached value of the '{@link #getInheritsFrom() <em>Inherits From</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInheritsFrom() * @generated * @ordered */ protected NamedObj inheritsFrom; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected NamedObjImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return KernelPackage.Literals.NAMED_OBJ; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public String getName() { return (name != null ? name : (inheritsFrom != null ? inheritsFrom.getName() : null)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, KernelPackage.NAMED_OBJ__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public String getDisplayName() { return (displayName != null ? displayName : (inheritsFrom != null ? inheritsFrom.getDisplayName() : null)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDisplayName(String newDisplayName) { String oldDisplayName = displayName; displayName = newDisplayName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, KernelPackage.NAMED_OBJ__DISPLAY_NAME, oldDisplayName, displayName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Attribute> getAttributes() { if (attributes == null) { attributes = new EObjectContainmentEList<Attribute>(Attribute.class, this, KernelPackage.NAMED_OBJ__ATTRIBUTES); } return attributes; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NamedObj getInheritsFrom() { if (inheritsFrom != null && inheritsFrom.eIsProxy()) { InternalEObject oldInheritsFrom = (InternalEObject)inheritsFrom; inheritsFrom = (NamedObj)eResolveProxy(oldInheritsFrom); if (inheritsFrom != oldInheritsFrom) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, KernelPackage.NAMED_OBJ__INHERITS_FROM, oldInheritsFrom, inheritsFrom)); } } return inheritsFrom; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NamedObj basicGetInheritsFrom() { return inheritsFrom; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInheritsFrom(NamedObj newInheritsFrom) { NamedObj oldInheritsFrom = inheritsFrom; inheritsFrom = newInheritsFrom; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, KernelPackage.NAMED_OBJ__INHERITS_FROM, oldInheritsFrom, inheritsFrom)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public Attribute getAttribute(String name) { return getNamed(name, this, KernelPackage.eINSTANCE.getNamedObj_Attributes()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public NamedObj getContainer() { return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public String getFullName() { return getName(null); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public String getName(NamedObj namedObj) { if (getName() == null) { return null; } StringBuilder fullName = new StringBuilder(getName()); Nameable container = getContainer(), cddr = (container != null ? container.getContainer() : null); while (container != namedObj && container != null) { if (container.getName() != null) { fullName.insert(0, '.'); fullName.insert(0, container.getName()); } container = container.getContainer(); if (cddr != null) { cddr = cddr.getContainer(); if (cddr != null) { cddr = cddr.getContainer(); } if (cddr == container) { throw new IllegalStateException("Circular containment structure"); } } } return fullName.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case KernelPackage.NAMED_OBJ__ATTRIBUTES: return ((InternalEList<?>)getAttributes()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case KernelPackage.NAMED_OBJ__NAME: return getName(); case KernelPackage.NAMED_OBJ__DISPLAY_NAME: return getDisplayName(); case KernelPackage.NAMED_OBJ__ATTRIBUTES: return getAttributes(); case KernelPackage.NAMED_OBJ__INHERITS_FROM: if (resolve) return getInheritsFrom(); return basicGetInheritsFrom(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case KernelPackage.NAMED_OBJ__NAME: setName((String)newValue); return; case KernelPackage.NAMED_OBJ__DISPLAY_NAME: setDisplayName((String)newValue); return; case KernelPackage.NAMED_OBJ__ATTRIBUTES: getAttributes().clear(); getAttributes().addAll((Collection<? extends Attribute>)newValue); return; case KernelPackage.NAMED_OBJ__INHERITS_FROM: setInheritsFrom((NamedObj)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case KernelPackage.NAMED_OBJ__NAME: setName(NAME_EDEFAULT); return; case KernelPackage.NAMED_OBJ__DISPLAY_NAME: setDisplayName(DISPLAY_NAME_EDEFAULT); return; case KernelPackage.NAMED_OBJ__ATTRIBUTES: getAttributes().clear(); return; case KernelPackage.NAMED_OBJ__INHERITS_FROM: setInheritsFrom((NamedObj)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case KernelPackage.NAMED_OBJ__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case KernelPackage.NAMED_OBJ__DISPLAY_NAME: return DISPLAY_NAME_EDEFAULT == null ? displayName != null : !DISPLAY_NAME_EDEFAULT.equals(displayName); case KernelPackage.NAMED_OBJ__ATTRIBUTES: return attributes != null && !attributes.isEmpty(); case KernelPackage.NAMED_OBJ__INHERITS_FROM: return inheritsFrom != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(); toString(result); return result.toString(); } protected void toString(StringBuffer result) { result.append(getName()); if (displayName != null) { result.append(" \"" + displayName + "\""); } } // protected static <T extends Nameable> T getNamed(String name, EList<T> nameds) { for (T t : nameds) { if (name.equals(t.getName())) { return t; } } return null; } protected static <T extends Nameable> T getNamed(String name, NamedObj named, EStructuralFeature feature) { return getNamed(name, (EList<T>) named.eGet(feature)); } } //NamedObjImpl
Java
CL
d3d8fcdad9015c0476238ba849238b204bd1979f8517f174e90dc1dea6e76bf4
package com.aci.demo.h2dbunit.config; import static org.junit.Assert.assertNotNull; import java.util.Collection; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import com.aci.demo.h2dbunit.loaders.CsvDataSetLoader; import com.aci.demo.h2dbunit.model.Characteristic; import com.aci.demo.h2dbunit.service.CharacteristicsService; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DbUnitConfiguration; import com.github.springtestdbunit.annotation.ExpectedDatabase; @ContextConfiguration @SpringBootTest(classes = { TestConfig.class }) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class }) @DbUnitConfiguration(dataSetLoader = CsvDataSetLoader.class) public class DataSetTests { @Autowired private CharacteristicsService charService; // @Test // @DatabaseSetup // @ExpectedDatabase("/datasets/csv/acs_pos_monthly_char/expected_entityId1020andEffDate31Jan17.csv") // public void testFindAllChars() { // Collection<Characteristic> allChars = charService.find(); // // assertNotNull(allChars); // } }
Java
CL
02155428e79e07e10411231acae4ee5486d53c08d7640d274eef650c35227dc1
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.spelling; import java.util.LinkedList; import java.util.Locale; import com.ibm.icu.text.BreakIterator; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; import org.eclipse.jdt.internal.ui.text.javadoc.IHtmlTagConstants; import org.eclipse.jdt.internal.ui.text.spelling.engine.DefaultSpellChecker; import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellCheckIterator; /** * Iterator to spell check javadoc comment regions. * * @since 3.0 */ public class SpellCheckIterator implements ISpellCheckIterator { /** * The token that denotes whitespace. * * @since 3.6 */ private static final int WHITE_SPACE_TOKEN = -1; /** The content of the region */ protected final String fContent; /** The line delimiter */ private final String fDelimiter; /** The last token */ protected String fLastToken = null; /** The next break */ protected int fNext = 1; /** The offset of the region */ protected final int fOffset; /** The predecessor break */ private int fPredecessor; /** The previous break */ protected int fPrevious = 0; /** The sentence breaks */ private final LinkedList<Integer> fSentenceBreaks = new LinkedList(); /** Does the current word start a sentence? */ private boolean fStartsSentence = false; /** The successor break */ protected int fSuccessor; /** The word iterator */ private final BreakIterator fWordIterator; private boolean fIsIgnoringSingleLetters; /** * Creates a new spell check iterator. * * @param document the document containing the specified partition * @param region the region to spell check * @param locale the locale to use for spell checking */ public SpellCheckIterator(IDocument document, IRegion region, Locale locale) { this(document, region, locale, BreakIterator.getWordInstance(locale)); } /** * Creates a new spell check iterator. * * @param document the document containing the specified partition * @param region the region to spell check * @param locale the locale to use for spell checking * @param breakIterator the break-iterator */ public SpellCheckIterator(IDocument document, IRegion region, Locale locale, BreakIterator breakIterator) { fOffset = region.getOffset(); fWordIterator = breakIterator; fDelimiter = TextUtilities.getDefaultLineDelimiter(document); String content; try { content = document.get(region.getOffset(), region.getLength()); if (content.startsWith(NLSElement.TAG_PREFIX)) //$NON-NLS-1$ content = ""; } catch (Exception exception) { content = ""; } fContent = content; fWordIterator.setText(content); fPredecessor = fWordIterator.first(); fSuccessor = fWordIterator.next(); final BreakIterator iterator = BreakIterator.getSentenceInstance(locale); iterator.setText(content); int offset = iterator.current(); while (offset != BreakIterator.DONE) { fSentenceBreaks.add(new Integer(offset)); offset = iterator.next(); } } /* * @see org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellCheckIterator#setIgnoreSingleLetters(boolean) * @since 3.3 */ @Override public void setIgnoreSingleLetters(boolean state) { fIsIgnoringSingleLetters = state; } /* * @see org.eclipse.spelling.done.ISpellCheckIterator#getBegin() */ @Override public final int getBegin() { return fPrevious + fOffset; } /* * @see org.eclipse.spelling.done.ISpellCheckIterator#getEnd() */ @Override public final int getEnd() { return fNext + fOffset - 1; } /* * @see java.util.Iterator#hasNext() */ @Override public final boolean hasNext() { return fSuccessor != BreakIterator.DONE; } /** * Does the specified token consist of at least one letter and digits * only? * * @param begin the begin index * @param end the end index * @return <code>true</code> iff the token consists of digits and at * least one letter only, <code>false</code> otherwise */ protected final boolean isAlphaNumeric(final int begin, final int end) { char character = 0; boolean letter = false; for (int index = begin; index < end; index++) { character = fContent.charAt(index); if (Character.isLetter(character)) letter = true; if (!Character.isLetterOrDigit(character)) return false; } return letter; } /** * Checks the last token against the given tags? * * @param tags the tags to check * @return <code>true</code> iff the last token is in the given array */ protected final boolean isToken(final String[] tags) { return isToken(fLastToken, tags); } /** * Checks the given token against the given tags? * * @param token the token to check * @param tags the tags to check * @return <code>true</code> iff the last token is in the given array * @since 3.3 */ protected final boolean isToken(final String token, final String[] tags) { if (token != null) { for (int index = 0; index < tags.length; index++) { if (token.equals(tags[index])) return true; } } return false; } /** * Is the current token a single letter token surrounded by * non-whitespace characters? * * @param begin the begin index * @return <code>true</code> iff the token is a single letter token, * <code>false</code> otherwise */ protected final boolean isSingleLetter(final int begin) { if (!Character.isLetter(fContent.charAt(begin))) return false; if (begin > 0 && !Character.isWhitespace(fContent.charAt(begin - 1))) return false; if (begin < fContent.length() - 1 && !Character.isWhitespace(fContent.charAt(begin + 1))) return false; return true; } /** * Does the specified token look like an URL? * * @param begin the begin index * @return <code>true</code> iff this token look like an URL, * <code>false</code> otherwise */ protected final boolean isUrlToken(final int begin) { for (int index = 0; index < DefaultSpellChecker.URL_PREFIXES.length; index++) { if (fContent.startsWith(DefaultSpellChecker.URL_PREFIXES[index], begin)) return true; } return false; } /** * Does the specified token consist of whitespace only? * * @param begin the begin index * @param end the end index * @return <code>true</code> iff the token consists of whitespace * only, <code>false</code> otherwise */ protected final boolean isWhitespace(final int begin, final int end) { for (int index = begin; index < end; index++) { if (!Character.isWhitespace(fContent.charAt(index))) return false; } return true; } /* * @see java.util.Iterator#next() */ @Override public String next() { String token = nextToken(); while (token == null && fSuccessor != BreakIterator.DONE) token = nextToken(); fLastToken = token; return token; } /** * Advances the end index to the next word break. */ protected final void nextBreak() { fNext = fSuccessor; fPredecessor = fSuccessor; fSuccessor = fWordIterator.next(); } /** * Returns the next sentence break. * * @return the next sentence break */ protected final int nextSentence() { return fSentenceBreaks.getFirst().intValue(); } /** * Determines the next token to be spell checked. * * @return the next token to be spell checked, or <code>null</code> * iff the next token is not a candidate for spell checking. */ protected String nextToken() { String token = null; fPrevious = fPredecessor; fStartsSentence = false; nextBreak(); boolean update = false; if (fNext - fPrevious > 0) { if (fSuccessor != BreakIterator.DONE && fContent.charAt(fPrevious) == IJavaDocTagConstants.JAVADOC_TAG_PREFIX) { nextBreak(); if (Character.isLetter(fContent.charAt(fPrevious + 1))) { update = true; token = fContent.substring(fPrevious, fNext); } else fPredecessor = fNext; } else if (fSuccessor != BreakIterator.DONE && fContent.charAt(fPrevious) == IHtmlTagConstants.HTML_TAG_PREFIX && (Character.isLetter(fContent.charAt(fNext)) || fContent.charAt(fNext) == '/')) { if (fContent.startsWith(IHtmlTagConstants.HTML_CLOSE_PREFIX, fPrevious)) nextBreak(); nextBreak(); if (fSuccessor != BreakIterator.DONE && fContent.charAt(fNext) == IHtmlTagConstants.HTML_TAG_POSTFIX) { nextBreak(); if (fSuccessor != BreakIterator.DONE) { update = true; token = fContent.substring(fPrevious, fNext); } } } else if (fSuccessor != BreakIterator.DONE && fContent.charAt(fPrevious) == IHtmlTagConstants.HTML_ENTITY_START && (Character.isLetter(fContent.charAt(fNext)))) { nextBreak(); if (fSuccessor != BreakIterator.DONE && fContent.charAt(fNext) == IHtmlTagConstants.HTML_ENTITY_END) { nextBreak(); if (isToken(fContent.substring(fPrevious, fNext), IHtmlTagConstants.HTML_ENTITY_CODES)) { skipTokens(fPrevious, IHtmlTagConstants.HTML_ENTITY_END); update = true; } else token = fContent.substring(fPrevious, fNext); } else token = fContent.substring(fPrevious, fNext); update = true; } else if (!isWhitespace(fPrevious, fNext) && isAlphaNumeric(fPrevious, fNext)) { if (isUrlToken(fPrevious)) skipTokens(fPrevious, WHITE_SPACE_TOKEN); else if (isToken(IJavaDocTagConstants.JAVADOC_PARAM_TAGS)) fLastToken = null; else if (isToken(IJavaDocTagConstants.JAVADOC_REFERENCE_TAGS)) { fLastToken = null; skipTokens(fPrevious, fDelimiter.charAt(0)); } else if (fNext - fPrevious > 1 || isSingleLetter(fPrevious) && !fIsIgnoringSingleLetters) token = fContent.substring(fPrevious, fNext); update = true; } } if (update && fSentenceBreaks.size() > 0) { if (fPrevious >= nextSentence()) { while (fSentenceBreaks.size() > 0 && fPrevious >= nextSentence()) fSentenceBreaks.removeFirst(); fStartsSentence = (fLastToken == null) || (token != null); } } return token; } /* * @see java.util.Iterator#remove() */ @Override public final void remove() { throw new UnsupportedOperationException(); } /** * Skip the tokens until the stop character is reached. * * @param begin the begin index * @param stop the stop character */ protected final void skipTokens(final int begin, final int stop) { final boolean isStoppingOnWhiteSpace = stop == WHITE_SPACE_TOKEN; int end = begin; while (end < fContent.length()) { char ch = fContent.charAt(end); if (ch == stop || isStoppingOnWhiteSpace && Character.isWhitespace(ch)) break; end++; } if (end < fContent.length()) { fNext = end; fPredecessor = fNext; fSuccessor = fWordIterator.following(fNext); } else fSuccessor = BreakIterator.DONE; } /* * @see org.eclipse.spelling.done.ISpellCheckIterator#startsSentence() */ @Override public final boolean startsSentence() { return fStartsSentence; } }
Java
CL
a43fb4589f14ae3ed479c9b0dd7d6dca364fe7b28936cb0226e74e3f0de35820
/* * Copyright (c) 2002-2017 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.causalclustering.helper; import org.neo4j.logging.Log; import static java.lang.String.format; import static org.neo4j.logging.FormattedLogProvider.toOutputStream; @SuppressWarnings( "unused" ) // for easy debugging, leave it public class StatUtil { public static class StatContext { private static final int N_BUCKETS = 10; // values >= Math.pow( 10, N_BUCKETS-1 ) all go into the last bucket private final String name; private final Log log; private final long printEvery; private final boolean clearAfterPrint; private BasicStats[] bucket = new BasicStats[N_BUCKETS]; private long totalCount; private StatContext( String name, Log log, long printEvery, boolean clearAfterPrint ) { this.name = name; this.log = log; this.printEvery = printEvery; this.clearAfterPrint = clearAfterPrint; clear(); } public synchronized void clear() { for ( int i = 0; i < N_BUCKETS; i++ ) { bucket[i] = new BasicStats(); } totalCount = 0; } public void collect( double value ) { int bucketIndex = bucketFor( value ); synchronized ( this ) { totalCount++; bucket[bucketIndex].collect( value ); if ( totalCount % printEvery == 0 ) { print(); } } } private int bucketFor( double value ) { int bucketIndex; if ( value <= 0 ) { // we do not have buckets for negative values, we assume user doesn't measure such things // however, if they do, it will all be collected in bucket 0 bucketIndex = 0; } else { bucketIndex = (int) Math.log10( value ); bucketIndex = Math.min( bucketIndex, N_BUCKETS - 1 ); } return bucketIndex; } public TimingContext time() { return new TimingContext( this ); } public synchronized void print() { for ( BasicStats stats : bucket ) { if ( stats.count > 0 ) { log.info( format( "%s%s", name, stats ) ); } } if ( clearAfterPrint ) { clear(); } } } private StatUtil() { } public static synchronized StatContext create( String name, long printEvery, boolean clearAfterPrint ) { return create( name, toOutputStream( System.out ).getLog( name ), printEvery, clearAfterPrint ); } public static synchronized StatContext create( String name, Log log, long printEvery, boolean clearAfterPrint ) { return new StatContext( name, log, printEvery, clearAfterPrint ); } public static class TimingContext { private final StatContext context; private final long startTime = System.currentTimeMillis(); TimingContext( StatContext context ) { this.context = context; } public void end() { context.collect( System.currentTimeMillis() - startTime ); } } private static class BasicStats { private Double min; private Double max; private Double avg = 0.; private long count; void collect( double val ) { count++; avg = avg + (val - avg) / count; min = min == null ? val : Math.min( min, val ); max = max == null ? val : Math.max( max, val ); } @Override public String toString() { return format( "{min=%s, max=%s, avg=%s, count=%d}", min, max, avg, count ); } } }
Java
CL
457ca24da9b7fdb6002392fbbb1689d28ae4155676d19db7c8e8d5059bcff8ae
package org.kivymfz.devicedl.mqtt.device; import com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3Publish; import org.kivymfz.devicedl.mqtt.command.Command; import org.kivymfz.devicedl.mqtt.command.EmitCommand; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class DeviceRm extends BaseDevice { public DeviceRm(String name, Mqtt3Publish pub) { super(name, pub); state |= STATE_STATELESS; } public static class Pair<K, V> { public K key; public V value; public Pair(K k, V v) { key = k; value = v; } } @Override public void parseState(Mqtt3Publish publish) { try { String topic = publish.getTopic().toString(); String id = getId(); String jsons = StandardCharsets.UTF_8.decode(publish.getPayload().get()).toString(); if (topic.equals("stat/" + id + "/emit")) { JSONArray jso = new JSONArray(jsons); int sta = 1; for (int i = 0; i<jso.length(); i++) { sta = jso.getJSONObject(i).getInt("status"); if (sta!=1) break; } state = (sta != 1? STATE_ERROR_OFFSET + sta: STATE_OK) | STATE_STATELESS | DEVICE_TYPE_REMOTE; /*Iterable it = (() -> jso.iterator()); Optional<Integer> rv = StreamSupport.stream(it.spliterator(),false). map(el -> ((JSONObject)el).getInt("status")). filter(sta -> (Integer)sta != 1).findFirst(); state = (rv.isPresent()? STATE_ERROR_OFFSET + rv.get(): STATE_OK) | STATE_STATELESS;*/ } else if (topic.equals("stat/" + id + "/remotes")) { JSONObject remotes = new JSONObject(jsons); List<Command> cmds = new ArrayList<>(); for (Iterator<String> it = remotes.keys(); it.hasNext(); ) { String remName = it.next(); JSONArray remote = remotes.getJSONArray(remName); for (int j = 0; j<remote.length(); j++) { cmds.add(new EmitCommand(remName, remote.getString(j), this)); } } /*List<Command> cmds = (List<Command>) remotes.keySet().stream().map(k -> new Pair<String, JSONArray>(k, remotes.getJSONArray(k))). flatMap(p -> { Iterable it = (() -> p.value.iterator()); return StreamSupport.stream(it.spliterator(),false).map(o -> new EmitCommand(p.key, o.toString(), this)); }).collect(Collectors.toList());*/ if (commands == null) commands = cmds; else { commands = commands.stream().filter(c -> c.getRemote().equals("@")).collect(Collectors.toList()); commands.addAll(cmds); } this.remotes = commands.stream().map(c -> c.getRemote()).distinct().collect(Collectors.toList()); } else if (topic.equals("stat/" + id + "/shortcuts")) { JSONArray shs = new JSONArray(jsons); List<Command> cmds = new ArrayList<>(); for (int j = 0; j<shs.length(); j++) { cmds.add(new EmitCommand("@", shs.getString(j), this)); } /*Iterable it = (() -> shs.iterator()); List<Command> cmds = (List<Command>) StreamSupport.stream(it.spliterator(),false).map(o -> new EmitCommand("@", o.toString(), this)).collect(Collectors.toList());*/ if (commands == null) commands = cmds; else { commands = commands.stream().filter(c -> !c.getRemote().equals("@")).collect(Collectors.toList()); commands.addAll(cmds); } this.remotes = commands.stream().map(c -> c.getRemote()).distinct().collect(Collectors.toList()); } } catch (JSONException e) { e.printStackTrace(); state = STATE_INVALID | STATE_STATELESS | DEVICE_TYPE_REMOTE; } } }
Java
CL
f744d28a36f90913cb986fa2c56e2c47e703182a31a97cd5eee7ea03900588a6
package org.apache.logging.log4j.spi; import java.util.concurrent.ConcurrentMap; /** * A basic registry for {@link LoggerContext} objects and their associated external * Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to * other external log systems. * * @param <L> the external logger class for this registry (e.g., {@code org.slf4j.Logger}) * @since 2.1 */ public interface LoggerAdapter<L> { /** * Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}. * * @param name the name of the logger to get * @return the named logger */ L getLogger(String name); /** * Gets or creates the ConcurrentMap of named loggers for a given LoggerContext. * * @param context the LoggerContext to get loggers for * @return the map of loggers for the given LoggerContext */ ConcurrentMap<String, L> getLoggersInContext(LoggerContext context); /** * Shuts down this registry. Implementations should clear out any instance data and perform any relevant clean-up. */ void stop(); }
Java
CL
67a6ae219e689803a4be8c574511cebaa91d5eb86a990bc3c4e231f689987957
/* * Copyright 2016 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.rf.ide.core.testdata.model.table.setting.views; import java.util.List; import org.rf.ide.core.testdata.model.table.setting.SuiteDocumentation; import org.rf.ide.core.testdata.text.read.recognizer.RobotToken; public class SuiteDocumentationView extends SuiteDocumentation implements ISingleElementViewer { private final List<SuiteDocumentation> suiteDocs; private final boolean changeForceRebuild; public SuiteDocumentationView(final List<SuiteDocumentation> suiteDocs) { this(suiteDocs, false); } public SuiteDocumentationView(final List<SuiteDocumentation> suiteDocs, final boolean changeForceRebuild) { super(suiteDocs.get(0).getDeclaration()); this.suiteDocs = suiteDocs; this.changeForceRebuild = changeForceRebuild; // join tags for this view final SuiteDocumentation doc = new SuiteDocumentation(getDeclaration()); joinDoc(doc, suiteDocs); copyWithoutJoinIfNeededExecution(doc); } @Override public boolean isForceRebuild() { return changeForceRebuild; } private void copyWithoutJoinIfNeededExecution(final SuiteDocumentation doc) { for (final RobotToken token : doc.getDocumentationText()) { super.addDocumentationText(token); } for (final RobotToken comment : doc.getComment()) { super.addCommentPart(comment); } } @Override public void addDocumentationText(final String text) { joinIfNeeded(); super.addDocumentationText(text); } @Override public void addDocumentationText(final RobotToken token) { joinIfNeeded(); super.addDocumentationText(token); } @Override public void setDocumentationText(final int index, final String docText) { OneSettingJoinerHelper.applyJoinBeforeModificationIfNeeded(this, super.getDocumentationText(), index); super.setDocumentationText(index, docText); } @Override public void setDocumentationText(final int index, final RobotToken docText) { OneSettingJoinerHelper.applyJoinBeforeModificationIfNeeded(this, super.getDocumentationText(), index); super.setDocumentationText(index, docText); } @Override public void addCommentPart(final RobotToken rt) { joinIfNeeded(); super.addCommentPart(rt); } @Override public void setComment(final String comment) { joinIfNeeded(); super.setComment(comment); } @Override public void setComment(final RobotToken rt) { joinIfNeeded(); super.setComment(rt); } @Override public synchronized void joinIfNeeded() { if (suiteDocs.size() > 1) { SuiteDocumentation joined = new SuiteDocumentation(getDeclaration()); joinDoc(joined, suiteDocs); suiteDocs.clear(); suiteDocs.add(this); } } private void joinDoc(final SuiteDocumentation target, final List<SuiteDocumentation> suiteDocs) { for (final SuiteDocumentation sd : suiteDocs) { for (final RobotToken text : sd.getDocumentationText()) { target.addDocumentationText(text); } for (final RobotToken comment : sd.getComment()) { target.addCommentPart(comment); } } } }
Java
CL
8f4233dee8d23a7bd8f543cb19aa13f49ed4b8d29868a7d5f66721fcb9de4823
/** * 系统名称 :城市一卡通综合管理平台 * 开发组织 :城市一卡通事业部 * 版权所属 :新开普电子股份有限公司 * (C) Copyright Corporation 2014 All Rights Reserved. * 本内容仅限于郑州新开普电子股份有限公司内部使用,版权保护,未经过授权拷贝使用将追究法律责任 */ package cn.newcapec.function.ecardcity.om.utils; import java.io.Serializable; import java.util.List; /** * @author wj * @category z-tree的后台bean * @version 1.0 * @date 2014年4月10日 下午10:37:30 */ public class TreeView implements Serializable{ private static final long serialVersionUID = 8167507052150298533L; private String id; private String pId; private String url; private String name; private String target; private boolean open; private List<TreeView> children; /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the pId */ public String getpId() { return pId; } /** * @param pId the pId to set */ public void setpId(String pId) { this.pId = pId; } /** * @return the url */ public String getUrl() { return url; } /** * @param url the url to set */ public void setUrl(String url) { this.url = url; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the target */ public String getTarget() { return target; } /** * @param target the target to set */ public void setTarget(String target) { this.target = target; } /** * @return the open */ public boolean isOpen() { return open; } /** * @param open the open to set */ public void setOpen(boolean open) { this.open = open; } /** * @return the nodes */ public List<TreeView> getNodes() { return children; } /** * @param nodes the nodes to set */ public void setNodes(List<TreeView> children) { this.children = children; } }
Java
CL
16403968da47e3dd471abcb6ac33fd3e0a8faf81d7a4418bde7ffbb4213906f6
package com.crunch.tutor.examples.musicstore; import java.io.IOException; import org.apache.crunch.MapFn; import au.com.bytecode.opencsv.CSVParser; import com.crunch.tutor.api.music.store.Song; /** * A {@link MapFn} implementation that takes in a String as input and return a {@link Song} * instance. Each line of the input string should be formatted of the form * {@code "songId","song title","artist"} */ public class SongMapFn extends MapFn<String, Song> { // Generate this since MapFn implements serializable private static final long serialVersionUID = -1034942975963730842L; // Let's create a default parser that splits based on comma(,) private static CSVParser CSV_PARSER = new CSVParser(); @Override public Song map(final String input) { final Song.Builder songBuilder = Song.newBuilder(); try { // For the sake of simplicity, let us assume that input file is properly formatted csv. final String[] parsedInputs = CSV_PARSER.parseLine(input); // Again, for simplicity, let us assume the input data contains the right fields and we // do not fail with exception. But in a real use case, we have to check for incorrectly // formatted data, and handle exceptions appropriately. songBuilder.setSongId(parsedInputs[0]); songBuilder.setSongTitle(parsedInputs[1]); songBuilder.setArtistName(parsedInputs[2]); } catch (final IOException e) { e.printStackTrace(); } return songBuilder.build(); } }
Java
CL
e6fb5ff4e291f269f15d63ebcee9ac6945311cb7be8b56c03b0e88faacc563ac
package resources.webService.endpoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ws.server.endpoint.annotation.Namespace; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import org.springframework.ws.server.endpoint.annotation.XPathParam; import org.w3c.dom.Element; import resources.webService.LocalisationService; /** * Created with IntelliJ IDEA. * User: Julien * Date: 01/04/13 * Time: 17:59 */ public class LocalisationEndPoint { private static final String NAMESPACE_URI = "http://barreaujonas.com/iaws/schemas/"; private LocalisationService localisation; @Autowired public LocalisationEndPoint(LocalisationService localisationService) { localisation = localisationService; } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "LocalisationRequest") @Namespace(prefix = "pref", uri = NAMESPACE_URI) @ResponsePayload public Element handleLocalisationRequest( @XPathParam("/pref:LocalisationRequest/pref:id_user") Integer userID, @XPathParam("/pref:LocalisationRequest/pref:rayon") Integer rayonKm) throws Exception { Element response = localisation.chercheVoisin(userID, rayonKm); return response; } }
Java
CL
dc4a1a755b226f85b297f133b29a0ddf5ca4fc86ba53e8d95240815b475e3eb6
package com.example.ccc.fit; import android.location.Location; import android.location.LocationListener; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.widget.*; import com.baidu.*; import com.baidu.mapapi.BMapManager; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.model.inner.GeoPoint; public class maptest2 extends AppCompatActivity { /* @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maptest2); } */ private String mMapKey = "c98eGttF0avoXSgRykVqWPhz3DE0F0aD"; private EditText destinationEditText = null; private Button startNaviButton = null; private MapView mapView = null; private BMapManager mMapManager = null; private MyLocationOverlay myLocationOverlay = null; //onResume时注册此listener,onPause时需要Remove,注意此listener不是Android自带的,是百度API中的 private LocationListener locationListener; private MKSearch searchModel; GeoPoint pt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_maptest2); destinationEditText = (EditText) this.findViewById(R.id.et_destination); startNaviButton = (Button) this.findViewById(R.id.btn_navi); mMapManager = new BMapManager(getApplication()); mMapManager.init(mMapKey,new MyGeneralListener()); super.initMapActivity(mMapManager); mapView = (MapView) this.findViewById(R.id.bmapsView); //设置启用内置的缩放控件 mapView.setBuiltInZoomControls(true); //设置在缩放动画过程中也显示overlay,默认为不绘制 // mapView.setDrawOverlayWhenZooming(true); //获取当前位置层 myLocationOverlay = new MyLocationOverlay(this, mapView); //将当前位置的层添加到地图底层中 mapView.getOverlays().add(myLocationOverlay); // 注册定位事件 locationListener = new LocationListener(){ @Override public void onLocationChanged(Location location) { if (location != null){ //生成GEO类型坐标并在地图上定位到该坐标标示的地点 pt = new GeoPoint((int)(location.getLatitude()*1e6), (int)(location.getLongitude()*1e6)); // System.out.println("---"+location.getLatitude() +":"+location.getLongitude()); mapView.getController().animateTo(pt); } } }; //初始化搜索模块 searchModel = new MKSearch(); //设置路线策略为最短距离 searchModel.setDrivingPolicy(MKSearch.ECAR_DIS_FIRST); searchModel.init(mMapManager, new MKSearchListener() { //获取驾车路线回调方法 @Override public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { // 错误号可参考MKEvent中的定义 if (error != 0 || res == null) { Toast.makeText(NavigationDemoActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show(); return; } RouteOverlay routeOverlay = new RouteOverlay(NavigationDemoActivity.this, mapView); // 此处仅展示一个方案作为示例 MKRoute route = res.getPlan(0).getRoute(0); int distanceM = route.getDistance(); String distanceKm = String.valueOf(distanceM / 1000) +"."+String.valueOf(distanceM % 1000); System.out.println("距离:"+distanceKm+"公里---节点数量:"+route.getNumSteps()); for (int i = 0; i < route.getNumSteps(); i++) { MKStep step = route.getStep(i); System.out.println("节点信息:"+step.getContent()); } routeOverlay.setData(route); mapView.getOverlays().clear(); mapView.getOverlays().add(routeOverlay); mapView.invalidate(); mapView.getController().animateTo(res.getStart().pt); } //以下两种方式和上面的驾车方案实现方法一样 @Override public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { //获取步行路线 } @Override public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) { //获取公交线路 } @Override public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) { } @Override public void onGetAddrResult(MKAddrInfo arg0, int arg1) { } @Override public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) { } @Override public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) { } }); startNaviButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String destination = destinationEditText.getText().toString(); //设置起始地(当前位置) MKPlanNode startNode = new MKPlanNode(); startNode.pt = pt; //设置目的地 MKPlanNode endNode = new MKPlanNode(); endNode.name = destination; //展开搜索的城市 String city = getResources().getString(R.string.beijing); // System.out.println("----"+city+"---"+destination+"---"+pt); searchModel.drivingSearch(city, startNode, city, endNode); //步行路线 // searchModel.walkingSearch(city, startNode, city, endNode); //公交路线 // searchModel.transitSearch(city, startNode, endNode); } }); } @Override protected void onResume() { mMapManager.getLocationManager().requestLocationUpdates(locationListener); myLocationOverlay.enableMyLocation(); myLocationOverlay.enableCompass(); // 打开指南针 mMapManager.start(); super.onResume(); } @Override protected void onPause() { mMapManager.getLocationManager().removeUpdates(locationListener); myLocationOverlay.disableMyLocation();//显示当前位置 myLocationOverlay.disableCompass(); // 关闭指南针 mMapManager.stop(); super.onPause(); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } // 常用事件监听,用来处理通常的网络错误,授权验证错误等 class MyGeneralListener implements MKGeneralListener { @Override public void onGetNetworkState(int iError) { Log.d("MyGeneralListener", "onGetNetworkState error is "+ iError); Toast.makeText(maptest2.this, "您的网络出错啦!", Toast.LENGTH_LONG).show(); } @Override public void onGetPermissionState(int iError) { Log.d("MyGeneralListener", "onGetPermissionState error is "+ iError); if (iError == MKEvent.ERROR_PERMISSION_DENIED) { // 授权Key错误: Toast.makeText(maptest2.this, "请在BMapApiDemoApp.java文件输入正确的授权Key!", Toast.LENGTH_LONG).show(); } } } }
Java
CL
291d5b0d8c39b2fdb507acd99029b10fd9f2eec1f228e5af437b11e135e02b40
package com.bnade.wow.catcher.entity; import com.bnade.wow.dao.ItemDao; import com.bnade.wow.entity.Bonus; import com.bnade.wow.util.RedisUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import java.sql.SQLException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class JAuction { private static Logger logger = LoggerFactory.getLogger(JAuction.class); private int auc; private int item; private String owner; private String ownerRealm; private long bid; private long buyout; private int quantity; private String timeLeft; private int rand; private long seed; private int context; private List<JModifier> modifiers; private int petSpeciesId; private int petBreedId; private int petLevel; private int petQualityId; private List<JBonusList> bonusLists; private static Set<Integer> caredBonusIds; private static Set<Integer> notCaredBonusIds; /** * 把BonusLists转化成String,且只显示自己关心的bonus * @return String */ public String convertBonusListsToString() { // 获取数据库中定义的bonus if (caredBonusIds == null) { caredBonusIds = new HashSet<>(); notCaredBonusIds = new HashSet<>(); try { List<Bonus> bonuses = ItemDao.getInstance().findAllBonuses(); for (Bonus bonus : bonuses) { // 空的bonus name表示不需要区分的 if (!"".equals(bonus.getName().trim())) { caredBonusIds.add(bonus.getId()); } else { notCaredBonusIds.add(bonus.getId()); } } } catch (SQLException e) { e.printStackTrace(); } logger.info("关心的bonus {}个", caredBonusIds.size()); logger.info("不关心的bonus {}个", notCaredBonusIds.size()); } String result = ""; if (bonusLists != null && bonusLists.size() > 0) { StringBuffer sb = new StringBuffer(); Collections.sort(bonusLists); for (JBonusList b : bonusLists) { if (caredBonusIds.contains(b.getBonusListId())) { if (sb.length() > 0) { sb.append(","); } sb.append(b.getBonusListId()); } else if (notCaredBonusIds.contains(b.getBonusListId())) { // 已定义了这些bonus id不需要区分,什么也不做 } else { // 保存那些还没有mapping的bonus,用于以后添加,防止漏掉重要的bonus try (Jedis jedis =RedisUtils.getJedisInstace()) { jedis.sadd("bonuses", item + "-" + b.getBonusListId()); } } } result = sb.toString(); } return result; } public int getAuc() { return auc; } public void setAuc(int auc) { this.auc = auc; } public int getItem() { return item; } public void setItem(int item) { this.item = item; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getOwnerRealm() { return ownerRealm; } public void setOwnerRealm(String ownerRealm) { this.ownerRealm = ownerRealm; } public long getBid() { return bid; } public void setBid(long bid) { this.bid = bid; } public long getBuyout() { return buyout; } public void setBuyout(long buyout) { this.buyout = buyout; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getTimeLeft() { return timeLeft; } public void setTimeLeft(String timeLeft) { this.timeLeft = timeLeft; } public int getRand() { return rand; } public void setRand(int rand) { this.rand = rand; } public long getSeed() { return seed; } public void setSeed(long seed) { this.seed = seed; } public int getContext() { return context; } public void setContext(int context) { this.context = context; } public int getPetSpeciesId() { return petSpeciesId; } public void setPetSpeciesId(int petSpeciesId) { this.petSpeciesId = petSpeciesId; } public int getPetBreedId() { return petBreedId; } public void setPetBreedId(int petBreedId) { this.petBreedId = petBreedId; } public int getPetLevel() { return petLevel; } public void setPetLevel(int petLevel) { this.petLevel = petLevel; } public int getPetQualityId() { return petQualityId; } public void setPetQualityId(int petQualityId) { this.petQualityId = petQualityId; } public List<JModifier> getModifiers() { return modifiers; } public void setModifiers(List<JModifier> modifiers) { this.modifiers = modifiers; } public List<JBonusList> getBonusLists() { return bonusLists; } public void setBonusLists(List<JBonusList> bonusLists) { this.bonusLists = bonusLists; } @Override public String toString() { return "JAuction [auc=" + auc + ", item=" + item + ", owner=" + owner + ", ownerRealm=" + ownerRealm + ", bid=" + bid + ", buyout=" + buyout + ", quantity=" + quantity + ", timeLeft=" + timeLeft + ", rand=" + rand + ", seed=" + seed + ", context=" + context + ", modifiers=" + modifiers + ", petSpeciesId=" + petSpeciesId + ", petBreedId=" + petBreedId + ", petLevel=" + petLevel + ", petQualityId=" + petQualityId + ", bonusLists=" + bonusLists + "]"; } }
Java
CL
511e8dd3053de107847c0b25a6cbbc829b1c96279bc72a2b29aa9983972527ad
package com.ravlinko.concordion.extension.mockserver.tag; import com.cedarsoftware.util.io.JsonWriter; import com.ravlinko.concordion.extension.mockserver.utils.JsonPrettyPrinter; import org.concordion.api.CommandCall; import org.concordion.api.Element; import org.concordion.api.Evaluator; import org.concordion.api.ResultRecorder; import org.springframework.stereotype.Component; import static org.mockserver.model.StringBody.exact; @Component public class RequestBodyTag extends MockServerTag { private static final String MOCK_REQUEST_BODY_VARIABLE = "#requestBody"; public RequestBodyTag() { setName("body"); setHttpName("pre"); } @Override public void setUp(CommandCall commandCall, Evaluator evaluator, ResultRecorder resultRecorder) { Element element = commandCall.getElement(); element.addStyleClass("json"); String body = new JsonPrettyPrinter().prettyPrint(element.getText()); element.appendText(body); evaluator.setVariable(MOCK_REQUEST_BODY_VARIABLE, body); RequestTag.requestFromEvaluator(evaluator).withBody(exact(body)); } @Override public void verify(CommandCall commandCall, Evaluator evaluator, ResultRecorder resultRecorder) { Element element = commandCall.getElement(); String body = JsonWriter.formatJson((String) evaluator.getVariable(MOCK_REQUEST_BODY_VARIABLE)); element.moveChildrenTo(new Element("span")); element.appendText(body); } }
Java
CL
8ffd2c46b2b46150cacaa6699c538c71946bde0f90e2a5017a3705214d861759
/* * Copyright 2005-2014 The Kuali Foundation * * 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/ecl1.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.kra.iacuc.correspondence; import org.kuali.kra.iacuc.actions.correspondence.IacucProtocolActionTypeToCorrespondenceTemplateService; import org.kuali.kra.iacuc.actions.print.IacucCorrespondenceXmlStream; import org.kuali.kra.iacuc.actions.print.IacucProtocolPrintWatermark; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.infrastructure.RoleConstants; import org.kuali.kra.protocol.actions.correspondence.ProtocolActionsCorrespondenceBase; import org.kuali.kra.protocol.actions.print.CorrespondenceXmlStreamBase; import org.kuali.kra.protocol.actions.print.ProtocolPrintWatermarkBase; public class IacucProtocolActionsCorrespondence extends ProtocolActionsCorrespondenceBase { private static final long serialVersionUID = 241798237383300450L; private String protocolActionType; public IacucProtocolActionsCorrespondence(String protocolActionType) { this.protocolActionType = protocolActionType; } @Override public String getProtocolActionType() { return protocolActionType; } public void setProtocolActionType(String protocolActionType) { this.protocolActionType = protocolActionType; } @Override protected IacucProtocolActionTypeToCorrespondenceTemplateService getProtocolActionTypeToCorrespondenceTemplateService() { return KraServiceLocator.getService(IacucProtocolActionTypeToCorrespondenceTemplateService.class); } @Override protected ProtocolPrintWatermarkBase getNewProtocolPrintWatermarkInstanceHook() { return new IacucProtocolPrintWatermark(); } @Override public CorrespondenceXmlStreamBase getCorrespondenceXmlStream() { return KraServiceLocator.getService(IacucCorrespondenceXmlStream.class); } @Override protected String getAdministratorType() { return RoleConstants.IACUC_ADMINISTRATOR; } @Override protected String getModuleNameSpace() { return Constants.MODULE_NAMESPACE_IACUC; } }
Java
CL
069f147d3cd8f168f1169bc662472f4515b94b4ee93adc90ca86e50efec6ad57
package com.jeecg.alipay.account.dao; import java.util.List; import org.jeecgframework.minidao.annotation.Param; import org.jeecgframework.minidao.annotation.ResultType; import org.jeecgframework.minidao.annotation.Sql; import org.jeecgframework.minidao.pojo.MiniDaoPage; import org.springframework.stereotype.Repository; import com.jeecg.alipay.account.entity.AlipayMenu; /** * 描述:</b>QywxMenuDao<br> * @author:p3.jeecg * @since:2016年03月28日 13时37分49秒 星期一 * @version:1.0 */ @Repository public interface AlipayMenuDao{ /** * 查询返回Java对象 * @param id * @return */ @Sql("SELECT * FROM alipay_menu WHERE ID = :id") AlipayMenu get(@Param("id") String id); /** * 通过菜单KEY,查询菜单 * @param alipayAccountId * @param * @return */ @Sql("SELECT * FROM alipay_menu WHERE MENU_KEY = :menuKey ") AlipayMenu getMenuByMenuKey(@Param("menuKey") String menuKey); /** * 修改数据 * @param alipayMenu * @return */ int update(@Param("alipayMenu") AlipayMenu alipayMenu); /** * 插入数据 * @param act */ void insert(@Param("alipayMenu") AlipayMenu alipayMenu); /** * 通用分页方法,支持(oracle、mysql、SqlServer、postgresql) * @param alipayMenu * @param page * @param rows * @return */ @ResultType(AlipayMenu.class) public MiniDaoPage<AlipayMenu> getAll(@Param("alipayMenu") AlipayMenu alipayMenu,@Param("page") int page,@Param("rows") int rows); /** * 通过应用ID,获取一级菜单 * @param accountid * @param agentid * @return */ @ResultType(AlipayMenu.class) public List<AlipayMenu> getAllFirstMenu(@Param("accountid")String accountid); /** * 通过父菜单ID,获取二级菜单 * @param agentid * @return */ @ResultType(AlipayMenu.class) public List<AlipayMenu> getAllMenuByParentid(@Param("fatherId") String fatherId); @Sql("DELETE from alipay_menu WHERE ID = :alipayMenu.id") public void delete(@Param("alipayMenu") AlipayMenu alipayMenu); /** * 查询父亲ID * @param sccountid * @param id * @return */ @Sql("SELECT m.id FROM alipay_menu m where m.orders = LEFT(:orders,1)") String getParentId(@Param("orders") String orders); }
Java
CL
b600f9a85db6c82c4f78ef42bd50ca21e18de3944ae6ca0a27fc0608a450fc1a
package com.hoolai.ccgames.skeleton.codec.json; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; import com.hoolai.ccgames.skeleton.dispatch.CommandProperties; import com.hoolai.ccgames.skeleton.dispatch.CommandRegistry; import com.hoolai.ccgames.skeleton.dispatch.NetMessage; public class JsonDecoder extends ByteToMessageDecoder { private CommandRegistry registry; public JsonDecoder( CommandRegistry registry ) { this.registry = registry; } @Override public void decode( ChannelHandlerContext ctx, ByteBuf msg, List< Object > out ) throws Exception { int kindId = msg.readInt(); int msgId = msg.readInt(); CommandProperties properties = registry.get( kindId ); if( properties == null ) throw new RuntimeException( "[JsonDecoder::decode] Can't find cmd " + kindId ); Object message = JsonUtil.decode( msg, properties.remoteObjectClass ); out.add( new NetMessage( kindId, msgId, message ) ); } @Override public void decodeLast( ChannelHandlerContext ctx, ByteBuf msg, List< Object > out ) throws Exception { // do nothing } }
Java
CL
d80323cbb19c28f81d6ad0117768ff1c05a93fef146bca43d1244d20fdc38e2e
/* * This is the confidential unpublished intellectual property of EMC Corporation, * and includes without limitation exclusive copyright and trade secret rights * of EMC throughout the world. */ package com.github.dano.zeromq.impl; import com.github.dano.zeromq.OutMessage; import com.github.dano.zeromq.Payload; import org.zeromq.ZMQ; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * An outgoing Message. */ public class OutMessageImpl implements OutMessage { private static final Logger LOG = LoggerFactory.getLogger(OutMessageImpl.class); private byte[] id; private PayloadImpl msg; private byte[] replyAddress; private OutMessageType type; public enum OutMessageType { REPLIABLE, NON_REPLIABLE } /** * Create an outgoing message without a reply address. * * @param id The socket ID. * @param msg The message. */ public OutMessageImpl(byte[] id, PayloadImpl msg) { this.id = id; this.msg = msg; type = OutMessageType.NON_REPLIABLE; } /** * Create an outgoing message with a reply address * * @param id The socket ID. * @param msg The message. * @param replyAddress The reply address. */ public OutMessageImpl(byte[] id, PayloadImpl msg, byte[] replyAddress) { this.id = id; this.msg = msg; this.replyAddress = replyAddress; type = OutMessageType.REPLIABLE; } /** * Get the socket ID * * @return The soscket ID */ public byte[] getId() { return id; } /** * Get the message contents. * * @return The message. */ public Payload getMsg() { return msg; } /** * Get the reply address. Could be null. * * @return The reply address, or null. */ public byte[] getReplyAddress() { return replyAddress; } /** * Returns true if this OutMessageImpl has a reply address. * @return true if the OutMessageImpl has a replay address, otherwise false. */ public boolean isRepliable() { return type.equals(OutMessageType.REPLIABLE); } /** * Serialize the message and send over a ZMQ.socket. * The id, message, and reply address (if present) are each sent in * separate frames. * * @param socket The socket to send the message over. */ public void sendMessage(ZMQ.Socket socket) { socket.send(id, ZMQ.SNDMORE); socket.send(msg.getMsg(), isRepliable() ? ZMQ.SNDMORE : 0); if (isRepliable()) { socket.send(replyAddress, 0); } } }
Java
CL
017360943ca57e795dd37a7cf925c624d2799ea4d5129b6588e31af8200f2e71
//============================================================================== // This software is part of the Open Standard for Unattended Sensors (OSUS) // reference implementation (OSUS-R). // // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along // with this software. If not, see // <http://creativecommons.org/publicdomain/zero/1.0/>. //============================================================================== package mil.dod.th.ose.remote.integration; import java.io.IOException; import java.net.Socket; import java.util.List; import com.google.protobuf.Message; import mil.dod.th.core.remote.proto.BaseMessages.BaseNamespace.BaseMessageType; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.ClientAckData; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.DataStreamStoreNamespace; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.DataStreamStoreNamespace.DataStreamStoreMessageType; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.DateRange; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.DisableArchivingRequestData; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.EnableArchivingRequestData; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.GetArchivePeriodsRequestData; import mil.dod.th.core.remote.proto.DataStreamStoreMessages.GetArchivePeriodsResponseData; import mil.dod.th.core.remote.proto.RemoteBase.Namespace; import mil.dod.th.core.remote.proto.RemoteBase.TerraHarvestMessage; import mil.dod.th.core.remote.proto.SharedMessages; /** * @author jmiller * */ public final class DataStreamStoreNamespaceUtils { /** * Timeout value used to wait for message responses. */ private static final int TIMEOUT = 5000; /** * Private constructor to prevent instantiation. */ private DataStreamStoreNamespaceUtils() { } /** * Enable archiving for a given stream profile instance. */ public static void enableArchiving(Socket socket, SharedMessages.UUID uuid, long heartbeatPeriod, boolean errorExpected) throws IOException { MessageListener listener = new MessageListener(socket); EnableArchivingRequestData request = EnableArchivingRequestData.newBuilder(). setStreamProfileUuid(uuid). setUseSourceBitrate(true). setHeartbeatPeriod(heartbeatPeriod). setDelay(0L).build(); TerraHarvestMessage message = DataStreamStoreNamespaceUtils.createDataStreamStoreNamespaceMessage( DataStreamStoreMessageType.EnableArchivingRequest, request); message.writeDelimitedTo(socket.getOutputStream()); if (errorExpected) { listener.waitForMessage(Namespace.Base, BaseMessageType.GenericErrorResponse, TIMEOUT); } else { listener.waitForMessage(Namespace.DataStreamStore, DataStreamStoreMessageType.EnableArchivingResponse, TIMEOUT); } } /** * Disable archiving for a given stream profile instance. */ public static void disableArchiving(Socket socket, SharedMessages.UUID uuid, boolean errorExpected) throws IOException { MessageListener listener = new MessageListener(socket); DisableArchivingRequestData request = DisableArchivingRequestData.newBuilder(). setStreamProfileUuid(uuid).build(); TerraHarvestMessage message = DataStreamStoreNamespaceUtils.createDataStreamStoreNamespaceMessage( DataStreamStoreMessageType.DisableArchivingRequest, request); message.writeDelimitedTo(socket.getOutputStream()); if (errorExpected) { listener.waitForMessage(Namespace.Base, BaseMessageType.GenericErrorResponse, TIMEOUT); } else { listener.waitForMessage(Namespace.DataStreamStore, DataStreamStoreMessageType.DisableArchivingResponse, TIMEOUT); } } public static void clientAck(Socket socket, SharedMessages.UUID uuid, boolean errorExpected) throws IOException { MessageListener listener = new MessageListener(socket); ClientAckData request = ClientAckData.newBuilder(). setStreamProfileUuid(uuid).build(); TerraHarvestMessage message = DataStreamStoreNamespaceUtils.createDataStreamStoreNamespaceMessage( DataStreamStoreMessageType.ClientAck, request); message.writeDelimitedTo(socket.getOutputStream()); if (errorExpected) { listener.waitForMessage(Namespace.Base, BaseMessageType.GenericErrorResponse, TIMEOUT); } } public static List<DateRange> getArchivePeriods(Socket socket, SharedMessages.UUID uuid, boolean errorExpected) throws IOException { MessageListener listener = new MessageListener(socket); GetArchivePeriodsRequestData request = GetArchivePeriodsRequestData.newBuilder(). setStreamProfileUuid(uuid).build(); TerraHarvestMessage message = DataStreamStoreNamespaceUtils.createDataStreamStoreNamespaceMessage( DataStreamStoreMessageType.GetArchivePeriodsRequest, request); message.writeDelimitedTo(socket.getOutputStream()); if (errorExpected) { listener.waitForMessage(Namespace.Base, BaseMessageType.GenericErrorResponse, TIMEOUT); return null; } else { DataStreamStoreNamespace response = (DataStreamStoreNamespace)listener.waitForMessage( Namespace.DataStreamStore, DataStreamStoreMessageType.GetArchivePeriodsResponse, TIMEOUT); GetArchivePeriodsResponseData dataResponse = GetArchivePeriodsResponseData.parseFrom(response.getData()); return dataResponse.getDateRangeList(); } } public static TerraHarvestMessage createDataStreamStoreNamespaceMessage(final DataStreamStoreMessageType type, final Message message) { DataStreamStoreNamespace.Builder dataStreamStoreMessageBuilder = DataStreamStoreNamespace.newBuilder(). setType(type); if (message != null) { dataStreamStoreMessageBuilder.setData(message.toByteString()); } TerraHarvestMessage thMessage = TerraHarvestMessageHelper.createTerraHarvestMsg( Namespace.DataStreamStore, dataStreamStoreMessageBuilder); return thMessage; } }
Java
CL
71a4843afb10e52e26838f526cc83467d8a6c93ef8605b98aad0e76910811279
package io.compgen.ngsutils.support.stats; import static org.apache.commons.math3.util.CombinatoricsUtils.factorialDouble; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.math3.distribution.ChiSquaredDistribution; import io.compgen.common.ComparablePair; import io.compgen.common.Pair; public class StatUtils { public static final double log2Factor = Math.log(2); /** * Based on a 2x2 contingency table: * * Group 1 Group 2 * ----------|---------- * Condition 1 A | B * ----------|---------- * Condition 2 C | D * ----------|---------- * * @param A * @param B * @param C * @param D * @return Fisher's exact p-value for the given table (does not take in to account more or less extreme tables) */ public static double fisherExact(int A, int B, int C, int D) { double AB = factorialDouble(A+B); double CD = factorialDouble(C+D); double AC = factorialDouble(A+C); double BD = factorialDouble(B+D); double Afact = factorialDouble(A); double Bfact = factorialDouble(B); double Cfact = factorialDouble(C); double Dfact = factorialDouble(D); double Nfact = factorialDouble(A+B+C+D); return (AB * CD * AC * BD) / (Afact * Bfact * Cfact * Dfact * Nfact); } // public static double poissonMean(int lambda, int n, float mu) { // return ppois(n, (int) Math.floor(lambda*mu)); // } // public static double dpois(int x, int lambda) { // return new PoissonDistribution(lambda).probability(x); // //return (Math.pow(lambda, x) / CombinatoricsUtils.factorialDouble(x)) * Math.exp(-1*lambda); // } // public static double ppois(int x, int lambda) { // return new PoissonDistribution(lambda).cumulativeProbability(x); //// double acc = 0.0; //// for (int i=0; i<=x; i++) { //// acc += (Math.pow(lambda, i) / CombinatoricsUtils.factorialDouble(i)); //// } //// return acc * Math.exp(-lambda); // } // /* Use CombinatoricsUtils.factorial instead private static Map<Integer, Long> factorialMemoize = new HashMap<Integer, Long> (); public static long factorial(int n) { if (n == 0) { return 1; } if (factorialMemoize.containsKey(n)) { return factorialMemoize.get(n); } long acc = 1; for (int i=1; i<=n; i++) { acc *= i; } factorialMemoize.put(n, acc); return acc; } */ public static double[] bonferroni(double[] pvalues) { double[] out = new double[pvalues.length]; for (int i=0; i<pvalues.length; i++) { out[i] = pvalues[i] * pvalues.length; } return arrayMin(1, out); } /** * Correct p-values for multiple testing using Benjamini-Hochberg * * Benjamini, Yoav; Hochberg, Yosef (1995). "Controlling the false discovery rate: a practical and powerful approach to multiple testing". Journal of the Royal Statistical Society, Series B 57 (1): 289–300. MR 1325392 * * See also: http://stackoverflow.com/questions/7450957/how-to-implement-rs-p-adjust-in-python * * R-code: * BH = { * i <- lp:1L * o <- order(p, decreasing = TRUE) * ro <- order(o) * pmin(1, cummin( n / i * p[o] ))[ro] * }, * */ public static double[] benjaminiHochberg(double[] pvalues) { int n = pvalues.length; int[] order = sortOrder(pvalues, true); int[] ro = sortOrder(order); double[] tmp = new double[n]; for (int i=0; i<n; i++) { int rank = n - i; tmp[i] = (double) n / rank * pvalues[order[i]-1]; } tmp = arrayMin(1, cummulativeMin(tmp)); double[] out = new double[n]; for (int i=0; i<n; i++) { out[i] = tmp[ro[i]-1]; } return out; } public static int[] sortOrder(double[] values) { return sortOrder(values, false); } /** * Returns the indexes for a correct sorted order (Ascending or descending) * * Note: this operates like the R method "order" * @param values * @param decreasing * @return */ public static int[] sortOrder(double[] values, boolean decreasing) { List<ComparablePair<Double,Integer>> vals = new ArrayList<ComparablePair<Double, Integer>>(); for (int i=0; i< values.length; i++) { vals.add(new ComparablePair<Double, Integer>(values[i], i)); } if (decreasing) { Collections.sort(vals, Collections.reverseOrder()); } else { Collections.sort(vals); } int[] ranks = new int[values.length]; for (int i=0; i<values.length; i++) { ranks[i] = vals.get(i).two+1; } return ranks; } public static int[] sortOrder(int[] values) { return sortOrder(values, false); } public static int[] sortOrder(int[] values, boolean decreasing) { List<ComparablePair<Integer,Integer>> vals = new ArrayList<ComparablePair<Integer, Integer>>(); for (int i=0; i< values.length; i++) { vals.add(new ComparablePair<Integer, Integer>(values[i], i)); } if (decreasing) { Collections.sort(vals, Collections.reverseOrder()); } else { Collections.sort(vals); } int[] ranks = new int[values.length]; for (int i=0; i<values.length; i++) { ranks[i] = vals.get(i).two+1; } return ranks; } /** * returns the cummulative-minima for an array * @param pvalues * @return */ public static double[] cummulativeMin(double[] vals) { double[] out = new double[vals.length]; double min = Double.MAX_VALUE; for (int i=0; i< vals.length; i++) { if (i ==0 || vals[i] < min) { min = vals[i]; } out[i] = min; } return out; } /** * returns the cummulative-maxima for an array * @param pvalues * @return */ public static double[] cummulativeMax(double[] vals) { double[] out = new double[vals.length]; double max = Double.MIN_VALUE; for (int i=0; i< vals.length; i++) { if (i ==0 || vals[i] > max) { max = vals[i]; } out[i] = max; } return out; } /** * returns the cummulative-sum for an array * @param pvalues * @return */ public static double[] cummulativeSum(double[] vals) { double[] out = new double[vals.length]; double acc = 0; for (int i=0; i< vals.length; i++) { acc += vals[i]; out[i] = acc; } return out; } /** * Applies a min value to all elements in an array * @param values * @return */ public static double[] arrayMin(double minVal, double[] vals) { double[] out = new double[vals.length]; for (int i=0; i< vals.length; i++) { out[i] = Math.min(minVal, vals[i]); } return out; } /** * Applies a max value to all elements in an array * @param values * @return */ public static double[] arrayMax(double maxVal, double[] vals) { double[] out = new double[vals.length]; for (int i=0; i< vals.length; i++) { out[i] = Math.max(maxVal, vals[i]); } return out; } /** * Are the values in the double[] arrays equal (within a given delta) * @param one * @param two * @param delta * @return */ public static boolean deltaEquals(double[] one, double[] two, double delta) { if (one.length != two.length) { return false; } for (int i=0; i<one.length; i++) { if (Math.abs(one[i]-two[i]) > delta) { return false; } } return true; } public static double median(int[] vals) { int[] copy = Arrays.copyOf(vals, vals.length); Arrays.sort(copy); if (copy.length % 2 == 0) { int acc = copy[copy.length / 2]; acc += copy[(copy.length / 2)-1]; return acc / 2.0; } else { return copy[copy.length / 2]; } } public static double median(double[] vals) { double[] copy = Arrays.copyOf(vals, vals.length); Arrays.sort(copy); if (copy.length % 2 == 0) { double acc = copy[copy.length / 2]; acc += copy[(copy.length / 2)-1]; return acc / 2.0; } else { return copy[copy.length / 2]; } } public static double log2(double val) { return Math.log(val) / log2Factor; } public static double[] log2(double[] vals) { double[] out = new double[vals.length]; for (int i=0; i<vals.length; i++) { out[i] = log2(vals[i]); } return out; } public static double log2(int val) { return Math.log(val) / log2Factor; } public static double[] log2(int[] vals) { double[] out = new double[vals.length]; for (int i=0; i<vals.length; i++) { out[i] = log2(vals[i]); } return out; } public static double medianInteger(List<Integer> vals) { List<Integer> copy = new ArrayList<Integer>(vals); Collections.sort(copy); if (copy.size() % 2 == 0) { int acc = copy.get(copy.size() / 2); acc += copy.get((copy.size() / 2) - 1); return acc / 2.0; } else { return copy.get(copy.size() / 2); } } public static double medianDouble(List<Double> vals) { List<Double> copy = new ArrayList<Double>(vals); Collections.sort(copy); if (copy.size() % 2 == 0) { Double acc = copy.get(copy.size() / 2); acc += copy.get((copy.size() / 2) - 1); return acc / 2.0; } else { return copy.get(copy.size() / 2); } } public static long sum(int[] vals) { long acc = 0; for (int i=0; i< vals.length; i++) { acc += vals[i]; } return acc; } public static class MeanStdDev { public final double mean; public final double stddev; private MeanStdDev(double mean, double stddev) { this.mean = mean; this.stddev = stddev; } } public static MeanStdDev calcMeanStdDev(double[] vals) { double acc = 0.0; int count = 0; for (int i=0; i< vals.length; i++) { acc += vals[i]; count += 1; } double mean = acc / count; acc = 0.0; for (int i=0; i< vals.length; i++) { acc += Math.pow(vals[i]-mean, 2); } return new MeanStdDev(mean, Math.sqrt(acc * 1/(count - 1))); } public static MeanStdDev calcMeanStdDev(int[] vals) { long acc = 0; int count = 0; for (int i=0; i< vals.length; i++) { acc += vals[i]; count += 1; } double mean = ((double)acc) / count; acc = 0; for (int i=0; i< vals.length; i++) { acc += Math.pow(vals[i]-mean, 2); } return new MeanStdDev(mean, Math.sqrt(acc * 1/(count - 1))); } // Chi Squared dist w/ 1 d.f. (for pvalue) private static ChiSquaredDistribution csd = null; /** * https://en.wikipedia.org/wiki/Yates%27s_correction_for_continuity * @param vcfRef * @param vcfAlt * @param ref * @param alt * @return */ public static double calcProportionalPvalue(int a, int b, int c, int d) { if (csd == null) { csd = new ChiSquaredDistribution(1); } double Na = a + b; double Nb = c + d; double Ns = a + c; double Nf = b + d; double N = a + b + c + d; double num = N * Math.pow(Math.max(0, Math.abs(a*d - b*c) - N/2),2); double dem = Ns * Nf * Na * Nb; // System.err.println("N="+N+", num="+num+", dem="+dem); double chi = num / dem; double pvalue=1-csd.cumulativeProbability(chi); // System.err.println("a="+a+", b="+b+", c="+c+", d="+d+", X="+chi+", pval="+ pvalue); return pvalue; } /** * Give a list of Double/Integer pairs, treat the double as a value and the integer as the * number of times the double is present in a list. * * Example: * The mean of: [(3,2), (1,2), (4,1)] should be ((3 * 2) + (1*2) + (4*1)) / 5 * * @param vals * @return */ public static double meanSpan(List<Pair<Double, Integer>> vals) { double acc = 0.0; int count = 0; for (Pair<Double, Integer> val: vals) { acc += (val.one * val.two); count += val.two; } return acc / count; } public static double meanSpan(double[] dvals, int[] sizes) { if (dvals.length != sizes.length) { throw new RuntimeException("Mismatched vals/sizes!"); } double acc = 0.0; int count = 0; for (int i=0; i< dvals.length; i++) { acc += (dvals[i] * sizes[i]); count += sizes[i]; } return acc / count; } /** * Return the median value for a value/size pair * * Note: we call this from the double[], int[] version as well so we can do a paired sort on the * tuple. * * @param vals * @return */ public static double medianSpan(List<Pair<Double, Integer>> spanVals) { if (spanVals == null || spanVals.size() == 0) { return Double.NaN; } // Make a copy of the list... we need to sort it and don't want to alter the incoming list. List<Pair<Double, Integer>> vals = new ArrayList<Pair<Double, Integer>>(spanVals.size()); for (Pair<Double, Integer> tup : spanVals) { vals.add(new Pair<Double, Integer>(tup.one, tup.two)); } return medianSpanInplace(vals); } public static double medianSpan(double[] dvals, int[] sizes) { if (dvals.length != sizes.length) { throw new RuntimeException("Mismatched vals/sizes!"); } List<Pair<Double, Integer>> vals = new ArrayList<Pair<Double, Integer>>(dvals.length); for (int i=0; i<dvals.length; i++) { vals.add(new Pair<Double, Integer>(dvals[i], sizes[i])); } return medianSpanInplace(vals); } /** * This method will calculate the median using the argument list in-place (so use it after * creating a copy in a public method) * * @param vals * @return */ private static double medianSpanInplace(List<Pair<Double, Integer>> vals) { vals.sort(new Comparator<Pair<Double, Integer>>() { @Override public int compare(Pair<Double, Integer> o1, Pair<Double, Integer> o2) { return Double.compare(o1.one, o2.one); }}); int total = 0; for (Pair<Double, Integer> tup : vals) { total += tup.two; } if (total % 2 == 0) { int mid1 = total / 2; int mid2 = (total / 2) + 1; int cur = 0; double val1 = Double.NaN; boolean found = false; for (Pair<Double, Integer> tup : vals) { cur += tup.two; if (!found && cur >= mid1) { found = true; val1 = tup.one; } if (cur >= mid2) { return (val1 + tup.one) / 2; } } } else { int mid = (total / 2) + 1; int cur = 0; for (Pair<Double, Integer> tup : vals) { cur += tup.two; if (cur >= mid) { return tup.one; } } } return Double.NaN; } public static double max(double[] dvals) { double thres = dvals[0]; for (int i=1; i<dvals.length; i++) { if (dvals[i] > thres) { thres = dvals[i]; } } return thres; } public static double min(double[] dvals) { double thres = dvals[0]; for (int i=1; i<dvals.length; i++) { if (dvals[i] < thres) { thres = dvals[i]; } } return thres; } // public static class Trendline { // public final double slope; // public final double intercept; // public final double mse; // public final double rsquare; // // public Trendline(double slope, double intercept, double mse, double rsquare) { // this.slope = slope; // this.intercept = intercept; // this.mse = mse; // this.rsquare = rsquare; // } // } // // public static Trendline linearRegression(double[] x, double[] y) { // SimpleRegression reg = new SimpleRegression(); // for (int i=0; i<x.length; i++) { // reg.addData(x[i], y[i]); // } // // return new Trendline(reg.getSlope(), reg.getIntercept(), reg.getMeanSquareError(), reg.getRSquare()); // } // }
Java
CL
67cb9144305226f4710ce14d77e2d5ab5b7b73f6fd0663586e1f18a982e881e4
package edu.illinois.cs.cogcomp.indsup.inference; import edu.illinois.cs.cogcomp.indsup.learning.WeightVector; /** * The function that is used for solving the Latent Structural SVM --- similar * to (Yu, Joachims ICML09). However, we used the square-hinge loss here so that * the optimization procedure is in fact quite different. * <p> * * Denote x as the input, h as the hidden structure, and y as the output * structure. If you want to implement the this type of Latent Structural SVM, * you need to implement three inference procedures (If you extend this class, * the java compiler will ask you to implement this three methods in order to * prevent compilation error): * <p> * * (1) * {@link AbstractLatentLossSensitiveStructureFinder#getBestStructure(WeightVector, IInstance)} * <p> * * Given a example, find the best structure. Here, you want to solve * <p> * * \max_{h,y} w^T \phi(x,h,y) * <p> * * Note that different from the standard Structural SVM, your output structure * now contains both (y,h). This is the procedure you want to use at test time. * <p> * * (2) * {@link AbstractLatentLossSensitiveStructureFinder#getLossSensitiveBestStructure(WeightVector, IInstance, IStructure)} * <p> * <p> * * Given a example and the gold output structure y, solve the loss sensitive * procedure. Here, you want to solve * <p> * * \max_{h,y} w^T \phi(x,h,y) + \delta(h,y,y*) * <p> * * The procedure will be used internally by the learning algorithm. * <p> * * (3) * {@link AbstractLatentLossSensitiveStructureFinder#getBestLatentStructure(WeightVector, IInstance, IStructure)} * <p> * * Given a example and the gold output structure y*, find the best latent * structure with respect to this gold structure. More precisely, * <p> * * \max_{h} w^T \phi(x,h,y*) * <p> * * Note that you should return a IStructure with (\hat{h}, y^*) where \hat{h} is * the solution of the above problem. The procedure will be used internally by * the learning algorithm. * <p> * * <tt> Make sure that you understand the differences and relations between these three procedures before using this class </tt>. * <p> * * @author Ming-Wei Chang * */ public abstract class AbstractLatentLossSensitiveStructureFinder extends AbstractLossSensitiveStructureFinder { private static final long serialVersionUID = 1L; /** * The function that find the best "latent structure" given a gold output * structure of a given example. * <p> * * \max_{h} w^T \phi(x,h,y*) * <p> * * @param weight * The weight vector * @param ins * Input example * @param goldStructure * The gold output structure of this example * @return The best latent structure with respect to this gold structure. * @throws Exception */ public abstract IStructure getBestLatentStructure(WeightVector weight, IInstance ins, IStructure goldStructure) throws Exception; }
Java
CL
3d51a414cdd66d6e0dd2f009ab9877b8970efa400061dbd22ee69def8a9bf8e1
package org.tinymediamanager.core.movie; import static org.assertj.core.api.Assertions.assertThat; import static org.tinymediamanager.core.movie.MovieEdition.DIRECTORS_CUT; import static org.tinymediamanager.core.movie.MovieEdition.EXTENDED_EDITION; import static org.tinymediamanager.core.movie.MovieEdition.IMAX; import static org.tinymediamanager.core.movie.MovieEdition.NONE; import static org.tinymediamanager.core.movie.MovieEdition.SPECIAL_EDITION; import static org.tinymediamanager.core.movie.MovieEdition.THEATRICAL_EDITION; import static org.tinymediamanager.core.movie.MovieEdition.UNCUT; import static org.tinymediamanager.core.movie.MovieEdition.UNRATED; import org.junit.Test; /** * @author Manuel Laggner */ public class MovieEditionTest { @Test public void testMovieEditionRegexp() { // DIRECTORS_CUT assertThat(parse("Halloween.Directors.Cut.German.AC3D.HDRip.x264-xx")).isEqualTo(DIRECTORS_CUT); assertThat(parse("Saw.Directors.Cut.2004.French.HDRiP.H264-xx")).isEqualTo(DIRECTORS_CUT); assertThat(parse("The.Grudge.Unrated.Directors.Cut.2004.AC3D.HDRip.x264")).isEqualTo(DIRECTORS_CUT); assertThat(parse("Straight Outta Compton Directors Cut 2015 German AC3 BDRiP XViD-abc")).isEqualTo(DIRECTORS_CUT); // EXTENDED assertThat(parse("Lord.Of.The.Rings.Extended.Edition")).isEqualTo(EXTENDED_EDITION); assertThat(parse("Vikings.S03E10.EXTENDED.720p.BluRay.x264-xyz")).isEqualTo(EXTENDED_EDITION); assertThat(parse("Taken.3.EXTENDED.2014.BRRip.XviD.AC3-xyz")).isEqualTo(EXTENDED_EDITION); assertThat(parse("Coyote.Ugly.UNRATED.EXTENDED.CUT.2000.German.AC3D.HDRip.x264")).isEqualTo(EXTENDED_EDITION); assertThat(parse("Project X EXTENDED CUT Italian AC3 BDRip XviD-xxx")).isEqualTo(EXTENDED_EDITION); // THEATRICAL assertThat(parse("The.Lord.of.the.Rings.The.Return.of.the.King.THEATRICAL.EDITION.2003.720p.BrRip.x264.mp4")).isEqualTo(THEATRICAL_EDITION); assertThat(parse("Movie.43.2013.American.Theatrical.Version.DVDRip.XViD.avi")).isEqualTo(THEATRICAL_EDITION); // UNRATED assertThat(parse("Get.Hard.2015.UNRATED.720p.BluRay.DTS.x264-xyz")).isEqualTo(UNRATED); assertThat(parse("Curse.Of.Chucky.2013.UNRATED.1080p.WEB-DL.H264-xyz")).isEqualTo(UNRATED); assertThat(parse("Men.Of.War.UNRATED.1994.AC3.HDRip.x264")).isEqualTo(UNRATED); assertThat(parse("Men Of War UNRATED 1994 AC3 HDRip x264")).isEqualTo(UNRATED); // UNCUT assertThat(parse("12 Monkeys [Uncut] [3D]")).isEqualTo(UNCUT); assertThat(parse("Creep.UNCUT.2004.AC3.HDTVRip.x264")).isEqualTo(UNCUT); assertThat(parse("Dragonball.Z.COMPLETE.Dutch.Dubbed.UNCUT.1989.ANiME.WS.DVDRiP.XviD")).isEqualTo(UNCUT); assertThat(parse("Rest Stop Dead Ahead 2006 UNCUT 720p BluRay H264 AAC-xxx")).isEqualTo(UNCUT); // IMAX assertThat(parse("IMAX.Sharks.2004.BDRip.XviD-xyz")).isEqualTo(IMAX); assertThat(parse("IMAX.Sea.Rex.GERMAN.DOKU.BDRip.XviD-xyz")).isEqualTo(IMAX); assertThat(parse("IMAX.Alaska.Spirit.of.the.Wild.1997.FRENCH.AC3.DOKU.DL.720p.BluRay.x264-xxx")).isEqualTo(IMAX); assertThat(parse("The.Hunger.Games.Catching.Fire.2013.IMAX.720p.BluRay.H264.AAC-xxx")).isEqualTo(IMAX); assertThat(parse("Transformers Revenge Of The Fallen 2009 IMAX 1080p BluRay x264-abc")).isEqualTo(IMAX); // SPECIAL_EDITION assertThat(parse("Blade.Runner.The.Final.Cut.1982.BluRay.1080p")).isEqualTo(SPECIAL_EDITION); // NORMAL assertThat(parse("Boomerang.1992.Incl.Directors.Commentary.DVDRip.x264-xyz")).isEqualTo(NONE); assertThat(parse("Unrated.The.Movie.2009.720p.BluRay.x264-xyz")).isEqualTo(NONE); assertThat(parse("The Lion Guard Return Of The Roar 2015 DVDRip x264-aaa")).isEqualTo(NONE); assertThat(parse("Spies 1928 720p BluRay x264-hhh")).isEqualTo(NONE); assertThat(parse("Rodeo Girl 2016 DVDRip x264-yxc")).isEqualTo(NONE); assertThat(parse("Climax")).isEqualTo(NONE); } private MovieEdition parse(String name) { return MovieEdition.getMovieEditionFromString(name); } }
Java
CL
e4670e37fe75292d47bf84cb1978e2fa5cb4fd697a1e568287f246f525eff9eb
package com.weiquding.netty.learning.netty.httpjson.client; import com.weiquding.netty.learning.netty.httpjson.domain.Order; import com.weiquding.netty.learning.netty.httpjson.handler.HttpJsonRequestEncoder; import com.weiquding.netty.learning.netty.httpjson.handler.HttpJsonResponseDecoder; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpResponseDecoder; import java.net.InetSocketAddress; /** * @author wubai * @date 2018/9/22 20:15 */ public class HttpJsonClient { public static void main(String[] args) throws InterruptedException { new HttpJsonClient().connect(8080); } private void connect(int port) throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .option(ChannelOption.TCP_NODELAY, true) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast("http-decoder", new HttpResponseDecoder()); socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); socketChannel.pipeline().addLast("json-decoder", new HttpJsonResponseDecoder(Order.class, true)); socketChannel.pipeline().addLast("http-encoder", new HttpRequestEncoder()); socketChannel.pipeline().addLast("json-encoder", new HttpJsonRequestEncoder()); socketChannel.pipeline().addLast("jsonClientHandler", new HttpJsonClientHandler()); } }); ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(port)).sync(); channelFuture.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } }
Java
CL
89b8e45a196e0af9056a622351e211b0bc2dbb32953b24a70d7204b0fa4dd55c
/* * This file is part of Quark Framework, licensed under the APACHE License. * * Copyright (c) 2014-2016 Agustin L. Alvarez <wolftein1@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 ar.com.quark.render.storage; import ar.com.quark.render.Render; /** * <code>VertexFormat</code> enumerate {@link Vertex} type(s). */ public enum VertexFormat { /** * Represent a signed 8-bit integer. */ BYTE(Render.GLES2.GL_BYTE, 0x01), /** * Represent an unsigned 8-bit integer. */ UNSIGNED_BYTE(Render.GLES2.GL_UNSIGNED_BYTE, 0x01), /** * Represent a signed 16-bit integer. */ SHORT(Render.GLES2.GL_SHORT, 0x02), /** * Represent an unsigned 16-bit integer. */ UNSIGNED_SHORT(Render.GLES2.GL_UNSIGNED_SHORT, 0x02), /** * Represent a signed 32-bit integer. */ INT(Render.GLES3.GL_INT, 0x04), /** * Represent an unsigned 32-bit integer. */ UNSIGNED_INT(Render.GLES3.GL_UNSIGNED_INT, 0x04), /** * Represent a IEEE-754 single-precision floating point number. */ FLOAT(Render.GLES2.GL_FLOAT, 0x04), /** * Represent a IEEE-754 half-precision floating point number. */ HALF_FLOAT(Render.GLES3.GL_HALF_FLOAT, 0x02); public final int eValue; public final int eLength; /** * <p>Constructor</p> */ VertexFormat(int value, int length) { this.eValue = value; this.eLength = length; } }
Java
CL
c54d4f92142b48f0ebbaf41f91a6a2e9a6497fd04562e904d5a7142a1c0fdc0c
package com.webcheckers.model; /** * A class to represent the position of a space on a checkers board. * * @author Andrew Frank, ajf8248@rit.edu */ public class Position { private int row; private int cell; /** * Instantiates a new Position with a row and cell(column) on the checkers board. * * @param row: The row of the checkers board that this Position is in * @param cell: The column of the checkers board that this Position is in */ public Position(int row, int cell) { this.row = row; this.cell = cell; } /** * Accessor for the row this Position is in. * * @return this Position's row. */ public int getRow() { return this.row; } /** * Accessor for the column this Position is in. * * @return this Position's column. */ public int getCell() { return this.cell; } }
Java
CL
7a68548ef3342da29dca998f1c680ec14202c23e96527dc909ec276a4c8b47ec
/******************************************/ /* WARNING: GENERATED FILE - DO NOT EDIT! */ /******************************************/ package imp.preferences; import org.eclipse.swt.widgets.TabFolder;import org.eclipse.imp.preferences.IPreferencesService;import org.eclipse.imp.preferences.PreferencesInitializer;import org.eclipse.imp.preferences.PreferencesTab;import org.eclipse.imp.preferences.TabbedPreferencesPage;import workspace.Activator; /** * A preference page class. */ public class HaxePreferencePage extends TabbedPreferencesPage { public HaxePreferencePage() { super(); prefService = Activator.getInstance().getPreferencesService(); } protected PreferencesTab[] createTabs(IPreferencesService prefService, TabbedPreferencesPage page, TabFolder tabFolder) { PreferencesTab[] tabs = new PreferencesTab[1]; HaxeInstanceTab instanceTab = new HaxeInstanceTab(prefService); instanceTab.createTabContents(page, tabFolder); tabs[0] = instanceTab; return tabs; } public PreferencesInitializer getPreferenceInitializer() { return new HaxeInitializer(); } }
Java
CL
ab908977413814b666232346b691607783309979d466c4c19caf4837b3b9d187
/* * Copyright (c) 2002-2010 The Regents of the University of California. * All rights reserved. * * '$Author: welker $' * '$Date: 2010-05-05 22:21:26 -0700 (Wed, 05 May 2010) $' * '$Revision: 24234 $' * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the above * copyright notice and the following two paragraphs appear in all copies * of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. * */ package org.geon; import ptolemy.actor.TypedAtomicActor; import ptolemy.actor.TypedIOPort; import ptolemy.data.IntToken; import ptolemy.data.StringToken; import ptolemy.data.type.BaseType; import ptolemy.kernel.CompositeEntity; import ptolemy.kernel.util.IllegalActionException; import ptolemy.kernel.util.NameDuplicationException; ////////////////////////////////////////////////////////////////////////// //// DiagramTransitions /** * This is a domain specific actor that holds all the information about rock * naming diagrams and the transtions between them. It transfers the data along * with initial information to a process that loops over the rock data. (As * currently there are only two digitized diagram, there is no actual * transitions table yet. The actor will be extended once more diagrams are * available). * * @author Efrat Jaeger * @version $Id: DiagramTransitions.java 24234 2010-05-06 05:21:26Z welker $ * @since Ptolemy II 3.0.2 */ public class DiagramTransitions extends TypedAtomicActor { /** * Construct an actor with the given container and name. * * @param container * The container. * @param name * The name of this actor. * @exception IllegalActionException * If the actor cannot be contained by the proposed * container. * @exception NameDuplicationException * If the container already has an actor with this name. */ public DiagramTransitions(CompositeEntity container, String name) throws NameDuplicationException, IllegalActionException { super(container, name); diagramsAndTransitions = new TypedIOPort(this, "diagramsAndTransitions", false, true); diagramsAndTransitions.setTypeEquals(BaseType.STRING); index = new TypedIOPort(this, "index", false, true); index.setTypeEquals(BaseType.INT); _attachText("_iconDescription", "<svg>\n" + "<rect x=\"-25\" y=\"-20\" " + "width=\"50\" height=\"40\" " + "style=\"fill:yellow\"/>\n" + "<polygon points=\"-15,-2 0,-15 15,-2 11,15 -11,15\" " + "style=\"fill:white\"/>\n" + "</svg>\n"); } // ///////////////////////////////////////////////////////////////// // // ports and parameters //// /** * All the diagrams and transitions information. */ public TypedIOPort diagramsAndTransitions; /** * A reference to the initial diagram. */ public TypedIOPort index; // ///////////////////////////////////////////////////////////////// // // public methods //// /** * Provide the diagrams and transitions between them along with a refernce * to first diagram. * * @exception IllegalActionException * If there's no director. */ public void fire() throws IllegalActionException { // FIX ME: need to implement the transitions table as soon as we have // more diagrams digitized. diagramsAndTransitions.broadcast(new StringToken( "Diagrams and Transitions")); index.broadcast(new IntToken(1)); } /** * Return false to indicate that the process has finished. * * @exception IllegalActionException * If thrown by the super class. */ public boolean postfire() throws IllegalActionException { return false; } }
Java
CL
29c3f2a657c2369431b0c6bc8cf12419d0f3e06d55b0ba35ca1cdd950d13002a
package juglr; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Asynchronously forward incoming messages to a collection of delegates * based on a given strategy. For cases where you want to forward messages * to a single actor out of a given set see {@link DelegatingActor}. * * @see DelegatingActor */ public class MulticastActor extends Actor { /** * Used by {@link MulticastActor} to determine which addresses * to relay a given message to */ public static interface Strategy { /** * Get an iterator over the recipients of {@code msg} * @param msg the message to find the recipeints for * @return and iterator over the addresses to send {@code msg} to */ public Iterator<Address> recipients(Message msg); /** * Make sure that all actors related to this strategy have their * {@link Actor#start} method invoked. Note that it is the * responsibility of the strategy to also start any actors that may * be created after this method call */ public void start(); } private static class ForwardToAllStrategy implements Strategy { private List<Address> delegates; private ForwardToAllStrategy() { delegates = new LinkedList<Address>(); } public ForwardToAllStrategy(Iterable<Address> delegates) { this.delegates = new LinkedList<Address>(); for (Address delegate : delegates) { this.delegates.add(delegate); } } public ForwardToAllStrategy(Address... delegates) { this(Arrays.asList(delegates)); } static ForwardToAllStrategy newForActors(Iterable<Actor> delegates) { ForwardToAllStrategy self = new ForwardToAllStrategy(); for (Actor delegate : delegates) { self.delegates.add(delegate.getAddress()); } return self; } static ForwardToAllStrategy newForActors(Actor... delegates) { return newForActors(Arrays.asList(delegates)); } public Iterator<Address> recipients(Message msg) { return delegates.iterator(); } public void start() { for (Address delegate : delegates) { delegate.getBus().start(delegate); } } } protected Strategy strategy; private MulticastActor() { } /** * Create a new multicast actor forwarding all incoming messages to all * members of {@code delegates}. * * @param delegates the collection of delegates to forward all messages to */ public MulticastActor (Address... delegates) { strategy = new ForwardToAllStrategy(delegates); } /** * Create a new multicast actor forwarding all incoming messages to all * members of {@code delegates}. * * @param delegates the collection of delegates to forward all messages to */ public MulticastActor (Iterable<Address> delegates) { strategy = new ForwardToAllStrategy(delegates); } /** * Create a new multicast actor forwarding all incoming messages to all * delegates determined by a given {@link Strategy}. * * @param strategy the {@link Strategy} used to determine the message * recipients */ public MulticastActor (Strategy strategy) { this.strategy = strategy; } public MulticastActor(Actor... delegates) { strategy = ForwardToAllStrategy.newForActors(delegates); } public static MulticastActor newForActors(Iterable<Actor> delegates) { MulticastActor self = new MulticastActor(); self.strategy = ForwardToAllStrategy.newForActors(delegates); return self; } public static MulticastActor newForActors(Actor... delegates) { return newForActors(Arrays.asList(delegates)); } /** * Asynchronously send {@code msg} to all addresses determined by calling * {@link Strategy#recipients}. * @param msg the incoming message */ @Override public void react(Message msg) { if (!validate(msg)) return; if (msg.getReplyTo() == null) { msg.setReplyTo(msg.getSender()); } /* Note that send() rewrites the sender, * but keeps the replyTo intact if it's set */ Iterator<Address> recipients = strategy.recipients(msg); while (recipients.hasNext()) { send(msg, recipients.next()); } } /** * Invoke {@link Strategy#start} */ @Override public void start() { strategy.start(); } /** * If this method returns {@code false} {@code msg} will not be sent * along to the delegates. The default implementation always return * {@code true} - subclasses should override this method with their own * validation logic. * @param msg the message to validate * @return {@code true} if the message is good and should be forwarded to * the delegates and {@code false} if the message should be blocked */ public boolean validate(Message msg) { return true; } }
Java
CL
32a81b0e769ab8a24805e6bfeab83b61dbd17b51b3dd04b22e656df4527d4219
package ru.semi.services; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import ru.semi.entities.TaskTime; import ru.semi.repositories.TaskTimeRepository; import ru.semi.dto.TaskTimeDto; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import static java.util.Objects.nonNull; import static ru.semi.config.Constants.DATE_TIME_FORMAT; @Slf4j @AllArgsConstructor @Service public class TaskTimeCalculatorServiceImpl implements TaskTimeCalculatorService { private final TaskTimeRepository taskTimeRepository; private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT); @Override public String calculateTaskTime(TaskTimeDto taskTimeDto) { log.info("taskTimeDto: {}", taskTimeDto); int hours = taskTimeDto.getHours(); LocalDateTime fromTime ; String processInstanceId = taskTimeDto.getProcessInstanceId(); String parentTaskId = taskTimeDto.getParentTaskId(); log.info("parent task Id: {}", parentTaskId ); String taskComplexityName = taskTimeDto.getTaskComplexityName(); String parentProcessInstanceId = taskTimeDto.getParentProcessInstanceId(); if (nonNull(parentTaskId)) { Optional<TaskTime> previous = taskTimeRepository.findFirstByProcessIdAndTaskIdAndParentProcessInstanceId(processInstanceId, parentTaskId, parentProcessInstanceId); log.info("is found previous task: {}", previous.isPresent() ? "yes" : "no"); if (previous.isPresent()) { fromTime = previous.get().getToTime(); } else throw new IllegalArgumentException("previous task not found"); } else { fromTime = nonNull(taskTimeDto.getFromTime()) ? taskTimeDto.getFromTime() : LocalDateTime.now(); } List<TaskTime> previousProcessTask ; if (nonNull(taskComplexityName)) { previousProcessTask = taskTimeRepository.findAllByTaskIdAndParentProcessInstanceIdAndToTimeIsAfterAndTaskComplexityOrderComplexityNameOrderByToTimeDesc( taskTimeDto.getCurrentActivityId(), parentProcessInstanceId, fromTime, taskComplexityName); }else { previousProcessTask = taskTimeRepository.findAllByTaskIdAndParentProcessInstanceIdAndToTimeIsAfterOrderByToTimeDesc(taskTimeDto.getCurrentActivityId(), parentProcessInstanceId, fromTime); } int queueCount = 0; int workerIndex = 1; if (previousProcessTask.size() > 0) { TaskTime taskTime = previousProcessTask.get(0); if (taskTime.getWorkerIndex() < taskTimeDto.getWorkerCount()) { workerIndex = taskTime.getWorkerIndex() + 1; } else { queueCount = previousProcessTask.size(); LocalDateTime toTime = taskTime.getToTime(); log.info("toTime -> fromTime {} for new task: {}", fromTime, toTime); fromTime = toTime; } } LocalDateTime endOfTaskTime = fromTime.plusHours(hours); log.info("from: {}, till: {}, hours: {}, name: {}, processId: {}", fromTime.format(formatter), endOfTaskTime.format(formatter), hours, taskTimeDto.getCurrentActivityName(), processInstanceId); saveTask(taskTimeDto.getCurrentActivityName(), taskTimeDto.getCurrentActivityId(), parentTaskId, processInstanceId, hours, fromTime, endOfTaskTime, queueCount, workerIndex, parentProcessInstanceId ); return endOfTaskTime.format(formatter); } private void saveTask(String currentActivityName, String currentActivityId, String parentTaskId, String processInstanceId, int hours, LocalDateTime fromTime, LocalDateTime endOfTaskTime, int queueCount, int workerIndex, String parentProcessInstanceId) { TaskTime taskTime = new TaskTime(); taskTime.setFromTime(fromTime); taskTime.setToTime(endOfTaskTime); taskTime.setHours(hours); taskTime.setName(currentActivityName); taskTime.setTaskId(currentActivityId); taskTime.setProcessId(processInstanceId); taskTime.setEventTime(LocalDateTime.now()); taskTime.setParentTaskId(parentTaskId); taskTime.setQueueCount(queueCount); taskTime.setWorkerIndex(workerIndex); taskTime.setParentProcessInstanceId(parentProcessInstanceId); taskTimeRepository.save(taskTime); } }
Java
CL
9a4bee154ef8f368f4f08883e8ce8edf81e90e6ac53b902601e3f198658b46ee
package com.blogen.api.v1.controllers; import com.blogen.api.v1.model.ApiErrorsView; import com.blogen.api.v1.model.ApiFieldError; import com.blogen.api.v1.model.ApiGlobalError; import com.blogen.exceptions.BadRequestException; import com.blogen.exceptions.NotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.stream.Collectors.toList; /** * Exception Handlers for REST Controllers * * @author Cliff */ @Slf4j @ControllerAdvice("com.blogen.api.v1.controllers") public class RestControllerExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler( {NotFoundException.class} ) public ResponseEntity<Object> handleNotFoundException( Exception exception, WebRequest request ){ log.error( exception.getMessage() ); ApiGlobalError globalError = new ApiGlobalError( exception.getMessage() ); List<ApiGlobalError> globalErrors = Arrays.asList( globalError ); ApiErrorsView errorsView = new ApiErrorsView( null, globalErrors ); return new ResponseEntity<>( errorsView, new HttpHeaders(), HttpStatus.NOT_FOUND); } @ExceptionHandler( {BadRequestException.class} ) public ResponseEntity<Object> handleBadRequestException( Exception exception, WebRequest request ) { log.error( exception.getMessage() ); ApiGlobalError globalError = new ApiGlobalError( exception.getMessage() ); List<ApiGlobalError> globalErrors = Arrays.asList( globalError ); ApiErrorsView errorsView = new ApiErrorsView( null, globalErrors ); return new ResponseEntity<>( errorsView, new HttpHeaders(), HttpStatus.BAD_REQUEST ); } @Override protected ResponseEntity<Object> handleTypeMismatch( TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request ) { log.error( ex.getMessage() ); String methodParamName = ( ex instanceof MethodArgumentTypeMismatchException) ? (( MethodArgumentTypeMismatchException ) ex).getName() : ""; List<ApiFieldError> apiFieldErrors = new ArrayList<>(); List<ApiGlobalError> apiGlobalErrors = new ArrayList<>(); ApiGlobalError globalError = new ApiGlobalError(); globalError.setMessage( "invalid type sent for parameter: " + methodParamName + " with value:" + ex.getValue() ); apiGlobalErrors.add( globalError ); ApiErrorsView apiErrorsView = new ApiErrorsView(apiFieldErrors, apiGlobalErrors); return new ResponseEntity<>(apiErrorsView, HttpStatus.BAD_REQUEST); } @Override public ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException exception, HttpHeaders headers, HttpStatus status, WebRequest request ) { log.error( exception.getMessage() ); BindingResult bindingResult = exception.getBindingResult(); List<ApiFieldError> apiFieldErrors = bindingResult .getFieldErrors() .stream() .map( fieldError -> new ApiFieldError( fieldError.getField(), fieldError.getDefaultMessage(),fieldError.getRejectedValue() ) ) .collect( toList()); List<ApiGlobalError> apiGlobalErrors = bindingResult .getGlobalErrors() .stream() .map(globalError -> new ApiGlobalError( globalError.getCode()) ) .collect( toList() ); ApiErrorsView apiErrorsView = new ApiErrorsView(apiFieldErrors, apiGlobalErrors); return new ResponseEntity<>(apiErrorsView, HttpStatus.UNPROCESSABLE_ENTITY); } @ExceptionHandler(Exception.class) public ResponseEntity<Object> handleOtherExceptions( Exception exception ) { log.error( exception.getMessage() ); ApiGlobalError globalError = new ApiGlobalError( exception.getMessage() ); List<ApiGlobalError> globalErrors = Arrays.asList( globalError ); ApiErrorsView errorsView = new ApiErrorsView( null, globalErrors ); return new ResponseEntity<>( errorsView, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR ); } }
Java
CL
6bf4b10029915aaedac0f5bd62392e2e9c62e94621618675ee571b9ec532dcd4
package com.isonah.usermanagement.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.security.Principal; import java.util.Optional; /** * @author ielksseyer */ @Configuration @EnableWebSecurity public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean @Primary public DefaultTokenServices tokenServices() { DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); return defaultTokenServices; } @Value("${security.oauth2.resource.jwk.key-set-uri}") private String publicKeyUri; @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setVerifierKey(getPublicKeyValue(publicKeyUri)); return converter; } @Override public void configure(ResourceServerSecurityConfigurer resources) { resources.resourceId("/user"); } @Override public void configure(HttpSecurity http) throws Exception { http .requestMatchers().antMatchers("/usersq/**") .and() .authorizeRequests().anyRequest().access("#oauth2.hasScope('write')"); } private String getPublicKeyValue(String uriKey) { return Optional.of(WebClient.create(publicKeyUri)) .map(j -> j.get().retrieve().bodyToMono(JwtObject.class)) .map(Mono::block) .map(JwtObject::getValue) .orElseThrow( () -> new RuntimeException("An error has occured while getting the public key from remote : " + publicKeyUri)); } }
Java
CL
cae6753a0708e670a2817739bd143c576d95081c3730aa8235afef8b048981b5
package apycazo.codex.java.basic; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.StringSerializer; import io.cucumber.datatable.dependency.com.fasterxml.jackson.annotation.JsonIgnore; import io.cucumber.datatable.dependency.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.cucumber.datatable.dependency.com.fasterxml.jackson.annotation.JsonInclude; import io.cucumber.datatable.dependency.com.fasterxml.jackson.annotation.JsonProperty; import io.cucumber.datatable.dependency.com.fasterxml.jackson.annotation.JsonView; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class JsonObjects { public static class PublicView {} public static class PrivateView extends PublicView {} @JsonView(PublicView.class) private String name; @JsonView(PublicView.class) private String pwd; @JsonView(PublicView.class) @JsonSerialize(using = StringSerializer.class) private String numberAsString; @JsonView(PrivateView.class) private String privateId; @JsonIgnore // do not serialize this field public String getPwd() { return pwd; } @JsonProperty // but do deserialize it! public void setPwd(String value) { this.pwd = value; } public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); String content = "{'name':'test', 'pwd':'secret', 'numberAsString':10,'privateId':'101'}"; // deserialize JsonObjects instance = mapper.readValue(content, JsonObjects.class); assertThat(instance).isNotNull(); assertThat(instance.getName()).isEqualTo("test"); assertThat(instance.getPwd()).isEqualTo("secret"); assertThat(instance.getNumberAsString()).isEqualTo("10"); assertThat(instance.getPrivateId()).isEqualTo("101"); // serialize String json = mapper.writeValueAsString(instance); assertThat(json.indexOf("\"name\":\"test\"")).isGreaterThan(-1); assertThat(json.indexOf("\"pw\"")).isEqualTo(-1); // by default, all properties not explicitly marked as being part of a view are serialized, disable that with: mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); // test views, public only json = mapper.writerWithView(JsonObjects.PublicView.class).writeValueAsString(instance); assertThat(json.indexOf("privateId")).isEqualTo(-1); assertThat(json.indexOf("name")).isGreaterThan(-1); // test views, private too json = mapper.writerWithView(JsonObjects.PrivateView.class).writeValueAsString(instance); assertThat(json.indexOf("privateId")).isGreaterThan(-1); assertThat(json.indexOf("name")).isGreaterThan(-1); } }
Java
CL
7f1084b2a1ab019e9714dac0bc40c5b9889fb72b676fdce1a0bf54c1595b0725
/* * Copyright 2013 SmartBear Software * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the Licence for the specific language governing permissions and limitations * under the Licence. */ package com.eviware.loadui.util.serialization; import java.util.Collections; import java.util.Set; import java.util.WeakHashMap; import com.eviware.loadui.api.serialization.ListenableValue; import com.google.common.collect.ImmutableSet; /** * Support class for implementing the ListenableValue interface. Calls to * update() will only notify the listeners when the value changes. Weak * References are used for listeners. * * @author dain.nilsson */ public class ListenableValueSupport<T> { private final Set<ListenableValue.ValueListener<? super T>> listeners = Collections .newSetFromMap( new WeakHashMap<ListenableValue.ValueListener<? super T>, Boolean>() ); private T lastValue = null; public void update( T newValue ) { lastValue = newValue; for( ListenableValue.ValueListener<? super T> listener : ImmutableSet.copyOf( listeners ) ) { listener.update( newValue ); } } public void addListener( ListenableValue.ValueListener<? super T> listener ) { listeners.add( listener ); } public void removeListener( ListenableValue.ValueListener<? super T> listener ) { listeners.remove( listener ); } public int getListenerCount() { return listeners.size(); } public T getLastValue() { return lastValue; } }
Java
CL
48da7ecf5a7859bbd3d03e44b545264b88deb47bf927d80052f3444e5d2dfd4a
/** */ package org.servicifi.gelato.language.cobol.registers.impl; import org.eclipse.emf.ecore.EClass; import org.servicifi.gelato.language.cobol.registers.RegistersPackage; import org.servicifi.gelato.language.cobol.registers.ShiftOut; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Shift Out</b></em>'. * <!-- end-user-doc --> * * @generated */ public class ShiftOutImpl extends RegisterImpl implements ShiftOut { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ShiftOutImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RegistersPackage.Literals.SHIFT_OUT; } } //ShiftOutImpl
Java
CL
e3a8ea8ebcfc3fa826c15b04cbd7531617468b3475ac22b223c99c9865b22d58
package com.orhonit.modules.app.controller; import java.util.Date; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.orhonit.common.utils.PageUtils; import com.orhonit.common.utils.R; import com.orhonit.modules.app.annotation.Login; import com.orhonit.modules.sys.entity.UserMemorandumEntity; import com.orhonit.modules.sys.service.UserMemorandumService; @RestController @RequestMapping("/app/usermemorandum") public class AppUserMemorandumController { @Autowired private UserMemorandumService userMemorandumService; /** * APP用戶管理通用-备忘录-查询列表(userId) */ @Login @RequestMapping("/list") //@RequiresPermissions("sys:usermemorandum:list") public R list(@RequestParam Map<String, Object> params,@RequestAttribute Long userId) { PageUtils page = userMemorandumService.queryPage(params,userId); return R.ok().put("page", page); } /** * APP用戶管理通用-备忘录-查询单条(memorandumId) */ @Login @RequestMapping("/info/{memorandumId}") //@RequiresPermissions("sys:usermemorandum:info") public R info(@PathVariable("memorandumId") Integer memorandumId) { UserMemorandumEntity userMemorandum = userMemorandumService.selectById(memorandumId); return R.ok().put("userMemorandum", userMemorandum); } /** * APP用戶管理通用-备忘录-添加备忘录 */ @Login @RequestMapping("/save") //@RequiresPermissions("sys:usermemorandum:save") public R save(@RequestBody UserMemorandumEntity userMemorandum,@RequestAttribute Long userId) { userMemorandum.setUserId(userId); userMemorandum.setCtrTime(new Date()); userMemorandumService.insert(userMemorandum); return R.ok(); } /** * APP用戶管理通用-备忘录-修改备忘录 */ @Login @RequestMapping("/update") //@RequiresPermissions("sys:usermemorandum:update") public R update(@RequestBody UserMemorandumEntity userMemorandum) { userMemorandumService.updateById(userMemorandum); return R.ok(); } /** * APP用戶管理通用-备忘录-删除备忘录 */ @Login @RequestMapping("/delete/{memorandumId}") //@RequiresPermissions("sys:usermemorandum:delete") public R delete(@PathVariable("memorandumId") Integer memorandumId) { //userMemorandumService.deleteBatchIds(Arrays.asList(memorandumIds)); userMemorandumService.deleteById(memorandumId); return R.ok(); } }
Java
CL
645ce95de453dd9b9a7d52fcaf6ae63ea7c53eca450a7bf706b0385920bf526e
package org.sample; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.util.CharsetUtil; import javax.net.ssl.SSLEngine; import java.net.URI; public class HttpsClientReadDataByChunks { private static final String HOST = "localhost"; private static final int PORT = 8263; private static final String REQUEST_PATH = "/api/endpoint"; private static final String REQUEST_BODY = "Hello, server!"; public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { // Configure SSL/TLS context SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); // Configure client Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<>() { @Override protected void initChannel(Channel ch) { ChannelPipeline pipeline = ch.pipeline(); SSLEngine sslEngine = sslContext.newEngine(ch.alloc()); sslEngine.setUseClientMode(true); pipeline.addLast(new SslHandler(sslEngine)); pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpContentDecompressor()); pipeline.addLast(new SimpleChannelInboundHandler<HttpObject>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; System.out.println("Response received:"); System.out.println("Status: " + response.status()); System.out.println("Headers: " + response.headers()); } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; ByteBuf buf = content.content(); String response = buf.toString(CharsetUtil.UTF_8); System.out.println("Content received: " + response); } } }); } }); // Start the client and establish connection ChannelFuture future = bootstrap.connect(HOST, PORT).sync(); Channel channel = future.channel(); // Prepare the HTTP request URI uri = new URI(REQUEST_PATH); FullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), Unpooled.copiedBuffer(REQUEST_BODY, CharsetUtil.UTF_8)); request.headers().set(HttpHeaderNames.HOST, HOST); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes()); // Send the HTTP request channel.writeAndFlush(request); // Wait for the response and close the connection channel.closeFuture().sync(); } finally { group.shutdownGracefully(); } } }
Java
CL
196a05b3660dcd1893576064800884a046e6fd7b43c1efd64faa7cc9b9f48cff
// Generated by the protocol buffer compiler. DO NOT EDIT! public final class SingleMessage extends com.google.protobuf.GeneratedMessage implements SingleMessageOrBuilder { // Use SingleMessage.newBuilder() to construct. private SingleMessage(Builder builder) { super(builder); } private SingleMessage(boolean noInit) {} private static final SingleMessage defaultInstance; public static SingleMessage getDefaultInstance() { return defaultInstance; } public SingleMessage getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return HelloWorld.internal_static_SingleMessage_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return HelloWorld.internal_static_SingleMessage_fieldAccessorTable; } private int bitField0_; // required .EmptyMessage req_msg = 1; public static final int REQ_MSG_FIELD_NUMBER = 1; private EmptyMessage reqMsg_; public boolean hasReqMsg() { return ((bitField0_ & 0x00000001) == 0x00000001); } public EmptyMessage getReqMsg() { return reqMsg_; } public EmptyMessageOrBuilder getReqMsgOrBuilder() { return reqMsg_; } private void initFields() { reqMsg_ = EmptyMessage.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasReqMsg()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, reqMsg_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, reqMsg_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static SingleMessage parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static SingleMessage parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static SingleMessage parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static SingleMessage parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static SingleMessage parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static SingleMessage parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static SingleMessage parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static SingleMessage parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static SingleMessage parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static SingleMessage parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(SingleMessage prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements SingleMessageOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return HelloWorld.internal_static_SingleMessage_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return HelloWorld.internal_static_SingleMessage_fieldAccessorTable; } // Construct using SingleMessage.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getReqMsgFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (reqMsgBuilder_ == null) { reqMsg_ = EmptyMessage.getDefaultInstance(); } else { reqMsgBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return SingleMessage.getDescriptor(); } public SingleMessage getDefaultInstanceForType() { return SingleMessage.getDefaultInstance(); } public SingleMessage build() { SingleMessage result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private SingleMessage buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { SingleMessage result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public SingleMessage buildPartial() { SingleMessage result = new SingleMessage(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (reqMsgBuilder_ == null) { result.reqMsg_ = reqMsg_; } else { result.reqMsg_ = reqMsgBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof SingleMessage) { return mergeFrom((SingleMessage)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(SingleMessage other) { if (other == SingleMessage.getDefaultInstance()) return this; if (other.hasReqMsg()) { mergeReqMsg(other.getReqMsg()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasReqMsg()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { EmptyMessage.Builder subBuilder = EmptyMessage.newBuilder(); if (hasReqMsg()) { subBuilder.mergeFrom(getReqMsg()); } input.readMessage(subBuilder, extensionRegistry); setReqMsg(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .EmptyMessage req_msg = 1; private EmptyMessage reqMsg_ = EmptyMessage.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< EmptyMessage, EmptyMessage.Builder, EmptyMessageOrBuilder> reqMsgBuilder_; public boolean hasReqMsg() { return ((bitField0_ & 0x00000001) == 0x00000001); } public EmptyMessage getReqMsg() { if (reqMsgBuilder_ == null) { return reqMsg_; } else { return reqMsgBuilder_.getMessage(); } } public Builder setReqMsg(EmptyMessage value) { if (reqMsgBuilder_ == null) { if (value == null) { throw new NullPointerException(); } reqMsg_ = value; onChanged(); } else { reqMsgBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setReqMsg( EmptyMessage.Builder builderForValue) { if (reqMsgBuilder_ == null) { reqMsg_ = builderForValue.build(); onChanged(); } else { reqMsgBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeReqMsg(EmptyMessage value) { if (reqMsgBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && reqMsg_ != EmptyMessage.getDefaultInstance()) { reqMsg_ = EmptyMessage.newBuilder(reqMsg_).mergeFrom(value).buildPartial(); } else { reqMsg_ = value; } onChanged(); } else { reqMsgBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearReqMsg() { if (reqMsgBuilder_ == null) { reqMsg_ = EmptyMessage.getDefaultInstance(); onChanged(); } else { reqMsgBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public EmptyMessage.Builder getReqMsgBuilder() { bitField0_ |= 0x00000001; onChanged(); return getReqMsgFieldBuilder().getBuilder(); } public EmptyMessageOrBuilder getReqMsgOrBuilder() { if (reqMsgBuilder_ != null) { return reqMsgBuilder_.getMessageOrBuilder(); } else { return reqMsg_; } } private com.google.protobuf.SingleFieldBuilder< EmptyMessage, EmptyMessage.Builder, EmptyMessageOrBuilder> getReqMsgFieldBuilder() { if (reqMsgBuilder_ == null) { reqMsgBuilder_ = new com.google.protobuf.SingleFieldBuilder< EmptyMessage, EmptyMessage.Builder, EmptyMessageOrBuilder>( reqMsg_, getParentForChildren(), isClean()); reqMsg_ = null; } return reqMsgBuilder_; } // @@protoc_insertion_point(builder_scope:SingleMessage) } static { defaultInstance = new SingleMessage(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:SingleMessage) }
Java
CL
729b2d77bed2ae3d6c747c7f990f40d5a972302422ea0c031ce555e2bf605339
/* * L2jFrozen Project - www.l2jfrozen.com * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jfrozen.gameserver.managers; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javolution.util.FastMap; import org.apache.log4j.Logger; import com.l2jfrozen.Config; import com.l2jfrozen.gameserver.model.actor.instance.L2NpcInstance; import com.l2jfrozen.util.CloseUtil; import com.l2jfrozen.util.database.DatabaseUtils; import com.l2jfrozen.util.database.L2DatabaseFactory; import com.l2jfrozen.util.random.Rnd; /** * control for Custom Npcs that look like players. * @version 1.00 * @author Darki699 */ public final class CustomNpcInstanceManager { private final static Logger LOGGER = Logger.getLogger(CustomNpcInstanceManager.class); private static CustomNpcInstanceManager _instance; private FastMap<Integer, customInfo> spawns; // <Object id , info> private FastMap<Integer, customInfo> templates; // <Npc Template Id , info> public L2NpcInstance _activeChar; /** * Small class to keep the npc poly data... Pretty code =) * @author Darki699 */ public final class customInfo { public String stringData[] = new String[2]; public int integerData[] = new int[27]; public boolean booleanData[] = new boolean[8]; } /** * Constructor Calls to load the data */ CustomNpcInstanceManager() { load(); } /** * Initiates the manager (if not initiated yet) and/or returns <b>this</b> manager instance * @return CustomNpcInstanceManager _instance */ public final static CustomNpcInstanceManager getInstance() { if (_instance == null) { _instance = new CustomNpcInstanceManager(); } return _instance; } /** * Flush the old data, and load new data */ public final void reload() { if (spawns != null) { spawns.clear(); } if (templates != null) { templates.clear(); } spawns = null; templates = null; load(); } /** * Just load the data for mysql... */ private final void load() { if (spawns == null || templates == null) { spawns = new FastMap<>(); templates = new FastMap<>(); } final String[] SQL_ITEM_SELECTS = { "SELECT" + " spawn,template,name,title,class_id,female,hair_style,hair_color,face,name_color,title_color," + " noble,hero,pvp,karma,wpn_enchant,right_hand,left_hand,gloves,chest,legs,feet,hair,hair2," + " pledge,cw_level,clan_id,ally_id,clan_crest,ally_crest,rnd_class,rnd_appearance,rnd_weapon,rnd_armor,max_rnd_enchant" + " FROM npc_to_pc_polymorph", }; Connection con = null; try { int count = 0; con = L2DatabaseFactory.getInstance().getConnection(false); for (final String selectQuery : SQL_ITEM_SELECTS) { PreparedStatement statement = con.prepareStatement(selectQuery); ResultSet rset = statement.executeQuery(); while (rset.next()) { count++; customInfo ci = new customInfo(); ci.integerData[26] = rset.getInt("spawn"); ci.integerData[25] = rset.getInt("template"); try { ci.stringData[0] = rset.getString("name"); ci.stringData[1] = rset.getString("title"); ci.integerData[7] = rset.getInt("class_id"); final int PcSex = rset.getInt("female"); switch (PcSex) { case 0: ci.booleanData[3] = false; break; case 1: ci.booleanData[3] = true; break; default: ci.booleanData[3] = Rnd.get(100) > 50 ? true : false; break; } ci.integerData[19] = rset.getInt("hair_style"); ci.integerData[20] = rset.getInt("hair_color"); ci.integerData[21] = rset.getInt("face"); ci.integerData[22] = rset.getInt("name_color"); ci.integerData[23] = rset.getInt("title_color"); ci.booleanData[1] = rset.getInt("noble") > 0 ? true : false; ci.booleanData[2] = rset.getInt("hero") > 0 ? true : false; ci.booleanData[0] = rset.getInt("pvp") > 0 ? true : false; ci.integerData[1] = rset.getInt("karma"); ci.integerData[8] = rset.getInt("wpn_enchant"); ci.integerData[11] = rset.getInt("right_hand"); ci.integerData[12] = rset.getInt("left_hand"); ci.integerData[13] = rset.getInt("gloves"); ci.integerData[14] = rset.getInt("chest"); ci.integerData[15] = rset.getInt("legs"); ci.integerData[16] = rset.getInt("feet"); ci.integerData[17] = rset.getInt("hair"); ci.integerData[18] = rset.getInt("hair2"); ci.integerData[9] = rset.getInt("pledge"); ci.integerData[10] = rset.getInt("cw_level"); ci.integerData[2] = rset.getInt("clan_id"); ci.integerData[3] = rset.getInt("ally_id"); ci.integerData[4] = rset.getInt("clan_crest"); ci.integerData[5] = rset.getInt("ally_crest"); ci.booleanData[4] = rset.getInt("rnd_class") > 0 ? true : false; ci.booleanData[5] = rset.getInt("rnd_appearance") > 0 ? true : false; ci.booleanData[6] = rset.getInt("rnd_weapon") > 0 ? true : false; ci.booleanData[7] = rset.getInt("rnd_armor") > 0 ? true : false; ci.integerData[24] = rset.getInt("max_rnd_enchant"); // Same object goes in twice: if (ci.integerData[25] != 0 && !templates.containsKey(ci.integerData[25])) { templates.put(ci.integerData[25], ci); } if (ci.integerData[25] == 0 && !spawns.containsKey(ci.integerData[26])) { spawns.put(ci.integerData[26], ci); } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); LOGGER.warn("Failed to load Npc Morph data for Object Id: " + ci.integerData[26] + " template: " + ci.integerData[25]); } ci = null; } DatabaseUtils.close(statement); statement = null; DatabaseUtils.close(rset); rset = null; } LOGGER.info("CustomNpcInstanceManager: loaded " + count + " NPC to PC polymorphs."); } catch (final Exception e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); /** LOGGER.warn( "CustomNpcInstanceManager: Passed "); **/ } finally { CloseUtil.close(con); con = null; } } /** * Checks if the L2NpcInstance calling this function has polymorphing data * @param spwnId - L2NpcInstance's unique Object id * @param npcId - L2NpcInstance's npc template id * @return */ public final boolean isThisL2CustomNpcInstance(final int spwnId, final int npcId) { if (spwnId == 0 || npcId == 0) return false; else if (spawns.containsKey(spwnId)) return true; else if (templates.containsKey(npcId)) return true; else return false; } /** * Return the polymorphing data for this L2NpcInstance if the data exists * @param spwnId - NpcInstance's unique Object Id * @param npcId - NpcInstance's npc template Id * @return customInfo type data pack, or null if no such data exists. */ public final customInfo getCustomData(final int spwnId, final int npcId) { if (spwnId == 0 || npcId == 0) return null; // First check individual spawn objects - incase they have different values than their template for (final customInfo ci : spawns.values()) if (ci != null && ci.integerData[26] == spwnId) return ci; // Now check if templates contains the morph npc template for (final customInfo ci : templates.values()) if (ci != null && ci.integerData[25] == npcId) return ci; return null; } /** * @return all template morphing queue */ public final FastMap<Integer, customInfo> getAllTemplates() { return templates; } /** * @return all spawns morphing queue */ public final FastMap<Integer, customInfo> getAllSpawns() { return spawns; } /** * Already removed customInfo - Change is saved in the DB <b>NOT IMPLEMENTED YET!</b> * @param ciToRemove */ public final void updateRemoveInDB(final customInfo ciToRemove) { // } public final void AddInDB(final customInfo ciToAdd) { String Query = "REPLACE INTO npc_to_pc_polymorph VALUES" + " spawn,template,name,title,class_id,female,hair_style,hair_color,face,name_color,title_color," + " noble,hero,pvp,karma,wpn_enchant,right_hand,left_hand,gloves,chest,legs,feet,hair,hair2," + " pledge,cw_level,clan_id,ally_id,clan_crest,ally_crest,rnd_class,rnd_appearance,rnd_weapon,rnd_armor,max_rnd_enchant" + " FROM npc_to_pc_polymorph"; Connection con = null; try { con = L2DatabaseFactory.getInstance().getConnection(false); PreparedStatement statement = con.prepareStatement(Query); ResultSet rset = statement.executeQuery(); DatabaseUtils.close(statement); statement = null; while (rset.next()) { final customInfo ci = new customInfo(); ci.integerData[26] = rset.getInt("spawn"); ci.integerData[25] = rset.getInt("template"); } DatabaseUtils.close(rset); rset = null; Query = null; } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); LOGGER.warn("Could not add Npc Morph info into the DB: "); } finally { CloseUtil.close(con); con = null; } } }
Java
CL
94ec1123aaf5b9319ff203a819af0224e89a55b7aab9cb702f14230810f475e6
/** * Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caintegrator/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.security; import gov.nih.nci.caintegrator.application.study.AuthorizedStudyElementsGroup; import gov.nih.nci.caintegrator.application.study.StudyConfiguration; import gov.nih.nci.caintegrator.domain.translational.Study; import gov.nih.nci.security.AuthorizationManager; import gov.nih.nci.security.authorization.domainobjects.Group; import gov.nih.nci.security.exceptions.CSException; import java.util.Collection; import java.util.Set; import org.hibernate.Session; /** * Interface to manage authentication and authorization data. */ public interface SecurityManager { /** * Creates the protectionElement on a Study given the StudyConfiguration. * @param studyConfiguration for which to create protection element on. * @throws CSException If there's a problem creating the PE. */ void createProtectionElement(StudyConfiguration studyConfiguration) throws CSException; /** * Creates the protectionElement on a AuthorizedStudyElementsGroup given the AuthorizedStudyElementsGroup. * @param studyConfiguration for which to create protection element on * @param authorizedStudyElementsGroup for which to create protection element on. * @throws CSException If there's a problem creating the PE. */ void createProtectionElement(StudyConfiguration studyConfiguration, AuthorizedStudyElementsGroup authorizedStudyElementsGroup) throws CSException; /** * Deletes a proteectionElement on a study given the Study Configuration. * @param studyConfiguration to delete the protection element for. * @throws CSException If there's a problem deleting the PE. */ void deleteProtectionElement(StudyConfiguration studyConfiguration) throws CSException; /** * Deletes a proteectionElement on a AuthorizedStudyElementsGroup given the AuthorizedStudyElementsGroup. * @param authorizedStudyElementsGroup to delete the protection element for. * @throws CSException If there's a problem deleting the PE. */ void deleteProtectionElement(AuthorizedStudyElementsGroup authorizedStudyElementsGroup) throws CSException; /** * Adds filter initialization to the session. * @param username to get all this users groups and filter based on those. * @param session hibernate session. * @throws CSException if there's problem using CSM. */ void initializeFiltersForUserGroups(String username, Session session) throws CSException; /** * Retrieves authorization manager. * @return authorization manager for CaIntegrator2. * @throws CSException if there's a problem retrieving authorization manager from CSM. */ AuthorizationManager getAuthorizationManager() throws CSException; /** * Retrieves a list of study configurations that the user has "UPDATE" access on. * @param username to check permissions for. * @param studies to check UPDATE permissions on. * @return study configurations that are managed by this user. * @throws CSException if there's a problem retrieving authorization manager from CSM. */ Set<StudyConfiguration> retrieveManagedStudyConfigurations(String username, Collection<Study> studies) throws CSException; /** * Checks to see if the given username exists. * @param username to check if it exists or not. * @return T/F value if it exists. */ boolean doesUserExist(String username); /** * Retrieves all AuthorizedStudyElementsGroups that this user has access to. * @param username to check access for. * @param availableGroups the AuthorizedStudyElementsGroups that have been created for this Study. * @return all AuthorizedStudyElementsGroups that this user has access to * @throws CSException if there's a problem retrieving authorization manager from CSM. */ Set<AuthorizedStudyElementsGroup> retrieveAuthorizedStudyElementsGroupsForInvestigator(String username, Set<AuthorizedStudyElementsGroup> availableGroups) throws CSException; /** * Retrieves a collection of all groups that have not yet been authorized for the given study configuration. * @param studyConfiguration the study configuration * @return the groups that have no yet been authorized for the given study * @throws CSException if there's a problem retrieving the authorization manager from CSM */ Collection<Group> getUnauthorizedGroups(StudyConfiguration studyConfiguration) throws CSException; }
Java
CL
8970b4ffcaf499c20573778d56d860b17555babce8d1424a2e78a4855f8b50b5
package cn.ibizlab.core.extensions.service; import cn.ibizlab.core.uaa.domain.SysApp; import cn.ibizlab.core.uaa.domain.SysPSSystem; import cn.ibizlab.core.uaa.domain.SysPermission; import cn.ibizlab.core.uaa.extensions.domain.PermissionType; import cn.ibizlab.core.uaa.service.ISysPermissionService; import cn.ibizlab.core.uaa.service.impl.SysPSSystemServiceImpl; import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.util.*; /** * 实体[系统] 自定义服务对象 */ @Slf4j @Primary @Service("SysPSSystemExService") public class SysPSSystemExService extends SysPSSystemServiceImpl { @Override protected Class currentModelClass() { return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1); } @Autowired @Lazy private ISysPermissionService sysPermissionService; @Override public boolean create(SysPSSystem et) { prepareApps(et); if(!super.create(et)) return false; // syncPermission(et); return true; } @Override public boolean update(SysPSSystem et) { Object ignoreSyncPermission=et.get("ignoreSyncPermission"); prepareApps(et); if(!super.update(et)) return false; // if(ignoreSyncPermission==null||ignoreSyncPermission.equals(false)) // syncPermission(et); return true; } /** * 自定义行为[PrepareApps]用户扩展 * @param system * @return */ @Override @Transactional public SysPSSystem prepareApps(SysPSSystem system) { if (StringUtils.isEmpty(system.getPssystemid()) || system.getSysstructure() == null) return system; Map<String, SysApp> oldApps = new HashMap<>(); Map<String, SysApp> newApps = new HashMap<>(); if(system.getApps()!=null) system.getApps().forEach(app->newApps.put(app.getId(),app)); List<SysApp> newList=new ArrayList<>(); SysPSSystem old = this.getById(system.getPssystemid()); if(old!=null&&old.getApps()!=null) old.getApps().forEach(app->oldApps.put(app.getId(),app)); system.getSysstructure().getSysApps(true).forEach(appNode -> { if(oldApps.containsKey(appNode.getId())) { SysApp sysApp=oldApps.get(appNode.getId()); if(newApps.containsKey(appNode.getId())) { SysApp newApp=newApps.get(appNode.getId()); sysApp.setAddr(newApp.getAddr()); sysApp.setIcon(newApp.getIcon()); sysApp.setFullname(newApp.getFullname()); sysApp.setType(newApp.getType()); sysApp.setGroup(newApp.getGroup()); } newList.add(sysApp); } else { appNode.setVisabled(1); if(newApps.containsKey(appNode.getId())) { SysApp newApp=newApps.get(appNode.getId()); appNode.setAddr(newApp.getAddr()); appNode.setIcon(newApp.getIcon()); appNode.setFullname(newApp.getFullname()); appNode.setType(newApp.getType()); appNode.setGroup(newApp.getGroup()); } newList.add(appNode); } }); if(old!=null&&old.getApps()!=null) old.getApps().forEach(app->{ if("THIRD-PARTY".equalsIgnoreCase(app.getGroup())) newList.add(app); }); system.setApps(newList); return system; } private Object lock=new Object(); /** * 自定义行为[SyncPermission]用户扩展 * @param system * @return */ @Override @Transactional @DS("db2") public SysPSSystem syncPermission(SysPSSystem system) { if(StringUtils.isEmpty(system.getPssystemid())||system.getSysstructure()==null) return system; Object ignoreSyncPermission=system.get("ignoreSyncPermission"); if(ignoreSyncPermission!=null&&ignoreSyncPermission.equals(true)) return system; Map<String,Integer> delPermission = new HashMap<>(); sysPermissionService.list(new QueryWrapper<SysPermission>().select("sys_permissionid").eq("pssystemid",system.getPssystemid())).forEach(sysPermission -> delPermission.put(sysPermission.getPermissionid(),1)); Set<SysPermission> list = system.getSysstructure().getSysPermissions(PermissionType.OPPRIV); list.addAll(system.getSysstructure().getSysPermissions(PermissionType.APPMENU)); list.addAll(system.getSysstructure().getSysPermissions(PermissionType.UNIRES)); Set<String> newIds=new HashSet<>(); list.forEach(sysPermission -> { delPermission.remove(sysPermission.getPermissionid()); newIds.add(sysPermission.getPermissionid()); }); //移除无效资源 if(delPermission.size()>0) sysPermissionService.removeBatch(delPermission.keySet()); //查询以往删除过的资源 String delIds = getDelPermissionIds(list,system.getPssystemid()); //将当前系统本次资源enable设为1以避免enable=0时,导致saveOrUpdate无法检测到主键存在,最终插入数据导致主键重复 if(newIds.size()>0 && !StringUtils.isEmpty(delIds)) sysPermissionService.execute(String.format("update ibzpermission set enable = 1 where sys_permissionid in (%s)",delIds),null); //存储或更新资源saveOrUpdate if(list.size()>0) sysPermissionService.saveBatch(list); return system; } @Override @Transactional @DS("db2") public boolean syncPermissionBatch(List<SysPSSystem> etList) { return super.syncPermissionBatch(etList); } private String getIds(Set<String> newIds) { String[] strIdArr = newIds.toArray(new String[newIds.size()]); return "'" + String.join("','", strIdArr) + "'"; } /** * 查询以往删除过的数据 * @param list * @return */ private String getDelPermissionIds(Set<SysPermission> list , String systemId) { String strDelIds = null; Map<String, Integer> delPermission = new HashMap<>(); Map param =new HashMap(); param.put("systemid",systemId); sysPermissionService.select("select sys_permissionid from ibzpermission t where pssystemid = #{et.systemid} and t.enable = 0 ", param).forEach(sysPermission -> delPermission.put(sysPermission.getString("sys_permissionid"), 1)); if (delPermission.size() == 0) return strDelIds; Set<String> delIds = new HashSet<>(); for (SysPermission permission : list) { if (!StringUtils.isEmpty(permission.getPermissionid())) { if (delPermission.containsKey(permission.getPermissionid())) { delIds.add(permission.getPermissionid()); } } } if (delIds.size() > 0) { strDelIds = getIds(delIds); } return strDelIds; } }
Java
CL
1dbdf3888fe0ffa6168865b099e111d28cf76f4bfb8a496109d48d94b72de8b7