hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
57eda78abb2ade3221972cc7f141210e47e27dc5
1,024
package uk.gov.companieshouse.api.accounts.model.entity.smallfull.notes.currentassetsinvestments; import com.google.gson.Gson; import uk.gov.companieshouse.api.accounts.model.entity.NoteEntity; import java.util.Objects; public class CurrentAssetsInvestmentsEntity extends NoteEntity { private CurrentAssetsInvestmentsDataEntity data; public CurrentAssetsInvestmentsDataEntity getData() { return data; } public void setData(CurrentAssetsInvestmentsDataEntity data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) {return true;} if (!(o instanceof CurrentAssetsInvestmentsEntity)) {return false;} CurrentAssetsInvestmentsEntity that = (CurrentAssetsInvestmentsEntity) o; return Objects.equals(getData(), that.getData()); } @Override public int hashCode() { return Objects.hash(getData()); } @Override public String toString() { return new Gson().toJson(this); } }
26.947368
97
0.704102
53bbc53ff5f68439c29a64a1fd0ce058540090b9
1,443
package com.jeecms.cms.entity.back.base; import java.io.Serializable; public abstract class BaseCmsConstraints implements Serializable { // constructors public BaseCmsConstraints() { initialize(); } protected void initialize() { } private int hashCode = Integer.MIN_VALUE; // fields private java.lang.String name; private java.lang.String tableName; private java.lang.String columnName; private java.lang.String referencedTableName; private java.lang.String referencedColumnName; public java.lang.String getName() { return name; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getTableName() { return tableName; } public void setTableName(java.lang.String tableName) { this.tableName = tableName; } public java.lang.String getColumnName() { return columnName; } public void setColumnName(java.lang.String columnName) { this.columnName = columnName; } public java.lang.String getReferencedTableName() { return referencedTableName; } public void setReferencedTableName(java.lang.String referencedTableName) { this.referencedTableName = referencedTableName; } public java.lang.String getReferencedColumnName() { return referencedColumnName; } public void setReferencedColumnName(java.lang.String referencedColumnName) { this.referencedColumnName = referencedColumnName; } public String toString() { return super.toString(); } }
21.220588
77
0.76438
3d40b4960e3592179b30337e3ff3bc9801a20ce1
17,268
package datawave.webservice.query.cachedresults; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import datawave.data.type.Type; import datawave.marking.MarkingFunctions; import datawave.marking.MarkingFunctionsFactory; import datawave.webservice.query.data.ObjectSizeOf; import datawave.webservice.query.util.TypedValue; import org.apache.accumulo.core.security.ColumnVisibility; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class CacheableQueryRowImpl extends CacheableQueryRow implements ObjectSizeOf { private static Logger log = Logger.getLogger(CacheableQueryRowImpl.class); private String user = null; private String queryId = null; private String logicName = null; private String dataType = null; private String eventId = null; private String row = null; private String colFam = null; private Map<String,String> markings = new HashMap<String,String>(); private Map<String,Map<String,String>> columnMarkingsMap = new HashMap<String,Map<String,String>>(); private Map<String,String> columnColumnVisibilityMap = new HashMap<String,String>(); private Map<String,String> columnTypeMap = Maps.newHashMap(); private Map<String,Long> columnTimestampMap = new HashMap<String,Long>(); private Map<String,Set<String>> columnValues = new HashMap<String,Set<String>>(); private Set<String> variableColumnNames = new TreeSet<String>(); private String queryOrigin = null; private String resultOrigin = null; private static final MarkingFunctions markingFunctions = MarkingFunctionsFactory.createMarkingFunctions(); public void addColumn(String columnName, String columnValueString, Map<String,String> markings, String columnVisibility, Long timestamp) { addColumn(columnName, new TypedValue(columnValueString), markings, columnVisibility, timestamp); } public void addColumn(String columnName, TypedValue columnTypedValue, Map<String,String> markings, String columnVisibility, Long timestamp) { columnName = columnName.replaceAll(" ", "_"); // if new markings are the same as the old markings, skip all of this // they are the same and the markings value has already been validated if (this.markings.equals(markings) == false) { if (this.markings.isEmpty()) { // validate the markings try { markingFunctions.translateToColumnVisibility(markings); if (this.markings.isEmpty()) { // markings were empty, so use the one passed in. this.markings = markings; } } catch (MarkingFunctions.Exception e) { log.error("Invalid markings " + markings + ", skipping column " + columnName + "=" + columnTypedValue, e); return; } } else { try { Set<ColumnVisibility> columnVisibilities = Sets.newHashSet(); columnVisibilities.add(markingFunctions.translateToColumnVisibility(this.markings)); columnVisibilities.add(markingFunctions.translateToColumnVisibility(markings)); ColumnVisibility combinedVisibility = markingFunctions.combine(columnVisibilities); Map<String,String> minMarkings = markingFunctions.translateFromColumnVisibility(combinedVisibility); // use combined marking as new markings this.markings = minMarkings; } catch (MarkingFunctions.Exception e) { log.error("Invalid markings " + markings + ", skipping column " + columnName + "=" + columnTypedValue, e); return; } } } Long currTimestamp = columnTimestampMap.get(columnName); if (currTimestamp == null || timestamp > currTimestamp) { columnTimestampMap.put(columnName, timestamp); } Type<?> datawaveType = null; String typedColumnName = ""; if (columnTypedValue.getValue() instanceof Type<?>) { datawaveType = (Type<?>) columnTypedValue.getValue(); typedColumnName = columnTypedValue.getType().replaceAll(":", "_").toUpperCase(); typedColumnName += "_" + columnName; } manageColumnInsert(datawaveType, columnName, columnTypedValue, markings, columnVisibility); if (typedColumnName.length() > 0 && typedColumnName.startsWith("XS_STRING") == false) { manageColumnInsert(datawaveType, typedColumnName, columnTypedValue, markings, columnVisibility); } } private void manageColumnInsert(Type<?> datawaveType, String columnName, TypedValue columnTypedValue, Map<String,String> markings, String columnVisibility) { if (this.columnValues.containsKey(columnName) == false) { Set<String> valuesSet = Sets.newLinkedHashSet(); if (datawaveType != null) { if (columnName.startsWith("XS")) { valuesSet.add(datawaveType.getNormalizedValue()); } else { valuesSet.add(datawaveType.getDelegate().toString()); } this.columnTypeMap.put(columnName, datawaveType.getClass().toString()); } else { valuesSet.add(columnTypedValue.getValue().toString()); } this.columnValues.put(columnName, valuesSet); this.columnMarkingsMap.put(columnName, markings); this.columnColumnVisibilityMap.put(columnName, columnVisibility); } else { if (datawaveType != null) { if (columnName.startsWith("XS")) { columnValues.get(columnName).add(datawaveType.getNormalizedValue()); } else { columnValues.get(columnName).add(datawaveType.getDelegate().toString()); } this.columnTypeMap.put(columnName, datawaveType.getClass().toString()); } else { columnValues.get(columnName).add(columnTypedValue.getValue().toString()); } Map<String,String> currMarkings = columnMarkingsMap.get(columnName); if (currMarkings.equals(markings) == false) { try { Set<ColumnVisibility> columnVisibilities = Sets.newHashSet(); columnVisibilities.add(markingFunctions.translateToColumnVisibility(currMarkings)); columnVisibilities.add(markingFunctions.translateToColumnVisibility(markings)); ColumnVisibility combinedVisibility = markingFunctions.combine(columnVisibilities); Map<String,String> minMarkings = markingFunctions.translateFromColumnVisibility(combinedVisibility); // use combined marking as new markings columnMarkingsMap.put(columnName, minMarkings); // new combined marking means that this colVis is greater than old colVis columnColumnVisibilityMap.put(columnName, columnVisibility); } catch (MarkingFunctions.Exception e) { throw new IllegalStateException(e.getMessage(), e); } } } } public String getUser() { return user; } public String getQueryId() { return queryId; } public String getLogicName() { return logicName; } public String getDataType() { return dataType; } public String getEventId() { return eventId; } public String getRow() { return row; } public String getColFam() { return colFam; } public Map<String,String> getMarkings() { return Maps.newHashMap(markings); } public Map<String,String> getColumnMarkings(String columnName) { columnName = columnName.replaceAll(" ", "_"); Map<String,String> markings = null; if (this.columnMarkingsMap.containsKey(columnName)) { markings = this.columnMarkingsMap.get(columnName); } else { markings = this.columnMarkingsMap.get("_DEFAULT_"); } if (markings == null) markings = Maps.newHashMap(); return markings; } public String getColumnTimestampString(Map<String,Integer> columnMap) { Map<Long,Set<String>> timestampMap = new HashMap<Long,Set<String>>(); for (Map.Entry<String,Long> entry : columnTimestampMap.entrySet()) { String currColumnName = entry.getKey(); Integer currColumnNumber = columnMap.get(currColumnName); if (currColumnNumber != null) { Long currLong = entry.getValue(); Set<String> columnSet = timestampMap.get(currLong); if (columnSet == null) { columnSet = new TreeSet<String>(); timestampMap.put(currLong, columnSet); } columnSet.add(currColumnName); } } int largestSetCount = 0; Long largestSetTimestamp = 0L; for (Map.Entry<Long,Set<String>> entry : timestampMap.entrySet()) { int currSize = entry.getValue().size(); if (currSize > largestSetCount) { largestSetCount = currSize; largestSetTimestamp = entry.getKey(); } } StringBuilder sb = new StringBuilder(); timestampMap.remove(largestSetTimestamp); sb.append(largestSetTimestamp).append("\0").append(0); for (Map.Entry<Long,Set<String>> entry : timestampMap.entrySet()) { sb.append("\0\0"); sb.append(entry.getKey()); sb.append("\0"); sb.append(CacheableQueryRow.createColumnList(entry.getValue(), columnMap)); } return sb.toString(); } public String getColumnVisibility(String columnName) { columnName = columnName.replaceAll(" ", "_"); String columnVisibility = null; if (this.columnColumnVisibilityMap.containsKey(columnName)) { columnVisibility = this.columnColumnVisibilityMap.get(columnName); } else { columnVisibility = this.columnColumnVisibilityMap.get("_DEFAULT_"); } return columnVisibility; } public Long getColumnTimestamp(String columnName) { columnName = columnName.replaceAll(" ", "_"); Long timestamp = null; if (this.columnTimestampMap.containsKey(columnName)) { timestamp = this.columnTimestampMap.get(columnName); } else { timestamp = this.columnTimestampMap.get("_DEFAULT_"); } return timestamp; } public void setQueryId(String queryId) { this.queryId = queryId; } public void setLogicName(String logicName) { this.logicName = logicName; } public void setDataType(String dataType) { this.dataType = dataType; } public void setEventId(String eventId) { this.eventId = eventId; } public void setRow(String row) { this.row = row; } public void setColFam(String colFam) { this.colFam = colFam; } public void setMarkings(Map<String,String> markings) { // validate the markings try { markingFunctions.translateToColumnVisibility(markings); this.markings = markings; } catch (MarkingFunctions.Exception e) { log.error("Invalid markings " + markings, e); } } public void setColumnMarkingsMap(Map<String,Map<String,String>> columnMarkingsMap) { this.columnMarkingsMap = columnMarkingsMap; } public void setColumnTimestampMap(Map<String,Long> columnTimestampMap) { this.columnTimestampMap = columnTimestampMap; } public void setUser(String user) { this.user = user; } public String getColumnSecurityMarkingString(Map<String,Integer> columnMap) { Map<String,String> combinedMap = new HashMap<String,String>(); for (String field : columnMarkingsMap.keySet()) { // sort the map Map<String,String> m = columnMarkingsMap.get(field); String v = columnColumnVisibilityMap.get(field); if (m == null) { m = new HashMap<String,String>(); } // use TreeMap to sort the map String mStr = MarkingFunctions.Encoding.toString(new TreeMap<String,String>(m)); if (v == null) { combinedMap.put(field, mStr); } else { combinedMap.put(field, mStr + ':' + v); } } int largestSetCount = 0; String largestSetMarkingString = ""; Map<String,Set<String>> markingToField = new HashMap<String,Set<String>>(); for (Map.Entry<String,String> entry : combinedMap.entrySet()) { String combinedMarking = entry.getValue(); Set<String> fields = markingToField.get(combinedMarking); if (fields == null) { fields = new HashSet<String>(); markingToField.put(combinedMarking, fields); } fields.add(entry.getKey()); if (fields.size() > largestSetCount) { largestSetCount = fields.size(); largestSetMarkingString = combinedMarking; } } StringBuilder sb = new StringBuilder(); markingToField.remove(largestSetMarkingString); sb.append(largestSetMarkingString).append("\0").append(0); for (Map.Entry<String,Set<String>> entry : markingToField.entrySet()) { sb.append("\0\0"); sb.append(entry.getKey()); sb.append("\0"); sb.append(CacheableQueryRow.createColumnList(entry.getValue(), columnMap)); } return sb.toString(); } public Map<String,String> getColumnValues() { Map<String,String> columnValues = new HashMap<String,String>(); for (Map.Entry<String,Set<String>> entry : this.columnValues.entrySet()) { columnValues.put(entry.getKey(), StringUtils.join(entry.getValue(), ",")); } return columnValues; } public void setColumnValues(Map<String,Set<String>> columnValues) { this.columnValues = columnValues; } public List<String> getVariableColumnNames() { List<String> l = new ArrayList<String>(); l.addAll(variableColumnNames); return l; } public void setVariableColumnNames(Collection<String> c) { this.variableColumnNames.clear(); this.variableColumnNames.addAll(c); } public String getQueryOrigin() { return queryOrigin; } public void setQueryOrigin(String queryOrigin) { this.queryOrigin = queryOrigin; } public String getResultOrigin() { return resultOrigin; } public void setResultOrigin(String resultOrigin) { this.resultOrigin = resultOrigin; } public Map<String,String> getColumnColumnVisibilityMap() { return columnColumnVisibilityMap; } public void setColumnColumnVisibilityMap(Map<String,String> columnColumnVisibilityMap) { this.columnColumnVisibilityMap = columnColumnVisibilityMap; } // the approximate size in bytes of this event private long size = -1; /** * Set the size based on the number of characters stored in the DB * * @param size * The number of characters */ public void setSizeInStoredCharacters(long size) { // in practice the size of a row will be about 6 times the number of character bytes setSizeInBytes(size * 6); } /** * @param size * the approximate size of this event in bytes */ public void setSizeInBytes(long size) { this.size = size; } /** * @return The set size in bytes, -1 if unset */ public long getSizeInBytes() { return this.size; } /** * Get the approximate size of this event in bytes. Used by the ObjectSizeOf mechanism in the webservice. Throws an exception if the local size was not set * to allow the ObjectSizeOf mechanism to do its thang. */ @Override public long sizeInBytes() { if (size <= 0) { throw new UnsupportedOperationException(); } return this.size; } }
37.785558
161
0.604934
6d1c4ccc102b313e06676a221b874a552dd17101
4,869
package com.github.kaeluka.cflat.storage; import com.github.kaeluka.cflat.util.Mutable; import java.util.Arrays; import static com.github.kaeluka.cflat.util.IndexCheck.checkIndexIsNonnegative; @SuppressWarnings({"WeakerAccess", "unchecked", "unused"}) public class IntTrieStorage implements Storage<Integer> { public final int[][][][] data = new int[0x80][][][]; private final static int EMPTY = Integer.MIN_VALUE; private int maxIdx = -1; public Integer get(final int idx) { checkIndexIsNonnegative(idx); assert idx >= 0; int[][][] d1; final int coord1 = idx >> 24 & 0x7F; if ((d1 = data[coord1]) == null) { return null; } int[][] d2; final int coord2 = idx >> 16 & 0xFF; if ((d2 = d1[coord2]) == null) { return null; } int[] d3; final int coord3 = idx >> 8 & 0xFF; if ((d3 = d2[coord3]) == null) { return null; } return readFromChunk(d3, idx & 0xFF); } private static int[] newChunk() { final int[] chunk = new int[0x100]; Arrays.fill(chunk, EMPTY); return chunk; } private static Integer readFromChunk(int[] chunk, int idx) { final int ret = chunk[idx]; if (ret == EMPTY) { return null; } else { return ret; } } @Override public Integer get2(final int idx, final Mutable<Integer> v2) { checkIndexIsNonnegative(idx); checkIndexIsNonnegative(idx+1); int coord1 = idx >> 24 & 0x7F; int coord2 = idx >> 16 & 0xFF; int coord3 = idx >> 8 & 0xFF; int coord4 = idx & 0xFF; int[][][] d1; int[][] d2; int[] d3; if ((d1 = data[coord1]) == null || (d2 = d1[coord2]) == null || (d3 = d2[coord3]) == null) { return null; } if (coord4 != 0xFF) { v2.x = readFromChunk(d3, coord4+1); } else { handleOverflow(v2, d1, coord1, d2, coord2, coord3); } return readFromChunk(d3, coord4); } private void handleOverflow(final Mutable<Integer> v2, final int[][][] d1, final int coord1, final int[][] d2, final int coord2, final int coord3) { if (coord3 != 0xFF) { v2.x = d2[coord3+1][0]; } else { if (coord2 != 0xFF) { v2.x = readFromChunk(d1[coord2+1][0],0); } else { if (coord1 != 0xFF) { v2.x = readFromChunk(data[coord1+1][0][0], 0); } else { throw new ArrayIndexOutOfBoundsException(); } } } } public Storage<Integer> set(final int idx, final Integer x) { checkIndexIsNonnegative(idx); if (idx > maxIdx) { maxIdx = idx; } int[][][] d1; int[][] d2; int[] d3; int coord1 = idx >> 24 & 0xFF; if ((d1 = data[coord1]) == null) { d1 = data[coord1] = new int[0x100][][]; } int coord2 = idx >> 16 & 0xFF; if ((d2 = d1[coord2]) == null) { d2 = d1[coord2] = new int[0x100][]; } int coord3 = idx >> 8 & 0xFF; if ((d3 = d2[coord3]) == null) { d3 = d2[coord3] = newChunk(); } d3[idx & 0xFF] = x == null ? EMPTY : x; return this; } public Storage<Integer> set2(final int idx, final Integer x, final Integer y) { checkIndexIsNonnegative(idx); checkIndexIsNonnegative(idx+1); if (idx > maxIdx) { maxIdx = idx; } int[][][] d1; int[][] d2; int[] d3; final int coord1 = idx >> 24 & 0xFF; if ((d1 = data[coord1]) == null) { d1 = data[coord1] = new int[0x100][][]; } final int coord2 = idx >> 16 & 0xFF; if ((d2 = d1[coord2]) == null) { d2 = d1[coord2] = new int[0x100][]; } final int coord3 = idx >> 8 & 0xFF; if ((d3 = d2[coord3]) == null) { d3 = d2[coord3] = newChunk(); } final int coord4 = idx & 0xFF; d3[coord4] = x; if (coord4 != 0xFF) { d3[coord4+1] = y == null ? EMPTY : y; } else { set(idx+1, y); } return this; } public Storage<Integer> clearAll() { Arrays.fill(data, null); return this; } public int maxIdxOverapproximation() { return maxIdx+1; } public Storage<Integer> emptyCopy() { return new HashMapStorage<>(); // return new HashMapStorage<>(new IntHashMap<>()); } public long bytesUsed() { System.err.println("returning bogus value for TrieStorage::bytesUsed"); return -1; } }
28.144509
152
0.489423
1ad622a09b0c9b2ae209e3075164cce69c15b25a
1,119
package com.smoothstack.collections; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class Student { String name; public Student(String name) { this.name = name; } public String toString() { return this.name; } } class SortByName implements Comparator<Student> { public int compare(Student a, Student b) { return a.name.compareTo(b.name); } } public class ComparatorDemo { public ComparatorDemo() { ArrayList<Student> ar = new ArrayList<Student>(); ar.add(new Student("Bob")); ar.add(new Student("Jack")); ar.add(new Student("Rajesh")); ar.add(new Student("Diana")); System.out.println("Unsorted"); for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); Collections.sort(ar, new SortByName()); System.out.println("\nSorted by name"); for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); } }
22.836735
57
0.581769
b7ed13b159f4bb8547c793479bd5e30e95cb1966
12,362
package com.ibm.ets.ita.ce.store.client.rest; /******************************************************************************* * (C) Copyright IBM Corporation 2011, 2017 * All Rights Reserved *******************************************************************************/ import static com.ibm.ets.ita.ce.store.names.JsonNames.JSONTYPE_CONMOD; import static com.ibm.ets.ita.ce.store.names.RestNames.REST_CONCEPT; import static com.ibm.ets.ita.ce.store.names.RestNames.REST_SOURCE; import static com.ibm.ets.ita.ce.store.names.RestNames.REST_SENTENCE; import static com.ibm.ets.ita.ce.store.names.RestNames.REST_PROPERTY; import static com.ibm.ets.ita.ce.store.utilities.FileUtilities.appendNewLineToSb; import static com.ibm.ets.ita.ce.store.utilities.FileUtilities.appendToSb; import static com.ibm.ets.ita.ce.store.utilities.ReportingUtilities.reportError; import java.util.ArrayList; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import com.ibm.ets.ita.ce.store.client.web.WebActionContext; import com.ibm.ets.ita.ce.store.client.web.model.CeWebConceptualModel; import com.ibm.ets.ita.ce.store.core.ModelBuilder; import com.ibm.ets.ita.ce.store.model.CeConcept; import com.ibm.ets.ita.ce.store.model.CeConceptualModel; import com.ibm.ets.ita.ce.store.model.CeInstance; import com.ibm.ets.ita.ce.store.model.CeProperty; import com.ibm.ets.ita.ce.store.model.CeSentence; import com.ibm.ets.ita.ce.store.model.CeSource; public class CeStoreRestApiConceptualModel extends CeStoreRestApi { public static final String copyrightNotice = "(C) Copyright IBM Corporation 2011, 2017"; public CeStoreRestApiConceptualModel(WebActionContext pWc, ArrayList<String> pRestParts, HttpServletRequest pRequest) { super(pWc, pRestParts, pRequest); } /* * Supported requests: * /models * /models/{name} * /models/{name}/sources * /models/{name}/sentences * /models/{name}/concepts * /models/{name}/properties */ public boolean processRequest() { boolean statsInResponse = false; if (this.restParts.size() == 1) { processOneElementRequest(); } else { String modelName = this.restParts.get(1); // String modelName = StaticFunctionsGeneral.decodeFromUrl(this.wc, rawModelName); CeConceptualModel tgtCm = getModelBuilder().getConceptualModel(modelName); if (tgtCm != null) { if (this.restParts.size() == 2) { statsInResponse = processTwoElementRequest(tgtCm); } else if (this.restParts.size() == 3) { processThreeElementRequest(tgtCm); } else { reportUnhandledUrl(); } } else { reportNotFoundError(modelName); } } return statsInResponse; } private void processOneElementRequest() { //URL = /models //List all conceptual models if (isGet()) { handleListConceptualModels(); } else { reportUnsupportedMethodError(); } } private boolean processTwoElementRequest(CeConceptualModel pCm) { //URL = /models/{name} boolean statsInResponse = false; if (isGet()) { //Get conceptual model details handleGetConceptualModelDetails(pCm); } else if (isDelete()) { if (!this.wc.getModelBuilder().isLocked()) { //DELETE conceptual model handleDeleteConceptualModel(pCm); statsInResponse = true; } else { reportError("ce-store is locked. The delete request was ignored", this.wc); } } else { reportUnsupportedMethodError(); } return statsInResponse; } private void processThreeElementRequest(CeConceptualModel pCm) { String qualifier = this.restParts.get(2); if (isGet()) { if (qualifier.equals(REST_SOURCE)) { //URL = /models/{name}/sources //List all sources for conceptual model handleListSourcesForConceptualModel(pCm); } else if (qualifier.equals(REST_SENTENCE)) { //URL = /models/{name}/sentences //List all sentences for conceptual model handleListSentencesForConceptualModel(pCm); } else if (qualifier.equals(REST_CONCEPT)) { //URL = /models/{name}/concepts //List all concepts for conceptual model handleListConceptsForConceptualModel(pCm); } else if (qualifier.equals(REST_PROPERTY)) { //URL = /models/{name}/properties //List all properties for conceptual model handleListPropertiesForConceptualModel(pCm); } else { reportUnhandledUrl(); } } else { reportUnsupportedMethodError(); } } private void handleListConceptualModels() { if (isJsonRequest()) { jsonListConceptualModels(); } else if (isTextRequest()) { textListConceptualModels(); } else { reportUnsupportedFormatError(); } } private void jsonListConceptualModels() { ArrayList<CeConceptualModel> cmList = getModelBuilder().listAllConceptualModels(); setConceptualModelListAsStructuredResult(cmList); } private void textListConceptualModels() { StringBuilder sb = new StringBuilder(); appendToSb(sb, "-- All sentences for all conceptual models"); appendNewLineToSb(sb); for (CeConceptualModel thisCm : getModelBuilder().getAllConceptualModels().values()) { generateTextForConceptualModel(this.wc, sb, thisCm, isFullStyle()); appendNewLineToSb(sb); } getWebActionResponse().setPlainTextPayload(this.wc, sb.toString()); } private void handleGetConceptualModelDetails(CeConceptualModel pCm) { if (isJsonRequest()) { jsonGetConceptualModelDetails(pCm); } else if (isTextRequest()) { textGetConceptualModelDetails(pCm); } else { reportUnsupportedFormatError(); } } private void jsonGetConceptualModelDetails(CeConceptualModel pCm) { setConceptualModelDetailsAsStructuredResult(pCm); } private void textGetConceptualModelDetails(CeConceptualModel pCm) { StringBuilder sb = new StringBuilder(); generateTextForConceptualModel(this.wc, sb, pCm, isFullStyle()); getWebActionResponse().setPlainTextPayload(this.wc, sb.toString()); } private void handleDeleteConceptualModel(CeConceptualModel pCm) { if (isJsonRequest()) { jsonDeleteConceptualModel(pCm); } else if (isTextRequest()) { textDeleteConceptualModel(pCm); } else { reportUnsupportedFormatError(); } } private void jsonDeleteConceptualModel(CeConceptualModel pCm) { setActionOutcomeAsStructuredResult(actionDeleteConceptualModel(pCm)); } private void textDeleteConceptualModel(CeConceptualModel pCm) { String summaryResult = actionDeleteConceptualModel(pCm); getWebActionResponse().setPlainTextPayload(this.wc, summaryResult); } private String actionDeleteConceptualModel(CeConceptualModel pCm) { ModelBuilder.deleteConceptualModel(this.wc, pCm); return "Conceptual model '" + pCm.getModelName() + "' has been deleted"; } private void handleListSourcesForConceptualModel(CeConceptualModel pCm) { if (isJsonRequest()) { jsonListSourcesForConceptualModel(pCm); } else if (isTextRequest()) { textListSourcesForConceptualModel(pCm); } else { reportUnsupportedFormatError(); } } private void jsonListSourcesForConceptualModel(CeConceptualModel pCm) { setSourceListAsStructuredResult(this, pCm.listSources()); } private void textListSourcesForConceptualModel(CeConceptualModel pCm) { StringBuilder sb = new StringBuilder(); appendToSb(sb, "-- All sentences for all sources for conceptual model " + pCm.getModelName()); appendNewLineToSb(sb); for (CeSource thisSrc : pCm.listSources()) { CeStoreRestApiSource.generateTextForSource(this.wc, sb, thisSrc, isFullStyle()); appendNewLineToSb(sb); } getWebActionResponse().setPlainTextPayload(this.wc, sb.toString()); } private void handleListSentencesForConceptualModel(CeConceptualModel pCm) { if (isJsonRequest()) { jsonListSentencesForConceptualModel(pCm); } else if (isTextRequest()) { textListSentencesForConceptualModel(pCm); } else { reportUnsupportedFormatError(); } } private void jsonListSentencesForConceptualModel(CeConceptualModel pCm) { setSentenceListAsStructuredResult(pCm.getSentences()); } private void textListSentencesForConceptualModel(CeConceptualModel pCm) { StringBuilder sb = new StringBuilder(); appendToSb(sb, "-- All sentences for conceptual model " + pCm.getModelName()); appendNewLineToSb(sb); for (CeSource thisSrc : pCm.getSources()) { for (CeSentence thisSen : thisSrc.listPrimarySentences()) { CeStoreRestApiSentence.generateTextForSentence(this.wc, sb, thisSen, isFullStyle()); appendNewLineToSb(sb); } } getWebActionResponse().setPlainTextPayload(this.wc, sb.toString()); } private void handleListConceptsForConceptualModel(CeConceptualModel pCm) { if (isJsonRequest()) { jsonListConceptsForConceptualModel(pCm); } else if (isTextRequest()) { textListConceptsForConceptualModel(pCm); } else { reportUnsupportedFormatError(); } } private void jsonListConceptsForConceptualModel(CeConceptualModel pCm) { setConceptListAsStructuredResult(pCm.listDefinedConcepts()); } private void textListConceptsForConceptualModel(CeConceptualModel pCm) { StringBuilder sb = new StringBuilder(); appendToSb(sb, "-- All sentences for all concepts for conceptual model " + pCm.getModelName()); appendNewLineToSb(sb); for (CeConcept thisCon : pCm.getDefinedConcepts()) { CeStoreRestApiConcept.generateTextForConcept(this.wc, sb, thisCon, isFullStyle()); appendNewLineToSb(sb); } getWebActionResponse().setPlainTextPayload(this.wc, sb.toString()); } private void handleListPropertiesForConceptualModel(CeConceptualModel pCm) { if (isJsonRequest()) { jsonListPropertiesForConceptualModel(pCm); } else if (isTextRequest()) { textListPropertiesForConceptualModel(pCm); } else { reportUnsupportedFormatError(); } } private void jsonListPropertiesForConceptualModel(CeConceptualModel pCm) { setPropertyListAsStructuredResult(pCm.listDefinedProperties()); } private void textListPropertiesForConceptualModel(CeConceptualModel pCm) { StringBuilder sb = new StringBuilder(); appendToSb(sb, "-- All sentences for all properties for conceptual model " + pCm.getModelName()); appendNewLineToSb(sb); for (CeProperty thisProp : pCm.getDefinedProperties()) { CeStoreRestApiProperty.generateTextForProperty(this.wc, sb, thisProp, isFullStyle()); appendNewLineToSb(sb); } getWebActionResponse().setPlainTextPayload(this.wc, sb.toString()); } private void generateTextForConceptualModel(WebActionContext pWc, StringBuilder pSb, CeConceptualModel pCm, boolean pFullStyle) { appendToSb(pSb, "-- Conceptual model: " + pCm.getModelName() + " (all sentences)"); appendNewLineToSb(pSb); //TODO: Link sentences directly to conceptual model. For now get them via the source(s) for (CeSource thisSrc : pCm.getSources()) { for (CeSentence thisSen : thisSrc.listPrimarySentences()) { CeStoreRestApiSentence.generateTextForSentence(pWc, pSb, thisSen, pFullStyle); appendNewLineToSb(pSb); } } CeInstance mmInst = getModelBuilder().getInstanceNamed(pWc, pCm.getModelName()); if (mmInst != null) { appendToSb(pSb, "-- Meta-model sentences"); for (CeSentence thisSen : mmInst.listAllSentences()) { CeStoreRestApiSentence.generateTextForSentence(pWc, pSb, thisSen, pFullStyle); appendToSb(pSb, ""); } } } private void reportNotFoundError(String pModelName) { reportNotFoundError(JSONTYPE_CONMOD, pModelName); } private void setConceptualModelListAsStructuredResult(Collection<CeConceptualModel> pCmList) { CeWebConceptualModel cmWeb = new CeWebConceptualModel(this.wc); if (isDefaultStyle() || isSummaryStyle()) { getWebActionResponse().setStructuredResult(cmWeb.generateSummaryListJsonFor(pCmList)); } else if (isMinimalStyle()) { getWebActionResponse().setStructuredResult(cmWeb.generateMinimalListJsonFor(pCmList)); } else if (isNormalisedStyle()) { getWebActionResponse().setStructuredResult(cmWeb.generateNormalisedListJsonFor(pCmList)); } else { getWebActionResponse().setStructuredResult(cmWeb.generateFullListJsonFor(pCmList)); } } private void setConceptualModelDetailsAsStructuredResult(CeConceptualModel pCm) { CeWebConceptualModel cmWeb = new CeWebConceptualModel(this.wc); if (isDefaultStyle() || isFullStyle()) { getWebActionResponse().setStructuredResult(cmWeb.generateFullDetailsJsonFor(pCm)); } else { getWebActionResponse().setStructuredResult(cmWeb.generateSummaryDetailsJsonFor(pCm)); } } }
32.531579
130
0.744459
3479d2ef26fe5c98f1fb6db07b794d70b50e6cd4
11,212
/* * Copyright (C) 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package com.google.cloud.teleport.bigtable; import com.datastax.driver.core.ColumnDefinitions.Definition; import com.datastax.driver.core.DataType; import com.datastax.driver.core.DataType.Name; import com.datastax.driver.core.LocalDate; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.net.InetAddress; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.Future; import java.util.stream.Collectors; import org.apache.beam.sdk.io.cassandra.Mapper; import org.apache.beam.sdk.options.ValueProvider; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.Field; import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.values.Row; import org.joda.time.DateTime; /** * This is an implementation of the Cassandra Mapper interface which allows custom Row Mapping logic * to be injected into the Beam CassandraIO. The goal of this implementation is to take a Cassandra * Resultset and for each of the rows map them into a BeamRow. * * @see <a href="https://beam.apache.org/releases/javadoc/2.12 * .0/org/apache/beam/sdk/io/cassandra/Mapper.html"> The Cassandra Mapper Interface</a> */ class CassandraRowMapperFn implements Mapper<Row>, Serializable { private final Session session; private final ValueProvider<String> table; private final ValueProvider<String> keyspace; private Schema schema; static final String KEY_ORDER_METADATA_KEY = "key_order"; /** * Constructor used by CassandraRowMapperFactory. * * @see CassandraRowMapperFactory * @see <a href="https://beam.apache.org/releases/javadoc/2.12 * .0/org/apache/beam/sdk/io/cassandra/Mapper.html"> The Cassandra Mapper Interface</a> * @see org.apache.beam.sdk.values.Row * @param session the Cassandra session. * @param keyspace the Cassandra keyspace to read data from. * @param table the Cassandra table to read from. */ CassandraRowMapperFn( Session session, ValueProvider<String> keyspace, ValueProvider<String> table) { this.session = session; this.table = table; this.keyspace = keyspace; } /** * @param resultSet the {@link ResultSet} to map. * @return an iterator containing the mapped rows. * @see ResultSet * @see Row */ @Override public Iterator<Row> map(ResultSet resultSet) { List<Definition> columnDefinitions = resultSet.getColumnDefinitions().asList(); // If there is no schema then generate one. We assume all rows have the same schema. if (schema == null) { // Get the order of the primary keys. We store the order of the primary keys in the field // metadata. Map<String, Integer> keyOrder = CassandraKeyUtils.primaryKeyOrder(session, keyspace.get(), table.get()); schema = createBeamRowSchema(columnDefinitions, keyOrder); } List<Row> rows = new ArrayList<>(); // Loop over each cassandra row and covert this to a Beam row. for (com.datastax.driver.core.Row cassandraRow : resultSet) { List<Object> values = new ArrayList<>(); for (int i = 0; i < columnDefinitions.size(); i++) { DataType columnType = columnDefinitions.get(i).getType(); Object columnValue = mapValue(cassandraRow.getObject(i), columnType); values.add(columnValue); } Row row = Row.withSchema(schema).addValues(values).build(); rows.add(row); } return rows.iterator(); } /** Not used as this pipeline only reads from cassandra. */ @Override public Future<Void> deleteAsync(Row entity) { throw new UnsupportedOperationException(); } /** Not used as this pipeline only reads from cassandra. */ @Override public Future<Void> saveAsync(Row entity) { throw new UnsupportedOperationException(); } /** * This method creates a Beam {@link Schema schema} based on the list of Definition supplied as * input. If a field name matches a key from the keyOrder map (supplied as a input parameter) this * denotes that the field was previously part of the Cassandra primary-key. To preserve the order * of these primary keys metadata is added to the field on the format "key_order": X - where X is * an integer indicating the order of the key in Cassandra. * * @param definitions a list of field definitions. * @param keyOrder the order of the fields that make up the Cassandra row key. key is field name, * value denotes the order from the row-key. * @return a {@link Schema schema} schema for all fields supplied as input. */ private Schema createBeamRowSchema(List<Definition> definitions, Map<String, Integer> keyOrder) { List<Field> fields = definitions.stream() .map(def -> Field.of(def.getName(), toBeamRowType(def.getType())).withNullable(true)) .map( fld -> keyOrder.containsKey(fld.getName()) ? fld.withType( fld.getType() .withMetadata(KEY_ORDER_METADATA_KEY, keyOrder.get(fld.getName()).toString())) : fld) .collect(Collectors.toList()); return Schema.builder().addFields(fields).build(); } /** * This method takes Objects retrieved from Cassandra as well as their Column type and converts * them into Objects that are supported by the Beam {@link Schema} and {@link Row}. * * <p>The method starts with the complex types {@link List}, {@link Map} and {@link Set}. For all * other types it assumes that they are primitives and passes them on. * * @param object The Cassandra cell value to be converted. * @param type The Cassandra Data Type * @return the beam compatible object. */ private Object mapValue(Object object, DataType type) { DataType.Name typeName = type.getName(); if (typeName == Name.LIST) { DataType innerType = type.getTypeArguments().get(0); List list = (List) object; // Apply toBeamObject on all items. return list.stream() .map(value -> toBeamObject(value, innerType)) .collect(Collectors.toList()); } else if (typeName == Name.MAP) { DataType ktype = type.getTypeArguments().get(0); DataType vtype = type.getTypeArguments().get(1); Set<Entry> map = ((Map) object).entrySet(); // Apply toBeamObject on both key and value. return map.stream() .collect( Collectors.toMap( e -> toBeamObject(e.getKey(), ktype), e -> toBeamObject(e.getValue(), vtype))); } else if (typeName == Name.SET) { DataType innerType = type.getTypeArguments().get(0); List list = new ArrayList((Set) object); // Apply toBeamObject on all items. return list.stream().map(l -> toBeamObject(l, innerType)).collect(Collectors.toList()); } else { return toBeamObject(object, type); } } /** * This method converts Cassandra {@link DataType} to Beam {@link FieldType}. Tuples are as of yet * not supported as there is no corresponding type in the Beam {@link Schema}. * * @param type the Cassandra DataType to be converted * @return the corresponding Beam Schema field type. * @see org.apache.beam.sdk.schemas.Schema.FieldType * @see com.datastax.driver.core.DataType * @link <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_reference/tupleType.html">Cassandra * Tuple</a> */ private FieldType toBeamRowType(DataType type) { DataType.Name n = type.getName(); switch (n) { case TIMESTAMP: case DATE: return FieldType.DATETIME; case BLOB: return FieldType.BYTES; case BOOLEAN: return FieldType.BOOLEAN; case DECIMAL: return FieldType.DECIMAL; case DOUBLE: return FieldType.DOUBLE; case FLOAT: return FieldType.FLOAT; case INT: return FieldType.INT32; case VARINT: return FieldType.DECIMAL; case SMALLINT: return FieldType.INT16; case TINYINT: return FieldType.BYTE; case LIST: case SET: DataType innerType = type.getTypeArguments().get(0); return FieldType.array(toBeamRowType(innerType)); case MAP: DataType kDataType = type.getTypeArguments().get(0); DataType vDataType = type.getTypeArguments().get(1); FieldType k = toBeamRowType(kDataType); FieldType v = toBeamRowType(vDataType); return FieldType.map(k, v); case VARCHAR: case TEXT: case INET: case UUID: case TIMEUUID: case ASCII: return FieldType.STRING; case BIGINT: case COUNTER: case TIME: return FieldType.INT64; default: throw new UnsupportedOperationException("Datatype " + type.getName() + " not supported."); } } /** * Most primitivies are represented the same way in Beam and Cassandra however there are a few * that differ. This method converts the native representation of timestamps, uuids, varint, dates * and IPs to a format which works for the Beam Schema. * * <p>Dates and Timestamps are returned as DateTime objects whilst UUIDs are converted to Strings. * Varint is converted into BigDecimal. The rest simply pass through as they are. * * @param value The object value as retrieved from Cassandra. * @param typeName The Cassandra schema type. * @see org.apache.beam.sdk.schemas.Schema.FieldType * @return The corresponding representation that works in the Beam schema. */ private Object toBeamObject(Object value, DataType typeName) { if (typeName == null || typeName.getName() == null) { throw new UnsupportedOperationException( "Unspecified Cassandra data type, cannot convert to beam row primitive."); } switch (typeName.getName()) { case TIMESTAMP: return new DateTime(value); case UUID: return ((UUID) value).toString(); case VARINT: return new BigDecimal((BigInteger) value); case TIMEUUID: return ((UUID) value).toString(); case DATE: LocalDate ld = (LocalDate) value; return new DateTime(ld.getYear(), ld.getMonth(), ld.getDay(), 0, 0); case INET: return ((InetAddress) value).getHostAddress(); default: return value; } } }
37.878378
110
0.67731
bf08df203df45dbab35ca5f8a154af907120d44e
962
package lehman.android; import android.content.Intent; import android.util.Log; import android.content.Context; import android.content.BroadcastReceiver; import android.graphics.Bitmap; import android.widget.ImageView; import android.view.View; public class StreetViewReceiver extends BroadcastReceiver { private final String TAG = getClass().getSimpleName(); private final boolean D = Log.isLoggable(TAG, Log.DEBUG); public static final String ACTION_STREETVIEW = "lehman.android.intent.action.STREETVIEW_RECEIVED"; private View mView; public StreetViewReceiver(View view) { mView = view; } @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive"); ImageView imageView = (ImageView)mView.findViewById(R.id.locStreetView); Bitmap streetView = intent.getParcelableExtra(StreetViewService.STREETVIEW_IMG); imageView.setImageBitmap(streetView); } }
30.0625
102
0.747401
eb9e2a2a36770c147c740e566100ca980c4d930e
9,092
package ru.pasha__kun.windowfx.impl; import javafx.beans.InvalidationListener; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import ru.pasha__kun.windowfx.Window; import java.util.*; public class WindowList implements ObservableList<Window> { private class WrapperChange extends ListChangeListener.Change<Window> { private final ListChangeListener.Change<? extends WindowEntry> change; private int[] permutation; private List<Window> removed; private WrapperChange(ListChangeListener.Change<? extends WindowEntry> change) { super(WindowList.this); this.change = change; } @Override public boolean next() { permutation = null; removed = null; return change.next(); } @Override public void reset() { change.reset(); } @Override public int getFrom() { return change.getFrom(); } @Override public int getTo() { return change.getTo(); } @Override public List<Window> getRemoved() { if (removed == null) { if (change.wasRemoved()) { removed = new ArrayList<>(change.getRemovedSize()); for (WindowEntry e : change.getRemoved()) removed.add(e.getWindow()); } else removed = Collections.emptyList(); } return removed; } @Override protected int[] getPermutation() { if (permutation == null) { if (change.wasPermutated()) { permutation = new int[change.getTo() - change.getFrom()]; for (int i = 0; i < permutation.length; i++) permutation[i] = change.getPermutation(i + change.getFrom()); } else permutation = new int[0]; } return permutation; } } private class EventHelper implements ListChangeListener<WindowEntry> { private Set<ListChangeListener<? super Window>> handlers = new HashSet<>(); @Override public void onChanged(Change<? extends WindowEntry> change) { ListChangeListener.Change<Window> change2 = new WrapperChange(change); for (ListChangeListener<? super Window> handler : handlers) handler.onChanged(change2); } } private class WindowEntryIterator implements ListIterator<Window> { private final ListIterator<WindowEntry> iterator; private WindowEntryIterator() { this.iterator = entries.listIterator(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Window next() { return iterator.next().getWindow(); } @Override public boolean hasPrevious() { return iterator.hasPrevious(); } @Override public Window previous() { return iterator.previous().getWindow(); } @Override public int nextIndex() { return iterator.nextIndex(); } @Override public int previousIndex() { return iterator.previousIndex(); } @Override public void remove() { iterator.remove(); } @Override public void set(Window window) { iterator.set(makeEntry(window)); } @Override public void add(Window window) { iterator.add(makeEntry(window)); } } private final ObservableList<WindowEntry> entries; private final EventHelper helper; public WindowList(ObservableList<WindowEntry> entries) { this.entries = entries; this.helper = new EventHelper(); entries.addListener(helper); } private WindowEntry makeEntry(Window w){ return new WindowEntry(w); } @Override public boolean setAll(Collection<? extends Window> collection) { throw new UnsupportedOperationException("setAll"); } @Override public boolean retainAll(Collection<?> c) { return entries.removeIf(e -> !c.contains(e.getWindow())); } @Override public ListIterator<Window> listIterator() { return new WindowEntryIterator(); } @Override public boolean retainAll(Window... windows) { return retainAll(Arrays.asList(windows)); } @Override public List<Window> subList(int fromIndex, int toIndex) { return new ArrayList<>(this).subList(fromIndex, toIndex); } @Override public boolean setAll(Window... windows) { return setAll(Arrays.asList(windows)); } @Override public boolean add(Window window) { return entries.add(makeEntry(window)); } @Override public Window set(int index, Window element) { WindowEntry e = entries.set(index, makeEntry(element)); return e == null? null: e.getWindow(); } @Override public void add(int index, Window element) { entries.add(index, makeEntry(element)); } @Override public void addListener(ListChangeListener<? super Window> listChangeListener) { helper.handlers.add(listChangeListener); } @Override public void removeListener(ListChangeListener<? super Window> listChangeListener) { helper.handlers.remove(listChangeListener); } @Override public boolean remove(Object o) { int i = indexOf(o); if (i > -1) remove(i); return i > -1; } @Override public int lastIndexOf(Object o) { ListIterator<Window> wi = listIterator(size() - 1); for (int i = size() - 1; wi.hasPrevious(); i--) if (Objects.equals(wi.previous(), o)) return i; return -1; } @Override public int indexOf(Object o) { Iterator<Window> wi = iterator(); for (int i = 0; wi.hasNext(); i++) if (Objects.equals(wi.next(), o)) return i; return -1; } @Override public boolean contains(Object o) { return indexOf(o) > -1; } @Override public Object[] toArray() { return toArray(new Window[size()]); } @Override public <T> T[] toArray(T[] a) { Iterator<Window> wi = iterator(); for (int i = 0; i < a.length && wi.hasNext(); i++) //noinspection unchecked a[i] = (T) wi.next(); return a; } @Override public void addListener(InvalidationListener invalidationListener) { entries.addListener(invalidationListener); } @Override public void removeListener(InvalidationListener invalidationListener) { entries.removeListener(invalidationListener); } @Override public ListIterator<Window> listIterator(int index) { ListIterator<Window> i = listIterator(); for (int j = 0; j < index; j++) i.next(); return i; } @Override public Iterator<Window> iterator() { return listIterator(); } @Override public Window get(int index) { return entries.get(index).getWindow(); } @Override public Window remove(int index) { return entries.remove(index).getWindow(); } @Override public void remove(int i, int i1) { entries.remove(i, i1); } @Override public int size() { return entries.size(); } @Override public boolean containsAll(Collection<?> c) { for (Object o : c) if (!contains(o)) return false; return true; } @Override public boolean removeAll(Window... windows) { boolean c = false; for (Window w : windows) if (remove(w)) c = true; return c; } @Override public boolean removeAll(Collection<?> c) { boolean e = false; for (Object w : c) if (remove(w)) e = true; return e; } @Override public boolean addAll(Collection<? extends Window> c) { boolean e = false; for (Object w : c) if (w instanceof Window && add((Window) w)) e = true; return e; } @Override public boolean addAll(int index, Collection<? extends Window> c) { boolean e = false; for (Object w : c) if (w instanceof Window) { add(index++, (Window) w); e = true; } return e; } @Override public boolean addAll(Window... windows) { boolean c = false; for (Window w : windows) if (add(w)) c = true; return c; } @Override public boolean isEmpty() { return entries.isEmpty(); } @Override public void clear() { entries.clear(); } }
24.245333
88
0.560493
8aa07b5ab11d2ee5b222fb7359c071de4f22bcb4
1,107
package de.othr.threads; public class TimerApp { public static void main(String[] args) { Timer t1 = new Timer("Spaghetti", 8); Timer t2 = new Timer("Sosse", 15); t1.start(); t2.start(); try { do { System.out.println(t1.getState()); Thread.sleep(1000); } while (t1.getState() != Thread.State.TERMINATED); } catch (InterruptedException e) { } main2(args); main3(args); } private static void main2(String[] args) { new Thread() { @Override public void run() { System.out.println("Hallo!"); } }.start(); } private static void main3(String[] args) { new Thread(() -> { System.out.println("Pizza-Timer gestartet."); try { Thread.sleep(15*1000); } catch (InterruptedException e) { System.out.println("Pizza-Timer unterbrochen."); } System.out.println("Pizza-Timer abgelaufen."); }).start(); } }
26.357143
64
0.492322
0dcb454e750913788768b7079d948fee2c70e675
39,943
/** * THIS SOFTWARE IS LICENSED UNDER MIT LICENSE.<br> * <br> * Copyright 2019 Andras Berkes [andras.berkes@programmer.net]<br> * Based on Moleculer Framework for NodeJS [https://moleculer.services]. * <br><br> * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions:<br> * <br> * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software.<br> * <br> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package services.moleculer.mongo; import org.bson.BsonValue; import org.bson.Document; import org.bson.conversions.Bson; import org.reactivestreams.Publisher; import com.mongodb.MongoNamespace; import com.mongodb.client.model.CountOptions; import com.mongodb.client.model.DeleteOptions; import com.mongodb.client.model.DropIndexOptions; import com.mongodb.client.model.FindOneAndDeleteOptions; import com.mongodb.client.model.FindOneAndReplaceOptions; import com.mongodb.client.model.FindOneAndUpdateOptions; import com.mongodb.client.model.Indexes; import com.mongodb.client.model.InsertOneOptions; import com.mongodb.client.model.RenameCollectionOptions; import com.mongodb.client.model.ReplaceOptions; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.mongodb.reactivestreams.client.FindPublisher; import com.mongodb.reactivestreams.client.MongoCollection; import io.datatree.Promise; import io.datatree.Tree; /** * Superclass of all Mongo handlers. If it used with Spring Framework, the DAO * classes must be annotated with the @Repository or @Component annotation. * Sample DAO class for handling "User" entities: * * <pre> * &#64;MongoCollection("user") * public class UserDAO extends MongoDAO { * * public Promise insertUser(String firstName, String lastName) { * Tree doc = new Tree(); * doc.put("firstName", firstName); * doc.put("lastName", lastName); * return insertOne(doc).then(res -&gt; { * return res.get("_id", ""); * }); * } * * public Promise findUserById(String id) { * return findOne(eq(id)); * } * * public Promise deleteUserById(String id) { * return deleteOne(eq(id)).then(res -&gt; { * return res.get("deleted", 0) &gt; 0; * }); * } * * } * </pre> * * Example of using the code above: * * <pre> * userDAO.insertUser("Tom", "Smith").then(res -&gt; { * System.out.println("Record ID: " + res.asString()); * }); * </pre> */ public class MongoDAO extends MongoFilters { // --- FIELD NAME CONSTANTS --- // Root node of rows public static final String ROWS = "rows"; // Row counter public static final String COUNT = "count"; // Set function public static final String SET = "$set"; // ObjectID public static final String ID = "_id"; // Number of matched rows public static final String MATCHED = "matched"; // Number of modified rows public static final String MODIFIED = "modified"; // Number of deleted rows public static final String DELETED = "deleted"; // True if the write was acknowledged public static final String ACKNOWLEDGED = "acknowledged"; // --- COLLECTION OF THIS DAO --- protected MongoCollection<Document> collection; protected int maxItemsPerQuery = 1024 * 10; // --- GET CONNECTION AND COLLECTION --- /** * Sets the MongoConnectionPool of this DAO. Processes the @MongoCollection * annotation. If no annotation is specified, generates the collection name * from the Class name (eg from "UserDAO" to "user"). * * @param pool * the MongoConnectionPool to use */ public void setMongoConnectionPool(MongoConnectionPool pool) { // Set collection by the @MongoCollection annotation // Eg. @MongoCollection("users") Class<? extends MongoDAO> c = getClass(); if (c.isAnnotationPresent(services.moleculer.mongo.MongoCollection.class)) { services.moleculer.mongo.MongoCollection annotation = c .getAnnotation(services.moleculer.mongo.MongoCollection.class); String collectionName = annotation.value(); if (collectionName != null) { collectionName = collectionName.trim(); collection = pool.getMongoDatabase().getCollection(collectionName); } } if (collection == null) { // Generate collection name by class name // Eg. "UserDAO" -> "user" String className = c.getName().toLowerCase(); int i = className.lastIndexOf('.'); if (i > -1) { className = className.substring(i + 1); } if (className.endsWith("dao")) { className = className.substring(0, className.length() - 3); } collection = pool.getMongoDatabase().getCollection(className); } } // --- DROP COLLECTION --- /** * Drops this collection from the Database. Sample of usage: * * <pre> * drop().then(res -&gt; { * // Drop operation finished * }); * </pre> * * @return a Promise with a single element indicating when the operation has * completed */ protected Promise drop() { return singleResult(collection.drop()); } // --- RENAME COLLECTION --- /** * Rename the collection. Sample of usage: * * <pre> * renameCollection("db", "collection").then(res -&gt; { * // Rename operation finished * }); * </pre> * * @param databaseName * name of the database * @param collectionName * new collection name * @return a Promise with a single element indicating when the operation has * completed */ protected Promise renameCollection(String databaseName, String collectionName) { return singleResult(collection.renameCollection(new MongoNamespace(databaseName, collectionName))); } /** * Rename the collection. Sample of usage: * * <pre> * RenameCollectionOptions opts = new RenameCollectionOptions(); * opts.dropTarget(false); * * renameCollection("db", "collection", opts).then(res -&gt; { * // Rename operation finished * }); * </pre> * * @param databaseName * name of the database * @param collectionName * new collection name * @param options * the options for renaming a collection * @return a Promise with a single element indicating when the operation has * completed */ protected Promise renameCollection(String databaseName, String collectionName, RenameCollectionOptions options) { return singleResult(collection.renameCollection(new MongoNamespace(databaseName, collectionName), options)); } // --- CREATE INDEX(ES) --- /** * Creates ascending indexes. Sample of usage: * * <pre> * createAscendingIndexes("field1", "field2").then(res -&gt; { * // Index created successfully * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param fieldNames * field names * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createAscendingIndexes(String... fieldNames) { return createIndexes(Indexes.ascending(fieldNames)); } /** * Creates descending indexes. Sample of usage: * * <pre> * createDescendingIndexes("field1", "field2").then(res -&gt; { * // Index created successfully * }); * </pre> * * @param fieldNames * field names * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createDescendingIndexes(String... fieldNames) { return createIndexes(Indexes.descending(fieldNames)); } /** * Creates 2dsphere indexes. Sample of usage: * * <pre> * createGeo2DSphereIndexes("field1", "field2").then(res -&gt; { * // Index created successfully * }); * </pre> * * @param fieldNames * field names * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createGeo2DSphereIndexes(String... fieldNames) { return createIndexes(Indexes.geo2dsphere(fieldNames)); } /** * Creates a geo2d index. Sample of usage: * * <pre> * createGeo2DIndex("field1").then(res -&gt; { * // Index created successfully * }); * </pre> * * @param fieldName * field name * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createGeo2DIndex(String fieldName) { return createIndexes(Indexes.geo2d(fieldName)); } /** * Creates a hashed index. Sample of usage: * * <pre> * createHashedIndex("field1").then(res -&gt; { * // Index created successfully * }); * </pre> * * @param fieldName * field name * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createHashedIndex(String fieldName) { return createIndexes(Indexes.hashed(fieldName)); } /** * Creates a text index. Sample of usage: * * <pre> * createTextIndex("field1").then(res -&gt; { * // Index created successfully * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param fieldName * field name * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createTextIndex(String fieldName) { return createIndexes(Indexes.text(fieldName)); } /** * Creates an index by the specified Tree object. Sample of usage: * * <pre> * BsonTree indexes = new BsonTree(Indexes.text("field1")); * createIndexes(indexes).then(res -&gt; { * // Index created successfully * }); * </pre> * * @param indexes * list of fields * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createIndexes(Tree indexes) { return createIndexes(toBson(indexes)); } /** * Creates an index by the specified Bson object. Sample of usage: * * <pre> * createIndexes(Indexes.text("field1")).then(res -&gt; { * // Index created successfully * }); * </pre> * * @param key * an object describing the index key(s), which may not be null. * @return a Promise with a single element indicating when the operation has * completed */ protected Promise createIndexes(Bson key) { return singleResult(collection.createIndex(key)); } // --- LIST INDEXES --- /** * Get all the indexes in this collection.<br> * <br> * Sample return structure: * * <pre> * { * "count":2, * "rows":[ * { * "v":1, * "key":{"_id":1}, * "name":"_id_", * "ns":"db.test" * }, { * "v":1, * "key":{"a":1}, * "name":"a_1", * "ns":"db.test" * } * ] * } * </pre> * * Sample of usage: * * <pre> * listIndexes().then(res -&gt; { * * // Operation finished * for (Tree index : res.get("rows")) { * System.out.println(index.get("name", "")); * } * * }); * </pre> * * @return a Promise with the list of indexes, and number of indexes */ protected Promise listIndexes() { return collectAll(collection.listIndexes()); } // --- DROP INDEX --- /** * Drops the specified index. Sample of usage: * * <pre> * dropIndex("field1").then(res -&gt; { * // Drop index operation finished * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param indexName * the name of the index to remove * @return a Promise with a single element indicating when the operation has * completed */ protected Promise dropIndex(String indexName) { return singleResult(collection.dropIndex(indexName)); } /** * Drops the given index. Sample of usage: * * <pre> * DropIndexOptions opts = new DropIndexOptions(); * opts.maxTime(10, TimeUnit.SECONDS); * * dropIndex("field1", opts).then(res -&gt; { * // Drop index operation finished * }); * </pre> * * @param indexName * the name of the index to remove * @param options * options to use when dropping indexes * @return a Promise with a single element indicating when the operation has * completed */ protected Promise dropIndex(String indexName, DropIndexOptions options) { return singleResult(collection.dropIndex(indexName, options)); } // --- INSERT ONE DOCUMENT --- /** * Inserts the provided document. If the document is missing an identifier, * the driver should generate one. Sample of usage: * * <pre> * Tree doc = new Tree(); * doc.put("field1", 123); * doc.put("field2.subfield", false); * * insertOne(doc).then(res -&gt; { * * // Insert operation finished * String id = res.get("_id", ""); * return id; * * }); * </pre> * * @param document * the document to insert * @return a Promise with a single element indicating when the operation has * completed */ protected Promise insertOne(Tree document) { Document doc = (Document) toBson(document); return singleResult(collection.insertOne(doc)).then(in -> { return doc; }); } /** * Inserts the provided document. If the document is missing an identifier, * the driver should generate one. Sample of usage: * * <pre> * Tree doc = new Tree(); * doc.put("field1", 123); * * InsertOneOptions opts = new InsertOneOptions(); * opts.bypassDocumentValidation(false); * * insertOne(doc, opts).then(res -&gt; { * * // Insert operation finished * String id = res.get("_id", ""); * return id; * * }); * </pre> * * @param document * the document to insert * @param options * the options to apply to the operation * @return a Promise with a single element indicating when the operation has * completed */ protected Promise insertOne(Tree document, InsertOneOptions options) { Document doc = (Document) toBson(document); return singleResult(collection.insertOne(doc, options)).then(in -> { return doc; }); } // --- REPLACE ONE DOCUMENT --- /** * Replace a document in the collection according to the specified * arguments. <br> * Sample to update result structure: * * <pre> * { * "matched": 10, * "modified": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * Tree replacement = new Tree(); * replacement.put("field1", 123); * * replaceOne(eq("field1", 123), replacement).then(res -&gt; { * * // Replace operation finished * int modified = res.get("modified"); * return modified &gt; 0; * * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param filter * the query filter to apply the the replace operation * @param replacement * the replacement document * @return a Promise with a single element the update result structure */ protected Promise replaceOne(Tree filter, Tree replacement) { return singleResult(collection.replaceOne(toBson(filter), (Document) toBson(replacement))) .thenWithResult(res -> { return updateResultToTree(res); }); } /** * Replace a document in the collection according to the specified * arguments. <br> * Sample to update result structure: * * <pre> * { * "matched": 10, * "modified": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * Tree replacement = new Tree(); * replacement.put("field1", 123); * * ReplaceOptions opts = new ReplaceOptions(); * opts.bypassDocumentValidation(false); * * replaceOne(eq("field1", 123), replacement, opts).then(res -&gt; { * * // Replace operation finished * int modified = res.get("modified"); * return modified &gt; 0; * * }); * </pre> * * @param filter * the query filter to apply the the replace operation * @param replacement * the replacement document * @param options * the options to apply to the replace operation * @return a Promise with a single element the update result structure */ protected Promise replaceOne(Tree filter, Tree replacement, ReplaceOptions options) { return singleResult(collection.replaceOne(toBson(filter), (Document) toBson(replacement), options)) .thenWithResult(res -> { return updateResultToTree(res); }); } // --- UPDATE ONE DOCUMENT --- /** * Update a single document in the collection according to the specified * arguments. <br> * Sample to update result structure: * * <pre> * { * "matched": 10, * "modified": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * Tree update = new Tree(); * update.put("field1", 123); * * updateOne(eq("field1", 123), update).then(res -&gt; { * * // Replace operation finished * int modified = res.get("modified"); * return modified &gt; 0; * * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param filter * a document describing the query filter, which may not be null. * @param update * a document describing the update, which may not be null. The * update to apply must include only update operators. * @return a Promise with a single element the update result structure */ protected Promise updateOne(Tree filter, Tree update) { Tree rec = prepareForUpdate(update); return singleResult(collection.updateOne(toBson(filter), toBson(rec))).thenWithResult(res -> { return updateResultToTree(res); }); } // --- UPDATE MANY DOCUMENTS --- /** * Update all documents in the collection according to the specified * arguments. <br> * Sample to update result structure: * * <pre> * { * "matched": 10, * "modified": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * Tree update = new Tree(); * update.put("field1", 123); * * updateMany(eq("field1", 123), update).then(res -&gt; { * * // Replace operation finished * int modified = res.get("modified"); * return modified &gt; 0; * * }); * </pre> * * @param filter * a document describing the query filter, which may not be null. * @param update * a document describing the update, which may not be null. The * update to apply must include only update operators. * @return a Promise with a single element the update result structure */ protected Promise updateMany(Tree filter, Tree update) { Tree rec = prepareForUpdate(update); return singleResult(collection.updateMany(toBson(filter), toBson(rec))).thenWithResult(res -> { return updateResultToTree(res); }); } // --- DELETE ONE DOCUMENT --- /** * Removes at most one document from the collection that matches the given * filter. If no documents match, the collection is not modified.<br> * Sample to delete result structure: * * <pre> * { * "deleted": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * deleteOne(eq("field1", 123)).then(res -&gt; { * * // Delete operation finished * int deleted = res.get("deleted"); * return deleted &gt; 0; * * }); * </pre> * * @param filter * the query filter to apply the the delete operation * @return a Promise with a single element the deleted result structure */ protected Promise deleteOne(Tree filter) { return singleResult(collection.deleteOne(toBson(filter))).thenWithResult(res -> { return deleteResultToTree(res); }); } /** * Removes at most one document from the collection that matches the given * filter. If no documents match, the collection is not modified.<br> * Sample to delete result structure: * * <pre> * { * "deleted": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * DeleteOptions opts = new DeleteOptions(); * opts.collation(...); * * deleteOne(eq("field1", 123), opts).then(res -&gt; { * * // Delete operation finished * int deleted = res.get("deleted"); * return deleted &gt; 0; * * }); * </pre> * * @param filter * the query filter to apply the the delete operation * @param options * the options to apply to the delete operation * @return a Promise with a single element the deleted result structure */ protected Promise deleteOne(Tree filter, DeleteOptions options) { return singleResult(collection.deleteOne(toBson(filter), options)).thenWithResult(res -> { return deleteResultToTree(res); }); } // --- DELETE ALL DOCUMENTS --- /** * Removes all documents from the collection.<br> * Sample to delete result structure: * * <pre> * { * "deleted": 10, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * deleteAll().then(res -&gt; { * * // Delete operation finished * int deleted = res.get("deleted"); * return deleted &gt; 0; * * }); * </pre> * * @return a Promise with a single element the deleted result structure */ protected Promise deleteAll() { return deleteMany(new Tree()); } // --- DELETE MANY DOCUMENTS --- /** * Removes all documents from the collection that match the given query * filter. If no documents match, the collection is not modified.<br> * Sample to delete result structure: * * <pre> * { * "deleted": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * deleteMany(eq("field1", 123)).then(res -&gt; { * * // Delete operation finished * int deleted = res.get("deleted"); * return deleted &gt; 0; * * }); * </pre> * * @param filter * the query filter to apply the the delete operation * @return a Promise with a single element the deleted result structure */ protected Promise deleteMany(Tree filter) { return singleResult(collection.deleteMany(toBson(filter))).thenWithResult(res -> { return deleteResultToTree(res); }); } /** * Removes all documents from the collection that match the given query * filter. If no documents match, the collection is not modified.<br> * Sample to delete result structure: * * <pre> * { * "deleted": 4, * "acknowledged": true * } * </pre> * * Sample of usage: * * <pre> * DeleteOptions opts = new DeleteOptions(); * opts.collation(...); * * deleteMany(eq("field1", 123), opts).then(res -&gt; { * * // Delete operation finished * int deleted = res.get("deleted"); * return deleted &gt; 0; * * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param filter * the query filter to apply the the delete operation * @param options * the options to apply to the delete operation * @return a Promise with a single element the deleted result structure */ protected Promise deleteMany(Tree filter, DeleteOptions options) { return singleResult(collection.deleteMany(toBson(filter), options)).thenWithResult(res -> { return deleteResultToTree(res); }); } // --- COUNT DOCUMENTS --- /** * Counts the number of documents in the collection. Sample of usage: * * <pre> * count().then(res -&gt; { * * // Count operation finished * long numberOfDocuments = res.asLong(); * return numberOfDocuments + " documents found."; * * }); * </pre> * * @return a Promise with a single element indicating the number of * documents */ protected Promise count() { return singleResult(collection.countDocuments()); } /** * Counts the number of documents in the collection according to the given * filters. Sample of usage: * * <pre> * count(eq("field1", 123)).then(res -&gt; { * * // Count operation finished * long numberOfDocuments = res.asLong(); * * Tree rsp = new Tree(); * rsp.put("count", numberOfDocuments); * return rsp; * * }); * </pre> * * @param filter * the query filter * @return a Promise with a single element indicating the number of * documents */ protected Promise count(Tree filter) { return singleResult(collection.countDocuments(toBson(filter))); } /** * Counts the number of documents in the collection according to the given * options. Sample of usage: * * <pre> * CountOptions opts = new CountOptions(); * opts.maxTime(10, TimeUnit.SECONDS); * * count(eq("field1", 123), opts).then(res -&gt; { * * // Count operation finished * long numberOfDocuments = res.asLong(); * * Tree rsp = new Tree(); * rsp.put("count", numberOfDocuments); * return rsp; * * }); * </pre> * * @param filter * the query filter * @param options * the options describing the count * @return a Promise with a single element indicating the number of * documents */ protected Promise count(Tree filter, CountOptions options) { return singleResult(collection.countDocuments(toBson(filter), options)); } // --- FIND ONE DOCUMENT --- /** * Finds one document by the specified query filter. Sample of usage: * * <pre> * findOne(eq("field1", 123)).then(res -&gt; { * * // Find operation finished * if (res != null) { * String firstName = res.get("firstName", ""); * int age = res.get("age", 0); * } * return res; * * }); * </pre> * * @param filter * the query filter * @return a Promise with the selected document. */ protected Promise findOne(Tree filter) { FindPublisher<Document> find = collection.find(); if (filter != null) { find.filter(toBson(filter)); } find.batchSize(1); return singleResult(find.first()); } // --- FIND MANY DOCUMENTS --- /** * Queries the all records from the collection by the specified filter. * Sample of usage: * * <pre> * find(gte("field1", 123), sort).then(res -&gt; { * // Find operation finished * }); * </pre> * * @param filter * the query filter * @return a Promise with the selected documents and the max number of * selectable documents. */ protected Promise find(Tree filter) { return find(filter, null, 0, maxItemsPerQuery); } /** * Queries the all records from the collection by the specified filter. * Sample of usage: * * <pre> * Tree sort = new Tree(); * sort.put("field1", -1); * find(lt("field1", 100), sort).then(res -&gt; { * // Find operation finished * }); * </pre> * * @param filter * the query filter * @param sort * sort filter (or null) * @return a Promise with the selected documents and the max number of * selectable documents. */ protected Promise find(Tree filter, Tree sort) { return find(filter, sort, 0, maxItemsPerQuery); } /** * Queries the specified number of records from the collection. Sample of * usage: * * <pre> * Tree sort = new Tree(); * sort.put("field2", 1); * find(lte("field1", 123), null, 0, 10).then(res -&gt; { * * // Find operation finished * int maxNumberOfSelectableDocuments = res.get("count"); * for (Tree doc : res.get("rows")) { * String firstName = res.get("firstName", ""); * } * return res; * * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param filter * the query filter * @param sort * sort filter (or null) * @param first * number of skipped documents (0 = get from the first record) * @param limit * number of retrieved documents * @return a Promise with the selected documents and the max number of * selectable documents. */ protected Promise find(Tree filter, Tree sort, int first, int limit) { // Set query limit final int l; if (limit < 1 || limit > maxItemsPerQuery) { l = maxItemsPerQuery; } else { l = limit; } // Find FindPublisher<Document> find = collection.find(); Bson countFilter = filter == null ? null : toBson(filter); if (filter != null) { find.filter(countFilter); } if (sort != null) { find.sort(toBson(sort)); } if (first > 0) { find.skip(first); } find.batchSize(Math.min(l, 50)); find.limit(l); // Get rows and size return collectAll(find).then(res -> { if (countFilter == null) { return singleResult(collection.countDocuments()).thenWithResult(max -> { res.put(COUNT, max); return res; }); } return singleResult(collection.countDocuments(countFilter)).thenWithResult(max -> { res.put(COUNT, max); return res; }); }); } // --- FIND ONE AND DELETE --- /** * Atomically find a document and remove it. Sample of usage: * * <pre> * findOneAndDelete(eq("field1", 123)).then(res -&gt; { * * // Delete operation finished * if (res != null) { * String firstName = res.get("firstName", ""); * int age = res.get("age", 0); * } * return res; * * }); * </pre> * * @param filter * the query filter to find the document with * @return a Promise with a single element the document that was removed. If * no documents matched the query filter, then null will be returned */ protected Promise findOneAndDelete(Tree filter) { return singleResult(collection.findOneAndDelete(toBson(filter))); } /** * Atomically find a document and remove it. Sample of usage: * * <pre> * FindOneAndDeleteOptions opts = new FindOneAndDeleteOptions(); * opts.maxTime(10, TimeUnit.SECONDS); * * findOneAndDelete(eq("field1", 123), opts).then(res -&gt; { * * // Delete operation finished * if (res != null) { * String firstName = res.get("firstName", ""); * int age = res.get("age", 0); * } * return res; * * }); * </pre> * * @param filter * the query filter to find the document with * @param options * the options to apply to the operation * @return a Promise with a single element the document that was removed. If * no documents matched the query filter, then null will be returned */ protected Promise findOneAndDelete(Tree filter, FindOneAndDeleteOptions options) { return singleResult(collection.findOneAndDelete(toBson(filter), options)); } // --- FIND ONE AND REPLACE --- /** * Atomically find a document and replace it. Sample of usage: * * <pre> * Tree replacement = new Tree(); * replacement.put("field1", 222); * * findOneAndReplace(eq("field1", 123), replacement).then(res -&gt; { * * // Replace operation finished * if (res != null) { * String firstName = res.get("firstName", ""); * int age = res.get("age", 0); * } * return res; * * }); * </pre> * * @param filter * the query filter to apply the the replace operation * @param replacement * the replacement document * @return a Promise with a single element the document that was replaced. * If no documents matched the query filter, then null will be * returned */ protected Promise findOneAndReplace(Tree filter, Tree replacement) { return singleResult(collection.findOneAndReplace(toBson(filter), (Document) toBson(replacement))); } /** * Atomically find a document and replace it. Sample of usage: * * <pre> * Tree replacement = new Tree(); * replacement.put("field1", 111); * * FindOneAndReplaceOptions opts = new FindOneAndReplaceOptions(); * opts.upsert(true); * * findOneAndReplace(eq("field1", 123), replacement, opts).then(res -&gt; { * * // Replace operation finished * if (res != null) { * String firstName = res.get("firstName", ""); * int age = res.get("age", 0); * } * return res; * * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param filter * the query filter to apply the the replace operation * @param replacement * the replacement document * @param options * the options to apply to the operation * @return a Promise with a single element the document that was replaced. * If no documents matched the query filter, then null will be * returned */ protected Promise findOneAndReplace(Tree filter, Tree replacement, FindOneAndReplaceOptions options) { return singleResult(collection.findOneAndReplace(toBson(filter), (Document) toBson(replacement), options)); } // --- FIND ONE AND UPDATE --- /** * Atomically find a document and update it. Sample of usage: * * <pre> * Tree update = new Tree(); * update.put("field1", 345); * * findOneAndUpdate(eq("field1", 123), update).then(res -&gt; { * * // Update operation finished * if (res != null) { * String firstName = res.get("firstName", ""); * int age = res.get("age", 0); * } * return res; * * }); * </pre> * * @param filter * a document describing the query filter, which may not be null. * @param update * a document describing the update, which may not be null. The * update to apply must include only update operators. * @return a Promise with a single element the document that was updated * before the update was applied. If no documents matched the query * filter, then null will be returned */ protected Promise findOneAndUpdate(Tree filter, Tree update) { Tree rec = prepareForUpdate(update); return singleResult(collection.findOneAndUpdate(toBson(filter), (Document) toBson(rec))); } /** * Atomically find a document and update it. Sample of usage: * * <pre> * Tree update = new Tree(); * update.put("field1", 345); * * FindOneAndUpdateOptions opts = new FindOneAndUpdateOptions(); * opts.upsert(true); * * findOneAndUpdate(eq("field1", 123), update, opts).then(res -&gt; { * * // Update operation finished * if (res != null) { * String firstName = res.get("firstName", ""); * int age = res.get("age", 0); * } * return res; * * }); * </pre> * * @param filter * a document describing the query filter, which may not be null. * @param update * a document describing the update, which may not be null. The * update to apply must include only update operators. * @param options * the options to apply to the operation * @return a Promise with a single element the document that was updated. */ protected Promise findOneAndUpdate(Tree filter, Tree update, FindOneAndUpdateOptions options) { Tree rec = prepareForUpdate(update); return singleResult(collection.findOneAndUpdate(toBson(filter), (Document) toBson(rec), options)); } // --- MAP/REDUCE --- /** * Aggregates documents according to the specified map-reduce function. * Sample of usage: * * <pre> * String mapFunction = "..."; * String reduceFunction = "..."; * mapReduce(mapFunction, reduceFunction).then(res -&gt; { * // Operation finished * }).then(res -&gt; { * // ... * }).then(res -&gt; { * // ... * }).catchError(err -&gt; { * // Error handler * }); * </pre> * * @param mapFunction * A JavaScript function that associates or "maps" a value with a * key and emits the key and value pair. * @param reduceFunction * A JavaScript function that "reduces" to a single object all * the values associated with a particular key. * @return an Promise containing the result of the map-reduce operation */ protected Promise mapReduce(String mapFunction, String reduceFunction) { return collectAll(collection.mapReduce(mapFunction, reduceFunction)); } // --- PRIVATE UTILITIES --- private <T> SingleResultPromise<T> singleResult(Publisher<T> publisher) { return new SingleResultPromise<T>(publisher); } private <T> CollectAllPromise<T> collectAll(Publisher<T> publisher) { return new CollectAllPromise<T>(publisher); } private Tree updateResultToTree(UpdateResult res) { Tree ret = new Tree(); ret.put(MATCHED, res.getMatchedCount()); ret.put(MODIFIED, res.getModifiedCount()); ret.put(ACKNOWLEDGED, res.wasAcknowledged()); BsonValue id = res.getUpsertedId(); if (id != null) { ret.put(ID, id.toString()); } return ret; } private Tree deleteResultToTree(DeleteResult res) { Tree ret = new Tree(); ret.put(DELETED, res.getDeletedCount()); ret.put(ACKNOWLEDGED, res.wasAcknowledged()); return ret; } private Tree prepareForUpdate(Tree record) { if (record.get(SET) == null) { Tree rec = new Tree(); rec.putMap(SET).copyFrom(record); return rec; } return record; } // --- GETTERS / SETTERS --- public final int getMaxItemsPerQuery() { return maxItemsPerQuery; } public final void setMaxItemsPerQuery(int maxItemsPerQuery) { this.maxItemsPerQuery = maxItemsPerQuery; } public final MongoCollection<Document> getCollection() { return collection; } public final void setCollection(MongoCollection<Document> collection) { this.collection = collection; } }
27.623098
115
0.605989
741f2c47396c9c328e6e41226a4cf755bee9eb7f
1,817
/* * 文件名称:EdenStatus.java * 系统名称:[系统名称] * 模块名称:[模块名称] * 软件版权:Copyright (c) 2011-2018, liming20110711@163.com All Rights Reserved. * 功能说明:[请在此处输入功能说明] * 开发人员:Rushing0711 * 创建日期:20180806 09:58 * 修改记录: * <Version> <DateSerial> <Author> <Description> * 1.0.0 20180806-01 Rushing0711 M201808060958 新建文件 ********************************************************************************/ package com.ishanshan.gateway.exception; import lombok.Getter; @Getter public enum GatewayStatus { SUCCESS(0, "成功"), GATEWAY_ERROR(990000, "网关异常"), GATEWAY_PRE_ERROR(990100, "限流控制"), GATEWAY_PRE_REQUEST_COUNT_LIMIT(990101, "系统繁忙,请稍后重试"), GATEWAY_PRE_BAD_REQUEST(990102, "请求地址不合法"), GATEWAY_PRE_ONLY_POST_JSON_SUPPORT(990103, "仅支持POST JSON形式的请求"), GATEWAY_PRE_TOKEN_NOT_FOUND(990104, "jwtToken not found!"), GATEWAY_PRE_TOKEN_INVALID(990105, "jwtToken invalid"), GATEWAY_PRE_TOKEN_EXPIRED(990106, "jwtToken expired"), GATEWAY_PRE_TOKEN_FORGED(990107, "jwtToken 被篡改"), GATEWAY_PRE_USER_FORCED_LOGOUT(990108, "您已被强制登出,请及时登录修改密码"), GATEWAY_PRE_COMBINE_REQUEST_BODY_ERROR(990108, "更新请求信息失败"), GATEWAY_ROUTE_ERROR(990200, "路由过滤异常"), GATEWAY_POST_ERROR(990300, "后置过滤异常"), GATEWAY_POST_PARSE_RESPONSE_BODY_ERROR(990301, "后置过滤解析应答体错误"), GATEWAY_POST_RESPONSE_BODY_EMPTY_ERROR(990302, "服务应答体为空"), GATEWAY_POST_GENERATE_TOKEN_ERROR(990303, "生成token失败"), GATEWAY_POST_MISS_AUTH_DETAIL_ERROR(990304, "用户标识信息不存在"), GATEWAY_POST_PARSE_AUTH_SESSION_CACHE_ERROR(990301, "后置过滤解析用户缓存错误"), GATEWAY_ERROR_FILTER_ERROR(990100, "错误过滤异常"), ; private Integer code; private String message; GatewayStatus(Integer code, String message) { this.code = code; this.message = message; } }
33.036364
82
0.689048
6b80f8b001cba9fd59f2119ae6190faa3f11f0fd
69,291
/* * 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.sis.util.collection; import java.io.IOException; import java.io.Serializable; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Iterator; import java.util.Comparator; import java.util.SortedSet; import java.util.AbstractSet; import java.util.NoSuchElementException; import java.util.ConcurrentModificationException; import org.apache.sis.measure.NumberRange; import org.apache.sis.measure.Range; import org.apache.sis.util.ArraysExt; import org.apache.sis.util.ArgumentChecks; import org.apache.sis.util.resources.Errors; import static org.apache.sis.util.Numbers.*; /** * An ordered set of disjoint ranges where overlapping ranges are merged. * All {@code add} and {@code remove} operations defined in this class interact with the existing * ranges, merging or splitting previously added ranges in order to ensure that every ranges in a * {@code RangeSet} are always disjoint. More specifically: * * <ul> * <li>When a range is {@linkplain #add(Range) added}, {@code RangeSet} first looks for existing * ranges overlapping the specified range. If overlapping ranges are found, then those ranges * are merged as of {@link Range#union(Range)}. Consequently, adding ranges may in some * circumstances <strong>reduce</strong> the {@linkplain #size() size} of this set.</li> * <li>Conversely, when a range is {@linkplain #remove(Object) removed}, {@code RangeSet} first * looks if that range is in the middle of an existing range. If such range is found, then * the enclosing range is splitted as of {@link Range#subtract(Range)}. Consequently, removing * ranges may in some circumstances <strong>increase</strong> the size of this set.</li> * </ul> * * <h2>Inclusive or exclusive endpoints</h2> * {@code RangeSet} requires that {@link Range#isMinIncluded()} and {@link Range#isMaxIncluded()} * return the same values for all instances added to this set. Those values need to be specified * at construction time. If a user needs to store mixed kind of ranges, then he needs to subclass * this {@code RangeSet} class and override the {@link #add(Range)}, {@link #remove(Object)} and * {@link #newRange(Comparable, Comparable)} methods. * * <div class="note"><b>Note:</b> * Current implementation does not yet support open intervals. The ranges shall be either closed intervals, * or half-open. This limitation exists because supporting open intervals implies that the internal array * shall support duplicated values.</div> * * <h2>Extensions to <code>SortedSet</code> API</h2> * This class contains some methods not found in standard {@link SortedSet} API. * Some of those methods look like {@link java.util.List} API, in that they work * with the index of a {@code Range} instance in the sequence of ranges returned * by the iterator. * * <ul> * <li>{@link #indexOfRange(Comparable)} returns the index of the range containing * the given value (if any).</li> * <li>{@link #getMinDouble(int)} and {@link #getMaxDouble(int)} return the endpoint values * in the range at the given index as a {@code double} without the cost of creating a * {@link Number} instance.</li> * <li>{@link #getMinLong(int)} and {@link #getMaxLong(int)} are equivalent to the above * methods for the {@code long} primitive type, used mostly for {@link java.util.Date} * values (see implementation note below).</li> * <li>{@link #intersect(Range)} provides a more convenient way than {@code subSet(…)}, * {@code headSet(…)} and {@code tailSet(…)} for creating views over subsets of a * {@code RangeSet}.</li> * <li>{@link #trimToSize()} frees unused space.</li> * </ul> * * <h2>Implementation note</h2> * For efficiency reasons, this set stores the range values in a Java array of primitive type if * possible. The {@code Range} instances given in argument to the {@link #add(Range)} method are * not retained by this class. Ranges are recreated during iterations by calls to the * {@link #newRange(Comparable, Comparable)} method. Subclasses can override that method if they * need to customize the range objects to be created. * * <p>While it is possible to create {@code RangeSet<Date>} instances, it is more efficient to * use {@code RangeSet<Long>} with millisecond values because {@code RangeSet} will internally * use {@code long[]} arrays in the later case.</p> * * @author Martin Desruisseaux (Geomatys) * @author Rémi Maréchal (Geomatys) * @version 0.5 * * @param <E> the type of range elements. * * @see Range * * @since 0.3 * @module */ public class RangeSet<E extends Comparable<? super E>> extends AbstractSet<Range<E>> implements CheckedContainer<Range<E>>, SortedSet<Range<E>>, Cloneable, Serializable { /** * Serial number for inter-operability with different versions. */ private static final long serialVersionUID = 7493555225994855486L; /** * The range comparator returned by {@link RangeSet#comparator()}. This comparator * is defined for compliance with the {@link SortedSet} contract, but is not not * used by the {@code RangeSet} implementation. * * <p>This comparator can order non-ambiguous ranges: the minimum and maximum values * of one range shall both be smaller, equal or greater than the values of the other * range. In case of ambiguity (when a range in included in the other range), this * comparator throws an exception. Such ambiguities should not happen in sequences * of ranges created by {@code RangeSet}.</p> * * @param <E> the type of range elements. */ private static final class Compare<E extends Comparable<? super E>> implements Comparator<Range<E>>, Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = 8688450091923783564L; /** * The singleton instance, as a raw type in order to allow * {@link RangeSet#comparator()} to return the same instance for all types. */ @SuppressWarnings("rawtypes") static final Compare INSTANCE = new Compare(); /** * Constructor for the singleton instance only. */ private Compare() { } /** * Compares the given range instance. * See class-javadoc for more information. */ @Override public int compare(final Range<E> r1, final Range<E> r2) { int cmin = r1.getMinValue().compareTo(r2.getMinValue()); int cmax = r1.getMaxValue().compareTo(r2.getMaxValue()); if (cmin == 0) { final boolean included = r1.isMinIncluded(); if (r2.isMinIncluded() != included) { cmin = included ? -1 : +1; } } if (cmax == 0) { final boolean included = r1.isMaxIncluded(); if (r2.isMaxIncluded() != included) { cmax = included ? +1 : -1; } } if (cmin == cmax) return cmax; // Easy case: min and max are both greater, smaller or eq. if (cmin == 0) return cmax; // Easy case: only max value differ. if (cmax == 0) return cmin; // Easy case: only min value differ. throw new IllegalArgumentException(Errors.format( // One range is included in the other. Errors.Keys.UndefinedOrderingForElements_2, r1, r2)); } /** * Returns the singleton instance on deserialization. */ Object readResolve() throws ObjectStreamException { return INSTANCE; } }; /** * The type of elements in the ranges. If the element are numbers, * then the value is the wrapper type (not the primitive type). * * @see Range#getElementType() */ protected final Class<E> elementType; /** * The primitive type, as one of {@code DOUBLE}, {@code FLOAT}, {@code LONG}, {@code INTEGER}, * {@code SHORT}, {@code BYTE}, {@code CHARACTER} enumeration. If the {@link #elementType} is * not the wrapper of a primitive type, then this field value is {@code OTHER}. */ private final byte elementCode; /** * {@code true} if the minimal values of ranges in this set are inclusive, or {@code false} * if exclusive. This value is specified at construction time and enforced when ranges are * added or removed. * * @see Range#isMinIncluded() */ protected final boolean isMinIncluded; /** * {@code true} if the maximal values of ranges in this set are inclusive, or {@code false} * if exclusive. This value is specified at construction time and enforced when ranges are * added or removed. * * @see Range#isMaxIncluded() */ protected final boolean isMaxIncluded; /** * The array of ranges. It may be either an array of Java primitive type like {@code int[]} or * {@code float[]}, or an array of {@link Comparable} elements. All elements at even indices * are minimal values, and all elements at odd indices are maximal values. Elements in this * array must be strictly increasing without duplicated values. * * <div class="note"><b>Note:</b> * The restriction against duplicated values will need to be removed in a future version * if we want to support open intervals. All binary searches in this class will need to * take in account the possibility for duplicated values.</div> */ private Object array; /** * The length of valid elements in the {@linkplain #array}. Since the array contains both * the minimum and maximum values, its length is twice the number of ranges in this set. * * @see #size() */ private transient int length; /** * The amount of modifications applied on the range {@linkplain #array}. * Used for checking concurrent modifications. */ private transient int modCount; /** * Constructs an initially empty set of ranges. * This constructor is provided for sub-classing only. * Client code should use the static {@link #create(Class, boolean, boolean)} method instead. * * @param elementType the type of the range elements. * @param isMinIncluded {@code true} if the minimal values are inclusive, or {@code false} if exclusive. * @param isMaxIncluded {@code true} if the maximal values are inclusive, or {@code false} if exclusive. */ protected RangeSet(final Class<E> elementType, final boolean isMinIncluded, final boolean isMaxIncluded) { ArgumentChecks.ensureNonNull("elementType", elementType); // Following assertion may fail only if the user bypass the parameterized type checks. assert Comparable.class.isAssignableFrom(elementType) : elementType; this.elementType = elementType; this.elementCode = getEnumConstant(elementType); this.isMinIncluded = isMinIncluded; this.isMaxIncluded = isMaxIncluded; if (!isMinIncluded && !isMaxIncluded) { /* * We do not localize this error message because it may disaspear * in a future SIS version if we decide to support closed intervals. */ throw new IllegalArgumentException("Open intervals are not yet supported."); } } /** * Constructs an initially empty set of ranges. * * @param <E> the type of range elements. * @param elementType the type of the range elements. * @param isMinIncluded {@code true} if the minimal values are inclusive, or {@code false} if exclusive. * @param isMaxIncluded {@code true} if the maximal values are inclusive, or {@code false} if exclusive. * @return a new range set for range elements of the given type. */ @SuppressWarnings({"unchecked","rawtypes"}) public static <E extends Comparable<? super E>> RangeSet<E> create(final Class<E> elementType, final boolean isMinIncluded, final boolean isMaxIncluded) { ArgumentChecks.ensureNonNull("elementType", elementType); if (Number.class.isAssignableFrom(elementType)) { return new Numeric(elementType, isMinIncluded, isMaxIncluded); } return new RangeSet<>(elementType, isMinIncluded, isMaxIncluded); } /** * Returns the type of elements in this <em>collection</em>, which is always {@code Range}. * This is not the type of minimal and maximal values in range objects. */ @Override @SuppressWarnings("unchecked") public final Class<Range<E>> getElementType() { return (Class) Range.class; } /** * Returns the comparator associated with this sorted set. */ @Override @SuppressWarnings({"unchecked","rawtypes"}) // Because we share the same static instance. public Comparator<Range<E>> comparator() { return Compare.INSTANCE; } /** * Removes all elements from this set of ranges. */ @Override public void clear() { if (array instanceof Object[]) { Arrays.fill((Object[]) array, 0, length, null); // Let GC do its job. } length = 0; modCount++; } /** * Returns the number of ranges in this set. */ @Override public int size() { assert (length & 1) == 0; // Length must be even. return length >>> 1; } /** * Unconditionally copies the internal array in a new array having just the required length. */ @SuppressWarnings("SuspiciousSystemArraycopy") private void reallocate() { if (length == 0) { array = null; } else { final Object oldArray = array; array = Array.newInstance(oldArray.getClass().getComponentType(), length); System.arraycopy(oldArray, 0, array, 0, length); } } /** * Trims this set to the minimal amount of memory required for holding its data. * This method may be invoked after all elements have been {@linkplain #add(Range) added} * in order to free unused memory. */ public final void trimToSize() { // This method is final because equals(Object) and other methods rely on this behavior. if (array != null && Array.getLength(array) != length) { reallocate(); // Will set the array to null if length == 0. assert isSorted(); } } /** * Inserts two values at the given index. The underlying {@linkplain #array} shall be * non-null before this method is invoked. This method increases the array size as needed. * * @param lower the index where to insert the values. * @param minValue the first value to insert. * @param maxValue the second value to insert. */ @SuppressWarnings("SuspiciousSystemArraycopy") private void insertAt(final int lower, final E minValue, final E maxValue) { final Object oldArray = array; final int capacity = Array.getLength(oldArray); if (length + 2 > capacity) { array = Array.newInstance(oldArray.getClass().getComponentType(), 2*Math.max(capacity, 8)); System.arraycopy(oldArray, 0, array, 0, lower); } System.arraycopy(oldArray, lower, array, lower+2, length-lower); Array.set(array, lower, minValue); Array.set(array, lower+1, maxValue); length += 2; modCount++; } /** * Removes the values in the given range. The underlying {@linkplain #array} shall be * non-null before this method is invoked. * * @param lower first value to remove, inclusive. * @param upper last value to remove, exclusive. */ @SuppressWarnings("SuspiciousSystemArraycopy") private void removeAt(final int lower, final int upper) { final int oldLength = length; System.arraycopy(array, upper, array, lower, oldLength - upper); length -= (upper - lower); if (array instanceof Object[]) { // Clear references so the garbage collector can do its job. Arrays.fill((Object[]) array, length, oldLength, null); } modCount++; } /** * Returns {@code true} if the element in the array are sorted. * This method is used for assertions only. The array shall be * trimmed to size before this method is invoked. */ @SuppressWarnings("unchecked") private boolean isSorted() { if (array == null) { return true; } final boolean strict = isMinIncluded | isMaxIncluded; switch (elementCode) { case DOUBLE: return ArraysExt.isSorted((double[]) array, strict); case FLOAT: return ArraysExt.isSorted((float[]) array, strict); case LONG: return ArraysExt.isSorted((long[]) array, strict); case INTEGER: return ArraysExt.isSorted((int[]) array, strict); case SHORT: return ArraysExt.isSorted((short[]) array, strict); case BYTE: return ArraysExt.isSorted((byte[]) array, strict); case CHARACTER: return ArraysExt.isSorted((char[]) array, strict); default: return ArraysExt.isSorted((E[]) array, strict); } } /** * Returns the index of {@code value} in {@link #array}. This method delegates to * one of {@code Arrays.binarySearch} methods, depending on element primary type. * * @param value the value to search. * @param lower index of the first value to examine. * @param upper index after the last value to examine. */ final int binarySearch(final E value, final int lower, final int upper) { switch (elementCode) { case DOUBLE: return Arrays.binarySearch((double[]) array, lower, upper, (Double) value); case FLOAT: return Arrays.binarySearch((float[]) array, lower, upper, (Float) value); case LONG: return Arrays.binarySearch((long[]) array, lower, upper, (Long) value); case INTEGER: return Arrays.binarySearch((int[]) array, lower, upper, (Integer) value); case SHORT: return Arrays.binarySearch((short[]) array, lower, upper, (Short) value); case BYTE: return Arrays.binarySearch((byte[]) array, lower, upper, (Byte) value); case CHARACTER: return Arrays.binarySearch((char[]) array, lower, upper, (Character) value); default: return Arrays.binarySearch((Object[]) array, lower, upper, value); } } /** * Ensures that the given minimum value is not greater than the maximum value. * This method is used for argument checks. */ private static <E extends Comparable<? super E>> void ensureOrdered(final E minValue, final E maxValue) { if (minValue.compareTo(maxValue) > 0) { throw new IllegalArgumentException(Errors.format(Errors.Keys.IllegalRange_2, minValue, maxValue)); } } /** * Adds a range to this set. If the specified range overlaps existing ranges, * then the existing ranges will be merged as of {@link Range#union(Range)}. * In other words, invoking this method may <strong>reduce</strong> the * {@linkplain #size() size} of this set. * * <p>The default implementation does nothing if the given range {@linkplain Range#isEmpty() is * empty}. Otherwise this method ensures that the {@code isMinIncluded} and {@code isMaxIncluded} * match the ones given to the constructor of this {@code RangeSet}, then delegates to * {@link #add(Comparable, Comparable)}.</p> * * @param range the range to add. * @return {@code true} if this set changed as a result of this method call. * @throws IllegalArgumentException if the {@code isMinIncluded} or {@code isMaxIncluded} * property does not match the one given at this {@code RangeSet} constructor. */ @Override public boolean add(final Range<E> range) throws IllegalArgumentException { ArgumentChecks.ensureNonNull("range", range); if (range.isEmpty()) { return false; } if (range.isMinIncluded() != isMinIncluded || range.isMaxIncluded() != isMaxIncluded) { throw new IllegalArgumentException(Errors.format( Errors.Keys.IllegalArgumentValue_2, "range", range)); } return add(range.getMinValue(), range.getMaxValue()); } /** * Adds a range of values to this set. If the specified range overlaps existing ranges, then * the existing ranges will be merged. This may result in smaller {@linkplain #size() size} * of this set. * * @param minValue the minimal value. * @param maxValue the maximal value. * @return {@code true} if this set changed as a result of this method call. * @throws IllegalArgumentException if {@code minValue} is greater than {@code maxValue}. */ public boolean add(final E minValue, final E maxValue) throws IllegalArgumentException { ArgumentChecks.ensureNonNull("minValue", minValue); ArgumentChecks.ensureNonNull("maxValue", maxValue); /* * If this set is initially empty, just store the given range directly. */ if (array == null) { ensureOrdered(minValue, maxValue); Class<?> type = elementType; if (type != Boolean.class) { // Because there is no Arrays.binarySearch(boolean[], …) method. type = wrapperToPrimitive(type); } array = Array.newInstance(type, 8); Array.set(array, 0, minValue); Array.set(array, 1, maxValue); length = 2; modCount++; return true; } final int modCountChk = modCount; int i0 = binarySearch(minValue, 0, length); int i1 = binarySearch(maxValue, (i0 >= 0) ? i0 : ~i0, length); if (i0 < 0) { i0 = ~i0; // Really tild operator, not minus sign. if ((i0 & 1) == 0) { /* * If the "insertion point" is outside any existing range, if the maximum value * is not present neither in this set (i1 < 0) and if its insertion point is the * same, then insert the new range in the space between two existing ranges. */ if (i0 == ~i1) { // Includes the (i0 == length) case. ensureOrdered(minValue, maxValue); insertAt(i0, minValue, maxValue); return true; } /* * Expand an existing range in order to contains the new minimal value. * * index: 0 1 2 3 4 5 * range: ███████ ◾◾◾◾██████████ ██████████ * minValue: │ (insertion point i0 == 2) */ Array.set(array, i0, minValue); modCount++; } } /* * If the minimal value "insertion point" is an odd index, this means that the value is * inside an existing range. In such case, just move to the beginning of the existing range. * * index: 0 1 2 3 4 5 * range: ███████ ██████████ ██████████ * minValue: │ (insertion point i0 == 3) * moving i0: ├────┘ */ i0 &= ~1; // Equivalent to executing i0-- only when i0 is odd. if (i1 < 0) { i1 = ~i1; // Really tild operator, not minus sign. if ((i1 & 1) == 0) { /* * If the "insertion point" is outside any existing range, expand the previous * range in order to contain the new maximal value. Note that we known that the * given range overlaps the previous range, otherwise the (i0 == ~i1) block above * would have been executed. * * index: 0 1 2 3 4 5 * range: ███████ ██████████◾◾◾◾ ██████████ * minValue: │ (insertion point i1 == 4) */ Array.set(array, --i1, maxValue); modCount++; } // At this point, i1 is guaranteed to be odd. } /* * Ensure that the index is odd. This means that if the maximum value is the begining of an * existing range, then we move to the end of that range. Otherwise the index is unchanged. */ i1 |= 1; // Equivalent to executing i1++ only if i1 is even. /* * At this point, the index of the [minValue … maxValue] range is now [i0 … i1]. * Remove everything between i0 and i1, excluding i0 and i1 themselves. */ assert getValue(i0).compareTo(maxValue) <= 0; assert getValue(i1).compareTo(minValue) >= 0; final int n = i1 - (++i0); if (n != 0) { removeAt(i0, i1); } assert (Array.getLength(array) >= length) && (length & 1) == 0 : length; return modCountChk != modCount; } /** * Removes a range from this set. If the specified range is inside an existing range, then the * existing range may be splitted in two smaller ranges as of {@link Range#subtract(Range)}. * In other words, invoking this method may <strong>increase</strong> the * {@linkplain #size() size} of this set. * * <p>The {@code isMinIncluded} and {@code isMaxIncluded} properties of the given range * shall be the complement of the ones given to the constructor of this {@code RangeSet}:</p> * <table class="sis"> * <caption>Expected bounds inclusion</caption> * <tr><th>{@code add(…)} values</th> <th>{@code remove(…)} values</th></tr> * <tr><td>{@code [min … max]}</td> <td>{@code (min … max)}</td></tr> * <tr><td>{@code (min … max)}</td> <td>{@code [min … max]}</td></tr> * <tr><td>{@code [min … max)}</td> <td>{@code (min … max]}</td></tr> * <tr><td>{@code (min … max]}</td> <td>{@code [min … max)}</td></tr> * </table> * * <p>The default implementation does nothing if the given object is {@code null}, or is not an * instance of {@code Range}, or {@linkplain Range#isEmpty() is empty}, or its element type is * not equals to the element type of the ranges of this set. Otherwise this method ensures that * the {@code isMinIncluded} and {@code isMaxIncluded} are consistent with the ones given to the * constructor of this {@code RangeSet}, then delegates to {@link #remove(Comparable, Comparable)}.</p> * * @param object the range to remove. * @return {@code true} if this set changed as a result of this method call. * @throws IllegalArgumentException if the {@code isMinIncluded} or {@code isMaxIncluded} * property is not the complement of the one given at this {@code RangeSet} constructor. */ @Override public boolean remove(final Object object) { if (object instanceof Range<?>) { @SuppressWarnings("unchecked") // Type will actally be checked on the line after. final Range<E> range = (Range<E>) object; if (range.getElementType() == elementType) { if (range.isMinIncluded() == isMaxIncluded || range.isMaxIncluded() == isMinIncluded) { throw new IllegalArgumentException(Errors.format( Errors.Keys.IllegalArgumentValue_2, "object", range)); } return remove(range.getMinValue(), range.getMaxValue()); } } return false; } /** * Removes a range of values to this set. If the specified range in inside an existing ranges, * then the existing range may be splitted in two smaller ranges. This may result in greater * {@linkplain #size() size} of this set. * * @param minValue the minimal value. * @param maxValue the maximal value. * @return {@code true} if this set changed as a result of this method call. * @throws IllegalArgumentException if {@code minValue} is greater than {@code maxValue}. */ public boolean remove(final E minValue, final E maxValue) throws IllegalArgumentException { ArgumentChecks.ensureNonNull("minValue", minValue); ArgumentChecks.ensureNonNull("maxValue", maxValue); if (length == 0) return false; // Nothing to do if no data. ensureOrdered(minValue, maxValue); // Search insertion index. int i0 = binarySearch(minValue, 0, length); int i1 = binarySearch(maxValue, (i0 >= 0) ? i0 : ~i0, length); if (i0 < 0) i0 = ~i0; if (i1 < 0) i1 = ~i1; if ((i0 & 1) == 0) { if ((i1 & 1) == 0) { /* * i0 & i1 are even. * Case where min and max value are outside any existing range. * * index : A0 B0 A1 B1 An Bn A(n+1) B(n+1) * range : ███████ ██████████ ◾◾◾ ██████████ ██████████ * |-----------------------------------| * values : minValue (i0) maxValue (i1) * * In this case delete all ranges between minValue and maxValue ([(A1, B1); (An, Bn)]). */ removeAt(i0, i1); } else { /* * i0 is even and i1 is odd. * Case where minValue is outside any existing range and maxValue is inside a specific range. * * index : A0 B0 A1 B1 An Bn A(n+1) B(n+1) * range : ███████ ██████████ ◾◾◾ ██████████ ██████████ * |----------------------------| * values : minValue (i0) maxValue (i1) * * In this case : * - delete all ranges between minValue and maxValue ([(A1, B1); (A(n-1), B(n-1))]). * - and replace range (An; Bn) by new range (MaxValue; Bn). * * Result : * index : A0 B0 i1 Bn A(n+1) B(n+1) * range : ███████ █████ ██████████ ◾◾◾ */ removeAt(i0, i1 & ~1); // equivalent to (i0, i1 - 1) Array.set(array, i0, maxValue); } } else { if ((i1 & 1) == 0) { /* * i0 is odd and i1 is even. * Case where minValue is inside a specific range and maxValue is outside any range. * * index : A0 B0 A1 B1 An Bn A(n+1) B(n+1) * range : ███████ ██████████ ◾◾◾ ██████████ ██████████ * |----------------------------| * values : minValue (i0) maxValue (i1) * * In this case : * - delete all ranges between minValue and maxValue ([(A2, B2); (An, Bn)]). * - and replace range (A1; B1) by new range (A1; i0). * * Result : * index : A0 B0 A1 i0 A(n+1) B(n+1) * range : ███████ █████ ██████████ ◾◾◾ */ removeAt(i0 + 1, i1); Array.set(array, i0, minValue); } else { /* * i0 and i1 are odd. * Case where minValue and maxValue are inside any specific range. * * index : A0 B0 A1 B1 An Bn A(n+1) B(n+1) * range : ███████ ██████████ ◾◾◾ ██████████ ██████████ * |-------------------| * values : minValue (i0) maxValue (i1) * * In this case : * - delete all ranges between minValue and maxValue ([(A2, B2); (A(n-1), B(n-1))]). * - and replace range (A1; B1) by new range (A1; i0). * * Result : * index : A0 B0 A1 i0 i1 Bn A(n+1) B(n+1) * range : ███████ █████ ◾◾◾ █████ ██████████ * * A particularity case exist if i0 equal i1, which means minValue * and maxValue are inside the same specific range. * * index : A0 B0 A1 B1 An Bn * range : ███████ █████████████████████ ◾◾◾ ██████████ * |-------------| * values : minValue (i0) maxValue (i1) * In this case total range number will be increase by one. * * Result : * index : A0 B0 A1 i0 i1 B1 An Bn * range : ███████ █████ █████ ◾◾◾ █████ */ if (i0 == i1) { // Above-cited special case insertAt(i1 + 1, maxValue, getValue(i1)); Array.set(array, i0, minValue); } else { final int di = i1 - i0; assert di >= 2 : di; if (di > 2) { removeAt(i0 + 1, i1 & ~1); // equivalent to (i0 + 1, i1 - 1) } Array.set(array, i0, minValue); Array.set(array, i0 + 1, maxValue); } } } return true; } /** * Returns {@code true} if the given object is an instance of {@link Range} compatible * with this set and contained inside one of the range elements of this set. * If this method returns {@code true}, then: * * <ul> * <li>Invoking {@link #add(Range)} is guaranteed to have no effect.</li> * <li>Invoking {@link #remove(Object)} is guaranteed to modify this set.</li> * </ul> * * Conversely, if this method returns {@code false}, then: * * <ul> * <li>Invoking {@link #add(Range)} is guaranteed to modify this set.</li> * <li>Invoking {@link #remove(Object)} may or may not modify this set. * The consequence of invoking {@code remove(…)} is undetermined because it * depends on whether the given range is outside every ranges in this set, * or if it overlaps with at least one range.</li> * </ul> * * The default implementation checks the type of the given object, then delegates to * <code>{@linkplain #contains(Range, boolean) contains}(object, false)</code>. * * @param object the object to check for inclusion in this set. * @return {@code true} if the given object is contained in this set. */ @Override public boolean contains(final Object object) { if (object instanceof Range<?>) { @SuppressWarnings("unchecked") // We are going to check just the line after. final Range<E> range = (Range<E>) object; if (range.getElementType() == elementType) { return contains(range, false); } } return false; } /** * Returns {@code true} if this set contains the specified element. * * <ul> * <li>If the {@code exact} argument is {@code true}, then this method searches * for an exact match (i.e. this method doesn't check if the given range is * contained in a larger range).</li> * <li>If the {@code exact} argument is {@code false}, then this method * behaves as documented in the {@link #contains(Object)} method.</li> * </ul> * * @param range the range to check for inclusion in this set. * @param exact {@code true} for searching for an exact match, * or {@code false} for searching for inclusion in any range. * @return {@code true} if the given object is contained in this set. */ public boolean contains(final Range<E> range, final boolean exact) { ArgumentChecks.ensureNonNull("range", range); if (exact) { if (range.isMinIncluded() && !range.isMaxIncluded()) { final int index = binarySearch(range.getMinValue(), 0, length); if (index >= 0 && (index & 1) == 0) { return getValue(index+1).compareTo(range.getMaxValue()) == 0; } } } else if (!range.isEmpty()) { int lower = binarySearch(range.getMinValue(), 0, length); if (lower < 0) { lower = ~lower; if ((lower & 1) == 0) { /* * The lower endpoint of the given range falls between * two ranges of this set. */ return false; } } else if ((lower & 1) == 0) { /* * Lower endpoint of the given range matches exactly * the lower endpoint of a range in this set. */ if (!isMinIncluded && range.isMinIncluded()) { return false; } } /* * At this point, the lower endpoint has been determined to be included * in a range of this set. Now check the upper endpoint. */ int upper = binarySearch(range.getMaxValue(), lower, length); if (upper < 0) { upper = ~upper; if ((upper & 1) == 0) { /* * The upper endpoint of the given range falls between * two ranges of this set, or is after all ranges. */ return false; } } else if ((upper & 1) != 0) { /* * Upper endpoint of the given range matches exactly * the upper endpoint of a range in this set. */ if (!isMaxIncluded && range.isMaxIncluded()) { return false; } } return (upper - lower) <= 1; } return false; } /** * Returns the first (lowest) range currently in this sorted set. * * @throws NoSuchElementException if this set is empty. */ @Override public Range<E> first() throws NoSuchElementException { if (length == 0) { throw new NoSuchElementException(); } return getRange(0); } /** * Returns the last (highest) range currently in this sorted set. * * @throws NoSuchElementException if the set is empty. */ @Override public Range<E> last() throws NoSuchElementException { if (length == 0) { throw new NoSuchElementException(); } return getRange(length - 2); } /** * Returns a view of the portion of this range set which is the intersection of * this {@code RangeSet} with the given range. Changes in this {@code RangeSet} * will be reflected in the returned view, and conversely. * * @param subRange the range to intersect with this {@code RangeSet}. * @return a view of the specified range within this range set. */ public SortedSet<Range<E>> intersect(final Range<E> subRange) { ArgumentChecks.ensureNonNull("subRange", subRange); return new SubSet(subRange); } /** * Returns a view of the portion of this sorted set whose elements range * from {@code lower}, inclusive, to {@code upper}, exclusive. * The default implementation is equivalent to the following pseudo-code * (omitting argument checks): * * {@preformat java * return intersect(new Range<E>(elementType, * lower.minValue, lower.isMinIncluded, * upper.minValue, !upper.isMinIncluded)); * } * * <div class="note"><b>API note:</b> * This method takes the minimal value of the {@code upper} argument instead * than the maximal value because the upper endpoint is exclusive.</div> * * @param lower low endpoint (inclusive) of the sub set. * @param upper high endpoint (exclusive) of the sub set. * @return a view of the specified range within this sorted set. * * @see #intersect(Range) */ @Override public SortedSet<Range<E>> subSet(final Range<E> lower, final Range<E> upper) { ArgumentChecks.ensureNonNull("lower", lower); ArgumentChecks.ensureNonNull("upper", upper); final E maxValue = upper.getMinValue(); if (maxValue == null) { throw new IllegalArgumentException(Errors.format( Errors.Keys.IllegalArgumentValue_2, "upper", upper)); } return intersect(new Range<>(elementType, lower.getMinValue(), lower.isMinIncluded(), maxValue, !upper.isMinIncluded())); } /** * Returns a view of the portion of this sorted set whose elements are * strictly less than {@code upper}. * The default implementation is equivalent to the same pseudo-code than the one * documented in the {@link #subSet(Range, Range)} method, except that the lower * endpoint is {@code null}. * * @param upper high endpoint (exclusive) of the headSet. * @return a view of the specified initial range of this sorted set. * * @see #intersect(Range) */ @Override public SortedSet<Range<E>> headSet(final Range<E> upper) { ArgumentChecks.ensureNonNull("upper", upper); final E maxValue = upper.getMinValue(); if (maxValue == null) { throw new IllegalArgumentException(Errors.format( Errors.Keys.IllegalArgumentValue_2, "upper", upper)); } return intersect(new Range<>(elementType, null, false, maxValue, !upper.isMinIncluded())); } /** * Returns a view of the portion of this sorted set whose elements are * greater than or equal to {@code lower}. * The default implementation is equivalent to the same pseudo-code than the one * documented in the {@link #subSet(Range, Range)} method, except that the upper * endpoint is {@code null}. * * @param lower low endpoint (inclusive) of the tailSet. * @return a view of the specified final range of this sorted set. * * @see #intersect(Range) */ @Override public SortedSet<Range<E>> tailSet(final Range<E> lower) { ArgumentChecks.ensureNonNull("lower", lower); return intersect(new Range<>(elementType, lower.getMinValue(), lower.isMinIncluded(), null, false)); } /** * A view over a subset of {@link RangeSet}. * Instances of this class are created by the {@link RangeSet#intersect(Range)} method. * * @see RangeSet#intersect(Range) */ private final class SubSet extends AbstractSet<Range<E>> implements SortedSet<Range<E>>, Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = 3093791428299754372L; /** * The minimal and maximal values of this subset, */ private Range<E> subRange; /** * Index of {@link #subRange} minimum and maximum values in the array of the enclosing {@code RangeSet}. * Those indices need to be recomputed every time the enclosing {@code RangeSet} has been modified. * * @see #updateBounds() */ private transient int lower, upper; /** * Modification count of the enclosing {@link RangeSet}, used for detecting changes. */ private transient int modCount; /** * Creates a new subset of the enclosing {@code RangeSet} between the given values. * * @param subRange the range to intersect with the enclosing {@code RangeSet}. */ SubSet(final Range<E> subRange) { this.subRange = subRange; if (subRange.isEmpty()) { throw new IllegalArgumentException(Errors.format( Errors.Keys.IllegalArgumentValue_2, "subRange", subRange)); } modCount = RangeSet.this.modCount - 1; } /** * Recomputes the {@link #lower} and {@link #upper} indices if they are outdated. * If the indices are already up to date, then this method does nothing. */ private void updateBounds() { if (modCount != RangeSet.this.modCount) { int lower = 0; int upper = length; final E minValue = subRange.getMinValue(); final E maxValue = subRange.getMaxValue(); if (minValue != null) { lower = binarySearch(minValue, 0, upper); if (lower < 0) { lower = ~lower; } lower &= ~1; // Force the index to even value. } if (maxValue != null) { upper = binarySearch(maxValue, lower, upper); if (upper < 0) { upper = ~upper; } /* * If 'upper' is even (i.e. is the index of a minimal value), keep that index * unchanged because this value is exclusive. But if 'upper' is odd (i.e. is * the index of a maximal value), move to the minimal value of the next range. */ upper = (upper + 1) & ~1; } this.lower = lower; this.upper = upper; modCount = RangeSet.this.modCount; } } /** * Returns the comparator, which is the same than the enclosing class. */ @Override public Comparator<Range<E>> comparator() { return RangeSet.this.comparator(); } /** * Clears this subset by removing all elements in the range given to the constructor. */ @Override public void clear() { RangeSet.this.remove(subRange); } /** * Returns the number of ranges in this subset. */ @Override public int size() { updateBounds(); return (upper - lower) >> 1; } /** * Adds a new range in the enclosing {@code RangeSet}, and updates this subset * in order to contain that range. */ @Override public boolean add(final Range<E> range) { final boolean changed = RangeSet.this.add(range); /* * Update the minimal and maximal values if this sub-set has been expanded as * a result of this method call. Note that we don't need to remember that the * indices need to be recomputed, because RangeSet.this.modCount has already * been increased by the enclosing class. */ subRange = subRange.union(range); return changed; } /** * Removes the given range or part of it from the enclosing {@code RangeSet}. * Before to perform the removal, this method intersects the given range with * the range of this subset. */ @Override public boolean remove(Object object) { if (object instanceof Range<?>) { @SuppressWarnings("unchecked") // Type will actally be checked on the line after. final Range<E> range = (Range<E>) object; if (range.getElementType() == elementType) { object = subRange.intersect(range); } } return RangeSet.this.remove(object); } /** * Tests if this subset contains the given range. Before to delegates to the enclosing * class, this method filter-out the ranges that are not contained in the range given * to the constructor of this subset. */ @Override public boolean contains(final Object object) { if (object instanceof Range<?>) { @SuppressWarnings("unchecked") // Type will actally be checked on the line after. final Range<E> range = (Range<E>) object; if (range.getElementType() == elementType && !subRange.contains(range)) { return false; } } return RangeSet.this.contains(object); } /** * Returns the first range in this subset, * intersected with the range given to the constructor. */ @Override public Range<E> first() { updateBounds(); if (lower == upper) { throw new NoSuchElementException(); } return subRange.intersect(getRange(lower)); } /** * Returns the last range in this subset, * intersected with the range given to the constructor. */ @Override public Range<E> last() { updateBounds(); if (lower == upper) { throw new NoSuchElementException(); } return subRange.intersect(getRange(upper - 2)); } /** * Delegates subset creation to the enclosing class. * The new subset will not be bigger than this subset. */ @Override public SortedSet<Range<E>> subSet(Range<E> fromElement, Range<E> toElement) { fromElement = subRange.intersect(fromElement); toElement = subRange.intersect(toElement); return RangeSet.this.subSet(fromElement, toElement); } /** * Delegates subset creation to the enclosing class. * The new subset will not be bigger than this subset. */ @Override public SortedSet<Range<E>> headSet(Range<E> toElement) { toElement = subRange.intersect(toElement); return RangeSet.this.headSet(toElement); } /** * Delegates subset creation to the enclosing class. * The new subset will not be bigger than this subset. */ @Override public SortedSet<Range<E>> tailSet(Range<E> fromElement) { fromElement = subRange.intersect(fromElement); return RangeSet.this.tailSet(fromElement); } /** * Returns an iterator over the elements in this subset. */ @Override public Iterator<Range<E>> iterator() { updateBounds(); return new SubIter(subRange, lower, upper); } } /** * The iterator returned by {@link SubSet#iterator()}. This iterator is similar * to the one returned by {@link RangeSet#iterator()}, except that: * * <ul> * <li>The iteration is restricted to a sub-region of the {@link RangeSet#array}.</li> * <li>The first and last ranges returned by the iterator are intercepted with * the range of the subset (other ranges should not need to be intercepted).</li> * <li>The range removed by {@link #remove()} is intercepted with the range of the * subset.</li> * </ul> * * @author Martin Desruisseaux (Geomatys) * @version 0.3 * @since 0.3 * @module */ private final class SubIter extends Iter { /** * A copy of the {@link SubSet#subRange} field value at the time of iterator creation. */ private final Range<E> subRange; /** * Index of the first element in the {@link RangeSet#array} where to iterate. */ private final int lower; /** * Creates a new iterator for the given portion of the {@link RangeSet#array}. */ SubIter(final Range<E> subRange, final int lower, final int upper) { super(upper); this.subRange = subRange; this.lower = lower; position = lower; } /** * Returns {@code true} if the iterator position is at the first or at the last range. * This method is accurate only when invoked after {@code super.next()}. */ private boolean isFirstOrLast() { return position <= lower+2 || position >= upper; } /** * Returns the next element in the iteration. */ @Override public Range<E> next() { Range<E> range = super.next(); if (isFirstOrLast()) { range = subRange.intersect(range); } return range; } /** * Removes from the underlying collection the last element returned by the iterator. */ @Override public void remove() { if (isFirstOrLast()) { // Default implementation is faster. super.remove(); return; } if (!canRemove) { throw new IllegalStateException(); } if (RangeSet.this.modCount != this.modCount) { throw new ConcurrentModificationException(); } RangeSet.this.remove(subRange.intersect(getRange(position - 2))); canRemove = false; } } /** * Returns an iterator over the elements in this set of ranges. * All elements are {@link Range} objects. */ @Override public Iterator<Range<E>> iterator() { return new Iter(length); } /** * The iterator returned by {@link RangeSet#iterator()}. * All elements are {@link Range} objects. * * @author Martin Desruisseaux (Geomatys) * @version 0.3 * @since 0.3 * @module */ private class Iter implements Iterator<Range<E>> { /** * Modification count at construction time. */ int modCount; /** * Index after the last element in the {@link RangeSet#array} where to iterate. */ final int upper; /** * Current position in {@link RangeSet#array}. */ int position; /** * {@code true} if the {@link #remove()} method can be invoked. */ boolean canRemove; /** * Creates a new iterator for the given portion of the {@link RangeSet#array}. */ Iter(final int upper) { this.upper = upper; this.modCount = RangeSet.this.modCount; } /** * Returns {@code true} if the iteration has more elements. */ @Override public final boolean hasNext() { return position < upper; } /** * Returns the next element in the iteration. */ @Override public Range<E> next() { if (!hasNext()) { throw new NoSuchElementException(); } final Range<E> range = getRange(position); if (RangeSet.this.modCount != this.modCount) { /* * This check has been performed last in case a change occurred * while we were creating the range. */ throw new ConcurrentModificationException(); } position += 2; canRemove = true; return range; } /** * Removes from the underlying collection the last element returned by the iterator. */ @Override public void remove() { if (!canRemove) { throw new IllegalStateException(); } if (RangeSet.this.modCount != this.modCount) { throw new ConcurrentModificationException(); } removeAt(position-2, position); this.modCount = RangeSet.this.modCount; canRemove = false; } } /////////////////////////////////////////////////////////////////////////////// //// List-like API - not usual Set API, but provided for efficiency. //// /////////////////////////////////////////////////////////////////////////////// /** * If the specified value is inside a range, returns the index of this range. * Otherwise, returns {@code -1}. * * @param value the value to search. * @return the index of the range which contains this value, or -1 if there is no such range. */ public int indexOfRange(final E value) { int index = binarySearch(value, 0, length); if (index < 0) { /* * Found an insertion point. Make sure that the insertion * point is inside a range (i.e. before the maximum value). */ index = ~index; // Tild sign, not minus. if ((index & 1) == 0) { return -1; } } else if (!((index & 1) == 0 ? isMinIncluded : isMaxIncluded)) { // The value is equals to an excluded endpoint. return -1; } index /= 2; // Round toward 0 (odd index are maximum values). return index; } /** * Returns a {@linkplain Range#getMinValue() range minimum value} as a {@code long}. * The {@code index} can be any value from 0 inclusive to the set {@link #size() size} * exclusive. The returned values always increase with {@code index}. * Widening conversions are performed as needed. * * @param index the range index, from 0 inclusive to {@link #size() size} exclusive. * @return the minimum value for the range at the specified index, inclusive. * @throws IndexOutOfBoundsException if {@code index} is out of bounds. * @throws ClassCastException if range elements are not convertible to {@code long}. */ public long getMinLong(int index) throws IndexOutOfBoundsException, ClassCastException { if ((index *= 2) >= length) { throw new IndexOutOfBoundsException(); } return Array.getLong(array, index); } /** * Returns a {@linkplain Range#getMinValue() range minimum value} as a {@code double}. * The {@code index} can be any value from 0 inclusive to the set {@link #size() size} * exclusive. The returned values always increase with {@code index}. * Widening conversions are performed as needed. * * @param index the range index, from 0 inclusive to {@link #size() size} exclusive. * @return the minimum value for the range at the specified index, inclusive. * @throws IndexOutOfBoundsException if {@code index} is out of bounds. * @throws ClassCastException if range elements are not convertible to numbers. * * @see org.apache.sis.measure.NumberRange#getMinDouble() */ public double getMinDouble(int index) throws IndexOutOfBoundsException, ClassCastException { if ((index *= 2) >= length) { throw new IndexOutOfBoundsException(); } return Array.getDouble(array, index); } /** * Returns a {@linkplain Range#getMaxValue() range maximum value} as a {@code long}. * The {@code index} can be any value from 0 inclusive to the set {@link #size() size} * exclusive. The returned values always increase with {@code index}. * Widening conversions are performed as needed. * * @param index the range index, from 0 inclusive to {@link #size() size} exclusive. * @return the maximum value for the range at the specified index, inclusive. * @throws IndexOutOfBoundsException if {@code index} is out of bounds. * @throws ClassCastException if range elements are not convertible to {@code long}. */ public long getMaxLong(int index) throws IndexOutOfBoundsException, ClassCastException { if ((index *= 2) >= length) { throw new IndexOutOfBoundsException(); } return Array.getLong(array, index + 1); } /** * Returns a {@linkplain Range#getMaxValue() range maximum value} as a {@code double}. * The {@code index} can be any value from 0 inclusive to the set's {@link #size size} * exclusive. The returned values always increase with {@code index}. * Widening conversions are performed as needed. * * @param index the range index, from 0 inclusive to {@link #size size} exclusive. * @return the maximum value for the range at the specified index, exclusive. * @throws IndexOutOfBoundsException if {@code index} is out of bounds. * @throws ClassCastException if range elements are not convertible to numbers. * * @see org.apache.sis.measure.NumberRange#getMaxDouble() */ public double getMaxDouble(int index) throws IndexOutOfBoundsException, ClassCastException { if ((index *= 2) >= length) { throw new IndexOutOfBoundsException(); } return Array.getDouble(array, index + 1); } /** * Returns the value at the specified index. Even index are lower endpoints, while odd index * are upper endpoints. The index validity must have been checked before this method is invoked. */ final E getValue(final int index) { assert (index >= 0) && (index < length) : index; return elementType.cast(Array.get(array, index)); } /** * Returns the range at the given array index. The given index is relative to * the interval {@link #array}, which is twice the index of range elements. * * @param index the range index, from 0 inclusive to {@link #length} exclusive. */ final Range<E> getRange(final int index) { return newRange(getValue(index), getValue(index+1)); } /** * Returns a new {@link Range} object initialized with the given values. * * @param lower the lower value, inclusive. * @param upper the upper value, exclusive. * @return the new range for the given values. */ protected Range<E> newRange(final E lower, final E upper) { return new Range<>(elementType, lower, isMinIncluded, upper, isMaxIncluded); } /** * A {@link RangeSet} implementation for {@link NumberRange} elements. * * @see RangeSet#create(Class, boolean, boolean) */ private static final class Numeric<E extends Number & Comparable<? super E>> extends RangeSet<E> { private static final long serialVersionUID = 5603640102714482527L; Numeric(final Class<E> elementType, final boolean isMinIncluded, final boolean isMaxIncluded) { super(elementType, isMinIncluded, isMaxIncluded); } @Override protected Range<E> newRange(final E lower, final E upper) { return new NumberRange<>(elementType, lower, isMinIncluded, upper, isMaxIncluded); } } /* * Do not override hash code - or if we do, we shall make sure than the * hash code value is computed as documented in the Set interface. */ /** * Compares the specified object with this set of ranges for equality. * * @param object the object to compare with this range. * @return {@code true} if the given object is equal to this range. */ @Override public boolean equals(final Object object) { if (object == this) { return true; } if (object instanceof RangeSet<?>) { /* * Following code should produce a result identical to super.equals(Object) * without the cost of creating potentially large number of Range elements. */ final RangeSet<?> that = (RangeSet<?>) object; if (length != that.length || elementType != that.elementType || isMinIncluded != that.isMinIncluded || isMaxIncluded != that.isMaxIncluded) { return false; } this.trimToSize(); that.trimToSize(); final Object a1 = this.array; final Object a2 = that.array; switch (elementCode) { case DOUBLE: return Arrays.equals((double[]) a1, (double[]) a2); case FLOAT: return Arrays.equals((float[]) a1, (float[]) a2); case LONG: return Arrays.equals((long[]) a1, (long[]) a2); case INTEGER: return Arrays.equals((int[]) a1, (int[]) a2); case SHORT: return Arrays.equals((short[]) a1, (short[]) a2); case BYTE: return Arrays.equals((byte[]) a1, (byte[]) a2); case CHARACTER: return Arrays.equals((char[]) a1, (char[]) a2); default: return Arrays.equals((Object[]) a1, (Object[]) a2); } } return super.equals(object); // Allow comparison with other Set implementations. } /** * Returns a clone of this range set. * * @return a clone of this range set. */ @Override @SuppressWarnings("unchecked") public RangeSet<E> clone() { final RangeSet<E> set; try { set = (RangeSet<E>) super.clone(); } catch (CloneNotSupportedException exception) { // Should not happen, since we are cloneable. throw new AssertionError(exception); } set.reallocate(); return set; } /** * Invoked before serialization. Trims the internal array to the minimal size * in order to reduce the size of the object to be serialized. * * @param out the output stream where to serialize this range set. * @throws IOException if an I/O error occurred while writing. */ private void writeObject(final ObjectOutputStream out) throws IOException { trimToSize(); out.defaultWriteObject(); } /** * Invoked after deserialization. Initializes the transient fields. * * @param in the input stream from which to deserialize a range set. * @throws IOException if an I/O error occurred while reading or if the stream contains invalid data. * @throws ClassNotFoundException if the class serialized on the stream is not on the classpath. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (array != null) { length = Array.getLength(array); assert isSorted(); } } }
42.535912
122
0.562411
8c822d62bf5a829571d5130337943636f6af84fd
61
package de.jugda.tictactoe.view; public class MainView { }
10.166667
32
0.754098
1f7edd9e8b97b7e52c300f9e543beb986cc44a11
1,275
package com.emichal.imagediff; import net.kroo.GifSequenceWriter; import javax.imageio.stream.ImageOutputStream; import javax.imageio.stream.MemoryCacheImageOutputStream; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; public class AnimationGenerator { private GifSequenceWriter gifWriter; private BufferedImage[] imageArray; private ImageOutputStream output; private int delay = 200; public AnimationGenerator createAnimatedGIF(BufferedImage... images) { imageArray = images; return this; } public AnimationGenerator withDelay(int seconds) { this.delay = seconds * 1000; return this; } public AnimationGenerator toStream(OutputStream stream) throws IOException { output = new MemoryCacheImageOutputStream(stream); gifWriter = getGifWriter(output); return this; } public void build() throws IOException { for (BufferedImage image : imageArray) { gifWriter.writeToSequence(image); } gifWriter.close(); output.close(); } private GifSequenceWriter getGifWriter(ImageOutputStream output) throws IOException { return new GifSequenceWriter(output, delay); } }
26.5625
89
0.708235
6795cb12d2a3f742482f426e38abd1398cda5ed0
4,118
/******************************************************************* * Copyright (c) 2006, All rights reserved * * This software is licensed under the terms of the MIT License, * see the LICENSE file for details. * ******************************************************************/ package net.sf.gm.jdbc.io; import java.io.File; import java.io.InputStream; import net.sf.gm.core.io.DataIOException; import net.sf.gm.core.ui.Progress; import net.sf.gm.jdbc.load.Loader; // /** * The Interface Importer. */ public interface Importer { /** * Process. * * @param commitCount the commit count * @param inputStream the input stream * @param mapColumnsByNames the map columns by names * @param loader the loader * @param con the con * @param batchSize the batch size * @param tableName the table name * @param progress the progress * @param schemaName the schema name * @param catalogName the catalog name * * @return true if succeeded, false if failed * * @throws DataIOException the sql IO exception */ boolean process(Progress progress, Loader loader, InputStream inputStream, String tableName, String schemaName, String catalogName) throws DataIOException; /** * Process. * * @param commitCount the commit count * @param inputPath the input path * @param mapColumnsByNames the map columns by names * @param loader the loader * @param con the con * @param batchSize the batch size * @param tableName the table name * @param progress the progress * @param schemaName the schema name * @param catalogName the catalog name * * @return true if succeeded, false if failed * * @throws DataIOException the sql IO exception */ boolean process(Progress progress, Loader loader, String inputPath, String tableName, String schemaName, String catalogName) throws DataIOException; /** * Process. * * @param list the list * @param commitCount the commit count * @param sort the sort * @param mapColumnsByNames the map columns by names * @param loader the loader * @param delete the delete * @param con the con * @param batchSize the batch size * @param progress the progress * * @return true if succeeded, false if failed * * @throws DataIOException the sql IO exception */ boolean process(Progress progress, Loader loader, TableList list, boolean sort, boolean delete) throws DataIOException; /** * Process. * * @param extension the extension * @param input the input * @param sort the sort * @param tableList the table list * @param loader the loader * @param delete the delete * @param progress the progress * * @return true if succeeded, false if failed * * @throws DataIOException the data IO exception */ public boolean process(final Progress progress, File input, String extension, final Loader loader, boolean sort, boolean delete, File tableList) throws DataIOException; /** * Process. * * @param extension the extension * @param input the input * @param sort the sort * @param loader the loader * @param delete the delete * @param progress the progress * @param tableName the table name * @param schemaName the schema name * @param catalogName the catalog name * * @return true if succeeded, false if failed * * @throws DataIOException the data IO exception */ public boolean process(final Progress progress, File input, String extension, final Loader loader, boolean sort, boolean delete, String catalogName, String schemaName, String tableName) throws DataIOException; }
32.171875
79
0.600049
8e8033b5b8b2a1ef16053fdd25e38c2d286995d7
3,116
/* * Copyright (c) 2016 Uber Technologies, Inc. (hoodie-dev-group@uber.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.hoodie.common.table.log; import com.uber.hoodie.common.model.HoodieLogFile; import com.uber.hoodie.common.table.log.block.HoodieLogBlock; import com.uber.hoodie.exception.HoodieIOException; import java.io.IOException; import java.util.List; import org.apache.avro.Schema; import org.apache.hadoop.fs.FileSystem; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; public class HoodieLogFormatReader implements HoodieLogFormat.Reader { private final List<HoodieLogFile> logFiles; private HoodieLogFileReader currentReader; private final FileSystem fs; private final Schema readerSchema; private final boolean readBlocksLazily; private final boolean reverseLogReader; private int bufferSize; private static final Logger log = LogManager.getLogger(HoodieLogFormatReader.class); HoodieLogFormatReader(FileSystem fs, List<HoodieLogFile> logFiles, Schema readerSchema, boolean readBlocksLazily, boolean reverseLogReader, int bufferSize) throws IOException { this.logFiles = logFiles; this.fs = fs; this.readerSchema = readerSchema; this.readBlocksLazily = readBlocksLazily; this.reverseLogReader = reverseLogReader; this.bufferSize = bufferSize; if (logFiles.size() > 0) { HoodieLogFile nextLogFile = logFiles.remove(0); this.currentReader = new HoodieLogFileReader(fs, nextLogFile, readerSchema, bufferSize, readBlocksLazily, false); } } @Override public void close() throws IOException { if (currentReader != null) { currentReader.close(); } } @Override public boolean hasNext() { if (currentReader == null) { return false; } else if (currentReader.hasNext()) { return true; } else if (logFiles.size() > 0) { try { HoodieLogFile nextLogFile = logFiles.remove(0); this.currentReader = new HoodieLogFileReader(fs, nextLogFile, readerSchema, bufferSize, readBlocksLazily, false); } catch (IOException io) { throw new HoodieIOException("unable to initialize read with log file ", io); } log.info("Moving to the next reader for logfile " + currentReader.getLogFile()); return this.currentReader.hasNext(); } return false; } @Override public HoodieLogBlock next() { return currentReader.next(); } @Override public HoodieLogFile getLogFile() { return currentReader.getLogFile(); } @Override public void remove() { } }
32.123711
119
0.724968
4f4452e6837133e2b30530dd960670e9419e8e09
802
package amino.run.runtime.exception; import amino.run.policy.Library; /** * Exception thrown when method invocation on {@link Library.ServerPolicyLibrary#appObject} failed. * * <p>This exception is caused by application errors, not MicroService errors. It indicates * something wrong in application. Good applications should <em>not</em> cause this exception on * method invocations. * * @author terryz */ public class AppExecutionException extends Exception { public AppExecutionException() { super(); } public AppExecutionException(String message) { super(message); } public AppExecutionException(String message, Throwable cause) { super(message, cause); } public AppExecutionException(Throwable cause) { super(cause); } }
25.870968
99
0.713217
e90a6344d052d6cc1714badcde162fc239abb060
1,314
package com.transparent.politics.services.data; public class GovMemberAverages { private final double averageWeeklyPresenceHours; private final double averageMonthlyCommitteePresence; private final double averageProposedBills; private final double averageApprovedBills; private final double averageGrade; public GovMemberAverages(double averageWeeklyPresenceHours, double averageMonthlyCommitteePresence, double averageProposedBills, double averageApprovedBills, double averageGrade) { this.averageWeeklyPresenceHours = averageWeeklyPresenceHours; this.averageMonthlyCommitteePresence = averageMonthlyCommitteePresence; this.averageProposedBills = averageProposedBills; this.averageApprovedBills = averageApprovedBills; this.averageGrade = averageGrade; } public double getAverageWeeklyPresenceHours() { return averageWeeklyPresenceHours; } public double getAverageMonthlyCommitteePresence() { return averageMonthlyCommitteePresence; } public double getAverageProposedBills() { return averageProposedBills; } public double getAverageApprovedBills() { return averageApprovedBills; } public double getAverageGrade() { return averageGrade; } }
32.04878
161
0.754186
9c2df0f66f345290c4fc01cff8b3cada53bff5d3
26,523
package net.stemmaweb.rest; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import javax.ws.rs.*; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.qmino.miredot.annotations.ReturnType; import net.stemmaweb.model.GraphModel; import net.stemmaweb.model.ReadingModel; import net.stemmaweb.model.RelationModel; import net.stemmaweb.model.RelationTypeModel; import net.stemmaweb.services.DatabaseService; import net.stemmaweb.services.GraphDatabaseServiceProvider; import net.stemmaweb.services.ReadingService; import net.stemmaweb.services.VariantGraphService; import org.neo4j.graphdb.*; import org.neo4j.graphdb.traversal.Traverser; import org.neo4j.graphdb.traversal.Uniqueness; import static net.stemmaweb.rest.Util.jsonerror; import static net.stemmaweb.services.RelationService.returnRelationType; import static net.stemmaweb.services.RelationService.TransitiveRelationTraverser; /** * Comprises all the api calls related to a relation. * can be called by using http://BASE_URL/relation * @author PSE FS 2015 Team2 */ public class Relation { private GraphDatabaseService db; private String tradId; private static final String SCOPE_LOCAL = "local"; private static final String SCOPE_SECTION = "section"; private static final String SCOPE_TRADITION = "tradition"; public Relation(String traditionId) { GraphDatabaseServiceProvider dbServiceProvider = new GraphDatabaseServiceProvider(); db = dbServiceProvider.getDatabase(); tradId = traditionId; } /** * Creates a new relation between the specified reading nodes. * * @summary Create relation * @param relationModel - JSON structure of the relation to create * @return The relation(s) created, as well as any other readings in the graph that * had a relation set between them. * @statuscode 201 - on success * @statuscode 304 - if the specified relation type/scope already exists * @statuscode 400 - if the request has an invalid scope * @statuscode 409 - if the relationship cannot legally be created * @statuscode 500 - on failure, with JSON error message */ // TODO make this an idempotent PUT call @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON + "; charset=utf-8") @ReturnType(clazz = GraphModel.class) public Response create(RelationModel relationModel) { // Make sure a scope is set if (relationModel.getScope() == null) relationModel.setScope(SCOPE_LOCAL); String scope = relationModel.getScope(); if (scope.equals(SCOPE_TRADITION) || scope.equals(SCOPE_SECTION) || scope.equals(SCOPE_LOCAL)) { GraphModel relationChanges = new GraphModel(); Response response = this.create_local(relationModel); if (Status.CREATED.getStatusCode() != response.getStatus()) { return response; } GraphModel createResult = (GraphModel)response.getEntity(); relationChanges.addReadings(createResult.getReadings()); relationChanges.addRelations(createResult.getRelations()); // Fish out the ID of the relationship that we explicitly created Optional<RelationModel> orm = createResult.getRelations().stream() .filter(x -> x.getTarget().equals(relationModel.getTarget()) && x.getSource().equals(relationModel.getSource())).findFirst(); assert(orm.isPresent()); String thisRelId = orm.get().getId(); if (!scope.equals(SCOPE_LOCAL)) { Boolean use_normal = returnRelationType(tradId, relationModel.getType()).getUse_regular(); try (Transaction tx = db.beginTx()) { Node readingA = db.getNodeById(Long.parseLong(relationModel.getSource())); Node readingB = db.getNodeById(Long.parseLong(relationModel.getTarget())); Node startingPoint = VariantGraphService.getTraditionNode(tradId, db); if (scope.equals(SCOPE_SECTION)) startingPoint = db.getNodeById((Long) readingA.getProperty("section_id")); Relationship thisRelation = db.getRelationshipById(Long.valueOf(thisRelId)); // Get all the readings that belong to our tradition or section ResourceIterable<Node> tradReadings = VariantGraphService.returnEntireTradition(startingPoint).nodes(); // Pick out the ones that share the readingA text Function<Node, Object> nodefilter = (n) -> use_normal && n.hasProperty("normal_form") ? n.getProperty("normal_form") : (n.hasProperty("text") ? n.getProperty("text"): ""); HashSet<Node> ourA = tradReadings.stream() .filter(x -> nodefilter.apply(x).equals(nodefilter.apply(readingA)) && !x.equals(readingA)) .collect(Collectors.toCollection(HashSet::new)); HashMap<String, HashSet<Long>> ranks = new HashMap<>(); for (Node cur_node : ourA) { long node_id = cur_node.getId(); long node_rank = (Long) cur_node.getProperty("rank"); String node_section = cur_node.getProperty("section_id").toString(); String key = node_section + "/" + node_rank; HashSet<Long> cur_set = ranks.getOrDefault(node_rank, new HashSet<>()); cur_set.add(node_id); ranks.putIfAbsent(key, cur_set); } // Pick out the ones that share the readingB text HashSet<Node> ourB = tradReadings.stream().filter(x -> x.hasProperty("text") && nodefilter.apply(x).equals(nodefilter.apply(readingB)) && !x.equals(readingB)) .collect(Collectors.toCollection(HashSet::new)); RelationModel userel; for (Node cur_node : ourB) { long node_id = cur_node.getId(); long node_rank = (Long) cur_node.getProperty("rank"); String node_section = cur_node.getProperty("section_id").toString(); String key = node_section + "/" + node_rank; HashSet cur_set = ranks.get(key); if (cur_set != null) { for (Object id : cur_set) { userel = new RelationModel(thisRelation); userel.setSource(Long.toString((Long) id)); userel.setTarget(Long.toString(node_id)); response = this.create_local(userel); if (Status.NOT_MODIFIED.getStatusCode() != response.getStatus()) { if (Status.CREATED.getStatusCode() == response.getStatus()) { createResult = (GraphModel) response.getEntity(); relationChanges.addReadings(createResult.getReadings()); relationChanges.addRelations(createResult.getRelations()); } // This is a best-effort operation, so ignore failures } } } } tx.success(); } catch (Exception e) { e.printStackTrace(); return Response.serverError().build(); } } return Response.status(Status.CREATED).entity(relationChanges).build(); } return Response.status(Status.BAD_REQUEST).entity("Undefined Scope").build(); } // Create a relation; return the relation created as well as any reading nodes whose // properties (e.g. rank) have changed. private Response create_local(RelationModel relationModel) { GraphModel readingsAndRelationModel; try (Transaction tx = db.beginTx()) { /* * Currently search by id search, because is much faster by measurement. Because * the id search is O(n) just go through all ids without care. And the * */ Node readingA = db.getNodeById(Long.parseLong(relationModel.getSource())); Node readingB = db.getNodeById(Long.parseLong(relationModel.getTarget())); Node ourSection = db.getNodeById(Long.valueOf(readingA.getProperty("section_id").toString())); Node ourTradition = ourSection.getSingleRelationship(ERelations.PART, Direction.INCOMING).getStartNode(); if (!ourTradition.getProperty("id").equals(tradId)) return Response.status(Status.CONFLICT) .entity(jsonerror("The specified readings do not belong to the specified tradition")) .build(); if (!readingA.getProperty("section_id").equals(readingB.getProperty("section_id"))) return Response.status(Status.CONFLICT) .entity(jsonerror("Cannot create relation across tradition sections")) .build(); if (isMetaReading(readingA) || isMetaReading(readingB)) return Response.status(Status.CONFLICT) .entity(jsonerror("Cannot set relation on a meta reading")) .build(); // Get, or create implicitly, the relation type node for the given type. RelationTypeModel rmodel = returnRelationType(tradId, relationModel.getType()); // Check that the relation type is compatible with the passed relation model if (!relationModel.getScope().equals("local") && !rmodel.getIs_generalizable()) return Response.status(Status.CONFLICT) .entity(jsonerror("Relation type " + rmodel.getName() + " cannot be made outside a local scope")) .build(); // Remove any weak relations that might conflict // LATER better idea: write a traverser that will disregard weak relations Boolean colocation = rmodel.getIs_colocation(); if (colocation) { Iterable<Relationship> relsA = readingA.getRelationships(ERelations.RELATED); for (Relationship r : relsA) { RelationTypeModel rm = returnRelationType(tradId, r.getProperty("type").toString()); if (rm.getIs_weak()) r.delete(); } Iterable<Relationship> relsB = readingB.getRelationships(ERelations.RELATED); for (Relationship r : relsB) { RelationTypeModel rm = returnRelationType(tradId, r.getProperty("type").toString()); if (rm.getIs_weak()) r.delete(); } } Boolean isCyclic = ReadingService.wouldGetCyclic(readingA, readingB); if (isCyclic && colocation) { return Response .status(Status.CONFLICT) .entity(jsonerror("This relation creation is not allowed, it would result in a cyclic graph.")) .build(); } else if (!isCyclic && !colocation) { return Response .status(Status.CONFLICT) .entity(jsonerror("This relation creation is not allowed. The two readings can be co-located.")) .build(); } // TODO add constraints about witness uniqueness or lack thereof // Check if relation already exists Iterable<Relationship> relationships = readingA.getRelationships(ERelations.RELATED); for (Relationship relationship : relationships) { if (relationship.getOtherNode(readingA).equals(readingB)) { RelationModel thisRel = new RelationModel(relationship); RelationTypeModel rtm = returnRelationType(tradId, thisRel.getType()); if (thisRel.getType().equals(relationModel.getType())) { // TODO allow for update of existing relation tx.success(); return Response.status(Status.NOT_MODIFIED).type(MediaType.TEXT_PLAIN_TYPE).build(); } else if (!rtm.getIs_weak()) { tx.success(); String msg = String.format("Relation of type %s already exists between readings %s and %s", relationModel.getType(), relationModel.getSource(), relationModel.getTarget()); return Response.status(Status.CONFLICT).entity(jsonerror(msg)).build(); } } } // We are finally ready to write a relation. readingsAndRelationModel = createSingleRelation(readingA, readingB, relationModel, rmodel); // We can also write any transitive relationships. propagateRelation(readingsAndRelationModel, rmodel); tx.success(); } catch (Exception e) { e.printStackTrace(); return Response.serverError().entity(jsonerror(e.getMessage())).build(); } return Response.status(Response.Status.CREATED).entity(readingsAndRelationModel).build(); } /** * Muck with the database to set a relation * * @param readingA - the source reading * @param readingB - the target reading * @param relModel - the RelationModel to set * @param rtm - the RelationTypeModel describing what sort of relation this is * @return a GraphModel containing the single n4j relationship plus whatever readings were re-ranked */ private GraphModel createSingleRelation(Node readingA, Node readingB, RelationModel relModel, RelationTypeModel rtm) throws Exception { ArrayList<ReadingModel> changedReadings = new ArrayList<>(); ArrayList<RelationModel> createdRelations = new ArrayList<>(); Boolean colocation = rtm.getIs_colocation(); Relationship relationAtoB = readingA.createRelationshipTo(readingB, ERelations.RELATED); relationAtoB.setProperty("type", nullToEmptyString(relModel.getType())); relationAtoB.setProperty("scope", nullToEmptyString(relModel.getScope())); relationAtoB.setProperty("annotation", nullToEmptyString(relModel.getAnnotation())); relationAtoB.setProperty("displayform", nullToEmptyString(relModel.getDisplayform())); relationAtoB.setProperty("a_derivable_from_b", relModel.getA_derivable_from_b()); relationAtoB.setProperty("b_derivable_from_a", relModel.getB_derivable_from_a()); relationAtoB.setProperty("alters_meaning", relModel.getAlters_meaning()); relationAtoB.setProperty("is_significant", relModel.getIs_significant()); relationAtoB.setProperty("non_independent", relModel.getNon_independent()); relationAtoB.setProperty("reading_a", readingA.getProperty("text")); relationAtoB.setProperty("reading_b", readingB.getProperty("text")); if (colocation) relationAtoB.setProperty("colocation", true); // Recalculate the ranks, if necessary Long rankA = (Long) readingA.getProperty("rank"); Long rankB = (Long) readingB.getProperty("rank"); if (!rankA.equals(rankB) && colocation) { // Which one is the lower-ranked reading? Promote it, and recalculate from that point Long higherRank = rankA < rankB ? rankB : rankA; Node lowerRanked = rankA < rankB ? readingA : readingB; lowerRanked.setProperty("rank", higherRank); changedReadings.add(new ReadingModel(lowerRanked)); Set<Node> changedRank = ReadingService.recalculateRank(lowerRanked); for (Node cr : changedRank) if (!cr.equals(lowerRanked)) changedReadings.add(new ReadingModel(cr)); } createdRelations.add(new RelationModel(relationAtoB)); return new GraphModel(changedReadings, createdRelations, new ArrayList<>()); } /** * Checks if a reading is a "Meta"-reading * * @param reading - the reading to check * @return true or false */ private boolean isMetaReading(Node reading) { return reading != null && ((reading.hasProperty("is_lacuna") && reading.getProperty("is_lacuna").equals(true)) || (reading.hasProperty("is_start") && reading.getProperty("is_start").equals(true)) || (reading.hasProperty("is_ph") && reading.getProperty("is_ph").equals(true)) || (reading.hasProperty("is_end") && reading.getProperty("is_end").equals(true)) ); } /** * Propagates reading relations according to type specification. * NOTE - To be used inside a transaction * * @param newRelationResult - the GraphModel that contains a relation just created * @param rtm - the relation type specification */ private void propagateRelation(GraphModel newRelationResult, RelationTypeModel rtm) throws Exception { // First see if this relation type should be propagated. if (!rtm.getIs_transitive()) return; // Now go through all the relations that have been created, and make sure that any // transitivity effects have been accounted for. for (RelationModel rm : newRelationResult.getRelations()) { TransitiveRelationTraverser relTraverser = new TransitiveRelationTraverser(tradId, rtm); Node startNode = db.getNodeById(Long.valueOf(rm.getSource())); ArrayList<Node> relatedNodes = new ArrayList<>(); // Get all the readings that are related by this or a more closely-bound type. db.traversalDescription().depthFirst() .relationships(ERelations.RELATED) .evaluator(relTraverser) .uniqueness(Uniqueness.NODE_GLOBAL) .traverse(startNode).nodes().forEach(relatedNodes::add); // Now go through them and make sure the relations are explicit. ArrayList<Node> iterateNodes = new ArrayList<>(relatedNodes); while (!iterateNodes.isEmpty()) { Node readingA = iterateNodes.remove(0); HashSet<Node> alreadyRelated = new HashSet<>(); readingA.getRelationships(ERelations.RELATED).forEach(x -> alreadyRelated.add(x.getOtherNode(readingA))); // System.out.println(String.format("Propagating type model %s on node %d / %s", // rtm.getName(), readingA.getId(), readingA.getProperty("text"))); for (Node readingB : iterateNodes) { if (!alreadyRelated.contains(readingB)) { // System.out.println(String.format("...making relation %s to node %d / %s", rm.getType(), readingB.getId(), readingB.getProperty("text"))); GraphModel interim = createSingleRelation(readingA, readingB, rm, rtm); newRelationResult.addReadings(interim.getReadings()); newRelationResult.addRelations(interim.getRelations()); } } } // Now go back through them and make sure that relations to more loosely-bound // transitive nodes are marked. for (Node sibling : relatedNodes) { HashMap<Node, Relationship> connections = new HashMap<>(); // Get the nodes we are directly related to, and the relations involved, if // they meet the criteria for (Relationship r : sibling.getRelationships(ERelations.RELATED)) { RelationTypeModel othertm = returnRelationType(tradId, r.getProperty("type").toString()); if (othertm.getBindlevel() > rtm.getBindlevel() && othertm.getIs_transitive()) connections.put(r.getOtherNode(sibling), r); } HashSet<Node> cousins = new HashSet<>(relatedNodes); for (Node n : connections.keySet()) { cousins.remove(n); RelationModel newmodel = new RelationModel(connections.get(n)); RelationTypeModel newtm = returnRelationType(tradId, newmodel.getType()); for (Node c : cousins) { ArrayList<Relationship> priorLinks = DatabaseService.getRelationshipTo(n, c, ERelations.RELATED); if (priorLinks.size() == 0) { // Create a relation based on the looser link GraphModel interim = createSingleRelation(n, c, newmodel, newtm); newRelationResult.addReadings(interim.getReadings()); newRelationResult.addRelations(interim.getRelations()); } } } } } } /** * Remove the relation specified. There should be only one. * * @summary Delete a relation specifed by JSON data. * @param relationModel - the JSON specification of the relationship(s) to delete * @return A list of all relationships that were removed. * @statuscode 200 - on success * @statuscode 400 - if an invalid scope was specified * @statuscode 404 - if no matching relationship was found * @statuscode 500 - on failure, with JSON error message */ @POST @Path("/remove") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON + "; charset=utf-8") @ReturnType("java.util.List<net.stemmaweb.model.RelationModel>") public Response deleteByData(RelationModel relationModel) { ArrayList<RelationModel> deleted = new ArrayList<>(); try (Transaction tx = db.beginTx()) { Node readingA = db.getNodeById(Long.parseLong(relationModel.getSource())); Node readingB = db.getNodeById(Long.parseLong(relationModel.getTarget())); switch (relationModel.getScope()) { case SCOPE_LOCAL: ArrayList<Relationship> findRel = DatabaseService.getRelationshipTo(readingA, readingB, ERelations.RELATED); if (findRel.isEmpty()) { return Response.status(Status.NOT_FOUND).entity(jsonerror("Relation not found")).build(); } else { Relationship theRel = findRel.get(0); RelationModel relInfo = new RelationModel(theRel); theRel.delete(); deleted.add(relInfo); } break; case SCOPE_SECTION: case SCOPE_TRADITION: Traverser toCheck = relationModel.getScope().equals(SCOPE_SECTION) ? VariantGraphService.returnTraditionSection(readingA.getProperty("section_id").toString(), db) : VariantGraphService.returnEntireTradition(tradId, db); for (Relationship rel : toCheck.relationships()) { if (rel.getType().name().equals(ERelations.RELATED.name())) { Node ra = db.getNodeById(Long.parseLong(relationModel.getSource())); Node rb = db.getNodeById(Long.parseLong(relationModel.getTarget())); if ((rel.getStartNode().getProperty("text").equals(ra.getProperty("text")) || rel.getEndNode().getProperty("text").equals(ra.getProperty("text"))) && (rel.getStartNode().getProperty("text").equals(rb.getProperty("text")) || rel.getEndNode().getProperty("text").equals(rb.getProperty("text")))) { RelationModel relInfo = new RelationModel(rel); rel.delete(); deleted.add(relInfo); } } } break; default: return Response.status(Status.BAD_REQUEST).entity(jsonerror("Undefined Scope")).build(); } tx.success(); } return Response.status(Response.Status.OK).entity(deleted).build(); } /** * Removes a relation by internal ID. * * @summary Delete relation by ID * @param relationId - the ID of the relation to delete * @return The deleted relation * @statuscode 200 - on success * @statuscode 403 - if the given ID does not belong to a relation * @statuscode 500 - on failure, with JSON error message */ @DELETE @Path("{relationId}") @Produces(MediaType.APPLICATION_JSON + "; charset=utf-8") @ReturnType(clazz = RelationModel.class) public Response deleteById(@PathParam("relationId") String relationId) { RelationModel relationModel; try (Transaction tx = db.beginTx()) { Relationship relationship = db.getRelationshipById(Long.parseLong(relationId)); if(relationship.getType().name().equals("RELATED")) { relationModel = new RelationModel(relationship); relationship.delete(); } else { return Response.status(Status.FORBIDDEN).entity(jsonerror("This is not a relation link")).build(); } tx.success(); } catch (Exception e) { return Response.serverError().entity(jsonerror(e.getMessage())).build(); } return Response.ok(relationModel).build(); } private String nullToEmptyString(String str){ return str == null ? "" : str; } }
53.046
164
0.594164
6b4ba97fa23e57ddb5a381b19f55298a956d808c
5,403
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-b10 // 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.08.05 at 10:17:37 PM BST // package org.openprovenance.prov.dot; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.openprovenance.prov.xml.builder.Equals; import org.openprovenance.prov.xml.builder.HashCode; import org.openprovenance.prov.xml.builder.ToString; import org.openprovenance.prov.xml.builder.JAXBEqualsBuilder; import org.openprovenance.prov.xml.builder.JAXBHashCodeBuilder; import org.openprovenance.prov.xml.builder.JAXBToStringBuilder; /** * <p>Java class for RelationStyleMap complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RelationStyleMap"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="relation" type="{http://openprovenance.org/model/opmPrinterConfig}RelationStyleMapEntry" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="default" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RelationStyleMap", namespace = "http://openprovenance.org/model/opmPrinterConfig", propOrder = { "relation" }) public class RelationStyleMap implements Equals, HashCode, ToString { @XmlElement(namespace = "http://openprovenance.org/model/opmPrinterConfig") protected List<RelationStyleMapEntry> relation; @XmlAttribute(name = "default") protected String _default; /** * Gets the value of the relation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the relation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRelation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link RelationStyleMapEntry } * * */ public List<RelationStyleMapEntry> getRelation() { if (relation == null) { relation = new ArrayList<RelationStyleMapEntry>(); } return this.relation; } /** * Gets the value of the default property. * * @return * possible object is * {@link String } * */ public String getDefault() { return _default; } /** * Sets the value of the default property. * * @param value * allowed object is * {@link String } * */ public void setDefault(String value) { this._default = value; } public void equals(Object object, EqualsBuilder equalsBuilder) { if (!(object instanceof RelationStyleMap)) { equalsBuilder.appendSuper(false); return ; } if (this == object) { return ; } final RelationStyleMap that = ((RelationStyleMap) object); equalsBuilder.append(this.getRelation(), that.getRelation()); equalsBuilder.append(this.getDefault(), that.getDefault()); } public boolean equals(Object object) { if (!(object instanceof RelationStyleMap)) { return false; } if (this == object) { return true; } final EqualsBuilder equalsBuilder = new JAXBEqualsBuilder(); equals(object, equalsBuilder); return equalsBuilder.isEquals(); } public void hashCode(HashCodeBuilder hashCodeBuilder) { hashCodeBuilder.append(this.getRelation()); hashCodeBuilder.append(this.getDefault()); } public int hashCode() { final HashCodeBuilder hashCodeBuilder = new JAXBHashCodeBuilder(); hashCode(hashCodeBuilder); return hashCodeBuilder.toHashCode(); } public void toString(ToStringBuilder toStringBuilder) { { List<RelationStyleMapEntry> theRelation; theRelation = this.getRelation(); toStringBuilder.append("relation", theRelation); } { String theDefault; theDefault = this.getDefault(); toStringBuilder.append("_default", theDefault); } } public String toString() { final ToStringBuilder toStringBuilder = new JAXBToStringBuilder(this); toString(toStringBuilder); return toStringBuilder.toString(); } }
31.412791
155
0.654451
3442ebf194ba56fba25b588a0265546365745778
6,469
// Copyright © 2010-2018, Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package org.specsy.junit; import fi.jumi.api.RunVia; import org.junit.platform.engine.*; import org.junit.platform.engine.UniqueId.Segment; import org.junit.platform.engine.discovery.ClassSelector; import org.junit.platform.engine.discovery.ClasspathRootSelector; import org.junit.platform.engine.discovery.PackageSelector; import org.junit.platform.engine.discovery.UniqueIdSelector; import org.junit.platform.engine.support.descriptor.EngineDescriptor; import org.specsy.Specsy; import org.specsy.bootstrap.ClassSpec; import org.specsy.core.Path; import org.specsy.core.SpecRun; import java.lang.reflect.Modifier; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.function.Predicate; import static org.junit.platform.commons.util.ReflectionUtils.findAllClassesInClasspathRoot; import static org.junit.platform.commons.util.ReflectionUtils.findAllClassesInPackage; import static org.junit.platform.engine.support.filter.ClasspathScanningSupport.buildClassNamePredicate; public class SpecsyTestEngine implements TestEngine { private static final String ENGINE_ID = "specsy"; @Override public String getId() { return ENGINE_ID; } @Override public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest, UniqueId myUniqueId) { EngineDescriptor engineDescriptor = new EngineDescriptor(myUniqueId, "Specsy"); Predicate<String> classNamePredicate = buildClassNamePredicate(discoveryRequest); for (ClassSelector selector : discoveryRequest.getSelectorsByType(ClassSelector.class)) { Class<?> testClass = selector.getJavaClass(); if (isSpecsyClass(testClass)) { engineDescriptor.addChild(new ClassTestDescriptor(engineDescriptor, testClass)); } } for (ClasspathRootSelector selector : discoveryRequest.getSelectorsByType(ClasspathRootSelector.class)) { for (Class<?> testClass : findAllClassesInClasspathRoot(selector.getClasspathRoot(), SpecsyTestEngine::isSpecsyClass, classNamePredicate)) { engineDescriptor.addChild(new ClassTestDescriptor(engineDescriptor, testClass)); } } for (PackageSelector selector : discoveryRequest.getSelectorsByType(PackageSelector.class)) { String packageName = selector.getPackageName(); for (Class<?> testClass : findAllClassesInPackage(packageName, SpecsyTestEngine::isSpecsyClass, classNamePredicate)) { engineDescriptor.addChild(new ClassTestDescriptor(engineDescriptor, testClass)); } } for (UniqueIdSelector selector : discoveryRequest.getSelectorsByType(UniqueIdSelector.class)) { UniqueId uniqueId = selector.getUniqueId(); System.out.println("id = " + uniqueId); if (uniqueId.getEngineId().orElse("").equals(ENGINE_ID)) { List<Segment> segments = uniqueId.getSegments(); Class<?> testClass = loadClass(segments.stream() .filter(s -> s.getType().equals(ClassTestDescriptor.SEGMENT_TYPE)) .map(Segment::getValue) .findFirst() .orElseThrow(() -> new IllegalArgumentException("class segment missing in " + uniqueId))); Path pathToExecute = Path.of(segments.stream() .filter(s -> s.getType().equals(NestedTestDescriptor.SEGMENT_TYPE)) .map(Segment::getValue) .mapToInt(Integer::parseInt) .toArray()); engineDescriptor.addChild(new ClassTestDescriptor(engineDescriptor, testClass, pathToExecute)); } } return engineDescriptor; } private static boolean isSpecsyClass(Class<?> testClass) { if (Modifier.isAbstract(testClass.getModifiers())) { return false; } RunVia runVia = testClass.getAnnotation(RunVia.class); return runVia != null && runVia.value() == Specsy.class; } private static Class<?> loadClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @Override public void execute(ExecutionRequest request) { execute(request.getRootTestDescriptor(), request.getEngineExecutionListener()); } private void execute(TestDescriptor descriptor, EngineExecutionListener listener) { if (descriptor instanceof EngineDescriptor) { execute((EngineDescriptor) descriptor, listener); } else if (descriptor instanceof ClassTestDescriptor) { execute((ClassTestDescriptor) descriptor, listener); } else { throw new IllegalArgumentException("Unrecognized descriptor: " + descriptor); } } private void execute(EngineDescriptor descriptor, EngineExecutionListener listener) { listener.executionStarted(descriptor); for (TestDescriptor child : descriptor.getChildren()) { execute(child, listener); } listener.executionFinished(descriptor, TestExecutionResult.successful()); } private void execute(ClassTestDescriptor descriptor, EngineExecutionListener listener) { ClassSpec spec = new ClassSpec(descriptor.getTestClass()); Path pathToExecute = descriptor.getPathToExecute(); SuiteNotifierAdapter notifier = new SuiteNotifierAdapter(listener, descriptor); AsyncThreadlessExecutor executor = new AsyncThreadlessExecutor(); executor.execute(new SpecRun(spec, pathToExecute, notifier, executor)); executor.executeUntilDone(); } private static class AsyncThreadlessExecutor implements Executor { private final Queue<Runnable> commands = new ConcurrentLinkedQueue<>(); @Override public void execute(Runnable command) { commands.add(command); } public void executeUntilDone() { Runnable command; while ((command = commands.poll()) != null) { command.run(); } } } }
42.84106
152
0.684032
015fada1ae19930ecfaa4eb7290310eda6b322cf
1,216
package com.reallifedeveloper.common.infrastructure.persistence; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.reallifedeveloper.common.application.eventstore.StoredEvent; import com.reallifedeveloper.common.application.eventstore.StoredEventRepository; /** * A Spring Data JPA "implementation" of the {@link StoredEventRepository} interface. * * @author RealLifeDeveloper */ public interface JpaStoredEventRepository extends StoredEventRepository, JpaRepository<StoredEvent, Long> { @Override @Query("select se from StoredEvent se where se.id > :firstStoredEventId") List<StoredEvent> allEventsSince(@Param("firstStoredEventId") long firstStoredEventId); @Override @Query("select se from StoredEvent se where se.id between :firstStoredEventId and :lastStoredEventId") List<StoredEvent> allEventsBetween(@Param("firstStoredEventId") long firstStoredEventId, @Param("lastStoredEventId") long lastStoredEventId); @Override @Query("select max(se.id) from StoredEvent se") Long lastStoredEventId(); }
38
107
0.790296
554b23406a68c3c0bbfdbb7bc7d0caf87b5e8b95
715
package net.maera.osgi.container; import net.maera.io.Resource; import net.maera.lifecycle.Startable; import net.maera.lifecycle.Stoppable; import org.osgi.framework.Bundle; /** * Interface representing the operations possible when interacting with an OSGi framework implementation * (e.g. Apache Felix, Eclipse Equinox, et. al.) */ public interface Container extends Startable, Stoppable { @Override void start() throws ContainerException; @Override void stop() throws InterruptedException, ContainerException; void stop(long waitMillis) throws InterruptedException, ContainerException; Bundle installBundle(Resource resource) throws ContainerException; }
28.6
105
0.755245
4924f229424eb1cc34e67ff6de1b683f8de556bc
12,574
package de.naoth.rc.dataformats; import com.google.protobuf.InvalidProtocolBufferException; import de.naoth.rc.drawings.Arrow; import de.naoth.rc.drawings.Circle; import de.naoth.rc.drawings.DrawingCollection; import de.naoth.rc.drawings.FillOval; import de.naoth.rc.drawings.Line; import de.naoth.rc.drawings.Pen; import de.naoth.rc.drawings.Robot; import de.naoth.rc.drawings.Text; import de.naoth.rc.math.Pose2D; import de.naoth.rc.math.Vector2D; import de.naoth.rc.core.messages.TeamMessageOuterClass; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; /** * * @author Heinrich Mellmann */ public class SPLMessage { public static final int SPL_STANDARD_MESSAGE_MAX_NUM_OF_PLAYERS = 5; /** List of supported versions */ public static final List<Integer> SPL_MESSAGE_VERSIONS = Arrays.asList( SPLMessage2017.SPL_STANDARD_MESSAGE_STRUCT_VERSION, SPLMessage2018.SPL_STANDARD_MESSAGE_STRUCT_VERSION ); //public byte header[4]; // 4 //public byte version; // 1 public byte playerNum; // 1 public byte teamNum; // 1 public byte fallen; // 1 public float pose_x; // 4 public float pose_y; // 4 public float pose_a; // 4 @Deprecated public float walkingTo_x; // 4 @Deprecated public float walkingTo_y; // 4 @Deprecated public float shootingTo_x; // 4 @Deprecated public float shootingTo_y; // 4 public float ballAge; // 4 public float ball_x; // 4 public float ball_y; // 4 @Deprecated public float ballVel_x; // 4 @Deprecated public float ballVel_y; // 4 public byte[] suggestion = new byte[SPL_STANDARD_MESSAGE_MAX_NUM_OF_PLAYERS]; // 5 // describes what the robot intends to do: // 0 - nothing particular (default) // 1 - wants to be keeper // 2 - wants to play defense // 3 - wants to play the ball // 4 - robot is lost // (the second byte is a padding byte) public byte intention; // 1 public short averageWalkSpeed; // 2 public short maxKickDistance; // 2 // [MANDATORY] // describes the current confidence of a robot about its self-location, // the unit is percent [0,..100] // the value should be updated in the course of the game public byte currentPositionConfidence; // 1 // [MANDATORY] // describes the current confidence of a robot about playing in the right direction, // the unit is percent [0,..100] // the value should be updated in the course of the game public byte currentSideConfidence; // 1 public short numOfDataBytes; // 2 public byte[] data; public transient TeamMessageOuterClass.BUUserTeamMessage user = null; public transient SPLMixedTeamHeader mixedHeader = null; public SPLMessage() { user = TeamMessageOuterClass.BUUserTeamMessage.getDefaultInstance(); } public static SPLMessage parseFrom(TeamMessageOuterClass.TeamMessage.Data msg) { SPLMessage spl = new SPLMessage(); spl.averageWalkSpeed = -1; spl.ballAge = msg.hasBallAge() ? msg.getBallAge() : -1; spl.ballVel_x = msg.hasBallVelocity() ? (float) msg.getBallVelocity().getX() : 0.0f; spl.ballVel_y = msg.hasBallVelocity() ? (float) msg.getBallVelocity().getY() : 0.0f; spl.ball_x = (float) msg.getBallPosition().getX(); spl.ball_y = (float) msg.getBallPosition().getY(); spl.currentPositionConfidence = -1; spl.currentSideConfidence = -1; spl.fallen = msg.getFallen() ? (byte) 1 : (byte) 0; spl.intention = (byte) (msg.getUser().getWasStriker() ? 3 : 0); spl.maxKickDistance = -1; spl.playerNum = (byte) msg.getPlayerNum(); spl.pose_x = (float) msg.getPose().getTranslation().getX(); spl.pose_y = (float) msg.getPose().getTranslation().getY(); spl.pose_a = (float) msg.getPose().getRotation(); // TODO: don't use default value spl.shootingTo_x = (float) msg.getPose().getTranslation().getX(); spl.shootingTo_y = (float) msg.getPose().getTranslation().getY(); if (msg.hasTeamNumber()) { spl.teamNum = (byte) msg.getTeamNumber(); } else if (msg.getUser().hasTeamNumber()) { spl.teamNum = (byte) msg.getTeamNumber(); } spl.user = msg.getUser(); spl.walkingTo_x = -1; spl.walkingTo_y = -1; return spl; } public static SPLMessage parseFrom(ByteBuffer buffer) throws Exception { // check message header if (buffer.get() != 'S' || buffer.get() != 'P' || buffer.get() != 'L' || buffer.get() != ' ') { throw new NotSplMessageException(); } int version = buffer.get(); if(version == SPL_MESSAGE_VERSIONS.get(0)) { // parse with v2017 return new SPLMessage2017(buffer); } else if(version == SPL_MESSAGE_VERSIONS.get(1)) { // parse with v2018 return new SPLMessage2018(buffer); } else { throw new WrongSplVersionException(version); } } public void draw(DrawingCollection drawings, Color robotColor, boolean mirror) { // put the penalized players on "the bench" if(user != null && ((user.hasIsPenalized() && user.getIsPenalized()) || (user.hasRobotState() && user.getRobotState() == TeamMessageOuterClass.RobotState.penalized))) { Pose2D robotPose = mirror ? new Pose2D(4600 - (playerNum * 500), -3300, Math.PI/2) : new Pose2D(-4600 + (playerNum * 500), 3300, -Math.PI/2); // robot drawings.add(new Pen(1.0f, robotColor)); drawings.add(new Robot(robotPose.translation.x, robotPose.translation.y, robotPose.rotation)); // number drawings.add(new Pen(1, Color.RED)); Font numberFont = new Font ("Courier New", Font.PLAIN | Font.CENTER_BASELINE, 250); drawings.add(new Text((int) robotPose.translation.x, (int) robotPose.translation.y + 250, 0, "" + playerNum, numberFont)); // don't draw anything else return; } Vector2D ballPos = new Vector2D(ball_x, ball_y); Pose2D robotPose = mirror ? new Pose2D(-pose_x, -pose_y, pose_a + Math.PI) : new Pose2D(pose_x, pose_y, pose_a); Vector2D globalBall = robotPose.multiply(ballPos); // robot drawings.add(new Pen(1.0f, robotColor)); drawings.add(new Robot(robotPose.translation.x, robotPose.translation.y, robotPose.rotation)); // number, use different colors for the different states switch (user.getRobotState()) { case initial: drawings.add(new Pen(1, Color.WHITE)); break; case ready: drawings.add(new Pen(1, Color.BLUE)); break; case set: drawings.add(new Pen(1, Color.YELLOW)); break; case playing: drawings.add(new Pen(1, Color.BLACK)); break; case finished: drawings.add(new Pen(1, Color.LIGHT_GRAY)); break; case penalized: drawings.add(new Pen(1, Color.RED)); break; default: drawings.add(new Pen(1, Color.PINK)); break; } Font numberFont = new Font ("Courier New", Font.PLAIN | Font.CENTER_BASELINE, 250); double fontRotation = 0;//robotPose.rotation+Math.PI/2; // rotate in the direction of the robots drawings.add(new Text((int) robotPose.translation.x, (int) robotPose.translation.y + 250, fontRotation, "" + playerNum, numberFont)); // striker if (intention == 3) { drawings.add(new Pen(30, Color.red)); drawings.add(new Circle((int) robotPose.translation.x, (int) robotPose.translation.y, 150)); } // ball if (ballAge >= 0 && ballAge < 3) { drawings.add(new Pen(1, Color.orange)); drawings.add(new FillOval((int) globalBall.x, (int) globalBall.y, 65, 65)); // add a surrounding black circle so the ball is easier to see drawings.add(new Pen(1, robotColor)); drawings.add(new Circle((int) globalBall.x, (int) globalBall.y, 65)); { // show the time since the ball was last seen drawings.add(new Pen(1, robotColor)); double t = ballAge; Text text = new Text( (int) globalBall.x + 50, (int) globalBall.y + 50, Math.round(t) + "s"); drawings.add(text); } // draw a line between robot and ball { drawings.add(new Pen(5, Color.darkGray)); Line ballLine = new Line( (int) robotPose.translation.x, (int) robotPose.translation.y, (int) globalBall.x, (int) globalBall.y); drawings.add(ballLine); } // if it is our striker ... if(user != null && intention == 3 && shootingTo_x != 0 && shootingTo_y != 0) { // ... draw the excpected ball position drawings.add(new Pen(5.0f, Color.gray)); drawings.add(new Circle((int) shootingTo_x, (int) shootingTo_y, 65)); drawings.add(new Pen(Color.gray, new BasicStroke(10, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{100, 50}, 0))); drawings.add(new Arrow((int) globalBall.x, (int) globalBall.y, (int) shootingTo_x, (int) shootingTo_y)); } } // if it is our player ... if(user != null) { double[] tb = {user.getTeamBall().getX(), user.getTeamBall().getY()}; if(user.hasTeamBall() && !Double.isInfinite(tb[0]) && !Double.isInfinite(tb[1])) { // ... draw the teamball position drawings.add(new Pen(5.0f, robotColor)); drawings.add(new Circle((int) tb[0], (int) tb[1], 65)); drawings.add(new Pen(robotColor, new BasicStroke(10, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{25, 50, 75, 100}, 0))); drawings.add(new Arrow((int) robotPose.translation.x, (int) robotPose.translation.y, (int) tb[0], (int) tb[1])); } if(user.getWantsToBeStriker() && !user.getWasStriker()) { drawings.add(new Pen(32, Color.YELLOW)); drawings.add(new Circle((int) robotPose.translation.x, (int) robotPose.translation.y, 150)); } } } public boolean parseCustomFromData() { // TODO: check if this needs to be changed - 'cause of dobermanheader!?! if(data != null) { try { user = TeamMessageOuterClass.BUUserTeamMessage.parseFrom(data); return true; } catch (InvalidProtocolBufferException ex) { /* ignore! instead "false" is returned. */ } } return false; } protected boolean extractCustomData(int size) { if(this.data.length > size) { byte[] dataWithOffset = Arrays.copyOfRange(this.data, size, this.data.length); try { this.user = TeamMessageOuterClass.BUUserTeamMessage.parseFrom(dataWithOffset); // additionally check if the magic string matches if(!"naoth".equals(this.user.getKey())) { this.user = null; } return this.user != null; } catch (InvalidProtocolBufferException ex) { // it's not our message } } return false; } public static int size() { return Integer.max(SPLMessage2017.SPL_STANDARD_MESSAGE_SIZE, SPLMessage2018.SPL_STANDARD_MESSAGE_SIZE); } /** * Exception for invalid spl message header. */ public static class NotSplMessageException extends Exception { public NotSplMessageException() { super("Not an SPL Message."); } } /** * Exception for invalid/unknown spl message version. */ public static class WrongSplVersionException extends Exception { public WrongSplVersionException(int version) { super("Wrong version: reveived " + version + ", but expected one of " + SPL_MESSAGE_VERSIONS); } } }
38.452599
159
0.594799
16c006276a77e4361e9015d16845d7f6b46ecfc8
7,470
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.protocol.internal.binary; import com.datastax.oss.protocol.internal.PrimitiveSizes; import com.datastax.oss.protocol.internal.util.Bytes; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.LinkedList; import java.util.Objects; /** A DSL that simulates a mock binary string for reading and writing, to use in our unit tests. */ // ErrorProne issues a warning about LinkedList. The suggested alternative is ArrayDeque, but it // does not override equals. Keeping LinkedList here since performance is not crucial in tests. @SuppressWarnings("JdkObsolete") public class MockBinaryString { private LinkedList<Element> elements = new LinkedList<>(); private LinkedList<Element> mark; public MockBinaryString byte_(int value) { append(Element.Type.BYTE, (byte) value); return this; } public MockBinaryString int_(int value) { append(Element.Type.INT, value); return this; } public MockBinaryString inetAddr(InetAddress host) { append(Element.Type.INETADDR, host); return this; } public MockBinaryString long_(long value) { append(Element.Type.LONG, value); return this; } public MockBinaryString unsignedShort(int value) { append(Element.Type.UNSIGNED_SHORT, value); return this; } public MockBinaryString string(String value) { append(Element.Type.STRING, value); return this; } public MockBinaryString longString(String value) { append(Element.Type.LONG_STRING, value); return this; } public MockBinaryString bytes(String value) { append(Element.Type.BYTES, value); return this; } public MockBinaryString shortBytes(String value) { append(Element.Type.SHORT_BYTES, value); return this; } public MockBinaryString append(MockBinaryString other) { for (Element element : other.elements) { this.elements.add(element); } return this; } public void markReaderIndex() { mark = new LinkedList<>(); mark.addAll(elements); } public void resetReaderIndex() { if (mark == null) { throw new IllegalStateException("No mark, call markReaderIndex() first"); } elements = mark; mark = null; } public MockBinaryString copy() { return new MockBinaryString().append(this); } public int size() { int size = 0; for (Element element : elements) { size += element.size(); } return size; } MockBinaryString slice(int targetSize) { // We can't write a perfect implementation for this, since our internal representation is based // on primitive types (INT, LONG_STRING...), but not individual bytes. // The code below works as long as the split happens on the boundary between two elements. We // also support splitting a BYTES element, but that operation alters the contents // (re-concatenating the two strings is not strictly equal to the original). // This works for the tests that exercise this method so far, because they only check the // length, not the actual contents. MockBinaryString slice = new MockBinaryString(); while (slice.size() < targetSize) { Element element = pop(); if (slice.size() + element.size() <= targetSize) { slice.append(element.type, element.value); } else if (element.type == Element.Type.BYTES) { String hexString = (String) element.value; // BYTES starts with an int length int bytesToCopy = targetSize - slice.size() - 4; // Hex strings starts with '0x' and each byte is two characters int split = 2 + bytesToCopy * 2; slice.append(Element.Type.BYTES, hexString.substring(0, split)); // Put the rest back in the source string. But we can't put it as a BYTES because size() // would over-estimate it by 4 (for the INT size). So write byte-by-byte instead. byte[] remainingBytes = Bytes.getArray(Bytes.fromHexString("0x" + hexString.substring(split))); for (byte b : remainingBytes) { this.prepend(Element.Type.BYTE, b); } } else { throw new UnsupportedOperationException("Can't split element other than BYTES"); } } return slice; } Element pop() { return elements.pop(); } Element pollFirst() { return elements.pollFirst(); } Element pollLast() { return elements.pollLast(); } private void append(Element.Type type, Object value) { this.elements.add(new Element(type, value)); } private void prepend(Element.Type type, Object value) { this.elements.addFirst(new Element(type, value)); } @Override public boolean equals(Object other) { if (other instanceof MockBinaryString) { MockBinaryString that = (MockBinaryString) other; return this.elements.equals(that.elements); } return false; } @Override public int hashCode() { return this.elements.hashCode(); } @Override public String toString() { return elements.toString(); } static class Element { enum Type { BYTE, INT, INET, INETADDR, LONG, UNSIGNED_SHORT, STRING, LONG_STRING, BYTES, SHORT_BYTES } final Type type; final Object value; private Element(Type type, Object value) { this.type = type; this.value = value; } int size() { String hexString; switch (type) { case BYTE: return 1; case INT: return PrimitiveSizes.INT; case INET: return PrimitiveSizes.sizeOfInet(((InetSocketAddress) value)); case INETADDR: return PrimitiveSizes.sizeOfInetAddr(((InetAddress) value)); case LONG: return PrimitiveSizes.LONG; case UNSIGNED_SHORT: return PrimitiveSizes.SHORT; case STRING: return PrimitiveSizes.sizeOfString((String) value); case LONG_STRING: return PrimitiveSizes.sizeOfLongString((String) value); case BYTES: hexString = (String) value; // 0xabcdef return PrimitiveSizes.INT + (hexString.length() - 2) / 2; case SHORT_BYTES: hexString = (String) value; return PrimitiveSizes.SHORT + (hexString.length() - 2) / 2; default: throw new IllegalStateException("Unsupported element type " + type); } } @Override public boolean equals(Object other) { if (other instanceof Element) { Element that = (Element) other; return this.type == that.type && (this.value == null ? that.value == null : this.value.equals(that.value)); } return false; } @Override public int hashCode() { return Objects.hash(type, value); } @Override public String toString() { return String.format("[%s:%s]", type, value); } } }
28.730769
99
0.659304
6dded0a1f2e8651983b8b6e731fccc1c15f4303b
574
package qrcode; public class Main { public static final String INPUT = "I love java. Java is a great language!"; /* * Parameters */ public static final int VERSION = 4; public static final int MASK = 0; public static final int SCALING = 20; public static void main(String[] args) { /* * Encoding */ boolean[] encodedData = DataEncoding.byteModeEncoding(INPUT, VERSION); /* * image */ int[][] qrCode = MatrixConstruction.renderQRCodeMatrix(VERSION, encodedData, MASK); /* * Visualization */ Helpers.show(qrCode, SCALING); } }
18.516129
85
0.665505
37b3d965e963f45a4d1e4b4fcd88974abb36bc66
150
@NothingIsNullByDefault package io.github.phantamanta44.pcrossbow.client; import io.github.phantamanta44.libnine.util.nullity.NothingIsNullByDefault;
37.5
75
0.88
e5a9495c1e3883b5f04c98e0d56ed6468a2dff34
5,027
package com.googlecode.common.util; import java.util.Arrays; import java.util.BitSet; /** * Contains bit set helper methods. */ public final class Bits { private Bits() { } public static long add(long bits, long mask) { return (bits | mask); } public static long del(long bits, long mask) { return (bits & ~mask); } public static boolean all(long bits, long mask) { return (bits & mask) == mask; } public static boolean any(long bits, long mask) { return (bits & mask) != 0; } public static boolean isAllSet(BitSet bs) { final int cardinality = bs.cardinality(); return (cardinality != 0 && cardinality == bs.size()); } public static BitSet fromIntArray(int[] bits) { BitSet set = new BitSet(bits.length << 5); for (int i = bits.length - 1; i >= 0; i--) { final int word = bits[i]; if (word != 0) { for (int bit = 31; bit >= 0; bit--) { if ((word & (1 << bit)) != 0) { set.set((i << 5) + bit); } } } } return set; } public static int[] toIntArray(BitSet set) { final int cardinality = set.cardinality(); if (cardinality == 0) { return CollectionsUtil.EMPTY_INT_ARR; } int[] bits = new int[((set.length() - 1) >>> 5) + 1]; if (cardinality == set.size()) { // special case: all bits are set Arrays.fill(bits, -1); return bits; } for (int i = set.nextSetBit(0); i >= 0; i = set.nextSetBit(i + 1)) { bits[i >>> 5] |= (1 << i); } return bits; } public static BitSet fromLongArray(long[] bits) { BitSet set = new BitSet(bits.length << 6); for (int i = bits.length - 1; i >= 0; i--) { final long word = bits[i]; if (word != 0L) { for (int bit = 63; bit >= 0; bit--) { if ((word & (1L << bit)) != 0L) { set.set((i << 6) + bit); } } } } return set; } public static long[] toLongArray(BitSet set) { return toLongArray(set, 0); } public static long[] toLongArray(BitSet set, int minArrLength) { final int count = Math.max(minArrLength, ((set.length() - 1) >> 6) + 1); if (count == 0) { return CollectionsUtil.EMPTY_LONG_ARR; } long[] bits = new long[count]; if (set.cardinality() == set.size()) { // special case: all bits are set Arrays.fill(bits, -1L); return bits; } for (int i = set.nextSetBit(0); i >= 0; i = set.nextSetBit(i + 1)) { bits[i >>> 6] |= (1L << i); } return bits; } static boolean testAllSet(BitSet set, boolean isAll) { boolean success = isAllSet(set); success = (success == isAll); System.out.println(set + " isAllSet(" + isAll + ") " + success); return success; } static boolean testFromToIntArray(BitSet set) { int[] bits = toIntArray(set); boolean success = set.equals(fromIntArray(bits)); System.out.println(set + " FromToIntArray(" + bits.length + ") " + success); return success; } static boolean testFromToLongArray(BitSet set) { long[] bits = toLongArray(set); boolean success = set.equals(fromLongArray(bits)); System.out.println(set + " FromToLongArray(" + bits.length + ") " + success); return success; } public static void main(String[] args) { BitSet allSet = new BitSet(); for (int i = 0; i < 64; i++) { allSet.set(i); } BitSet set = new BitSet(65); set.set(0); set.set(1); set.set(31); set.set(32); set.set(64); set.set(65); boolean success = true; success = success && testAllSet(allSet, true); success = success && testAllSet(set, false); success = success && testFromToIntArray(allSet); success = success && testFromToIntArray(set); success = success && testFromToLongArray(allSet); success = success && testFromToLongArray(set); BitSet emptySet = new BitSet(); long[] arr = toLongArray(emptySet, 1); success = success && (arr.length >= 1); if (!success) { System.err.println("Some of tests are FAILED"); } } }
29.057803
77
0.464293
16ac8ae38c62c6021b63f2a50ad4af900812d49f
2,810
package user; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import board.Board; public class UserDAO { private Connection conn; private PreparedStatement pstmt; private ResultSet rs; public UserDAO() { try { String dbURL = "jdbc:mysql://localhost:3306/Sprout?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; String dbIO = "Sprout"; String dbPassword = "qw660523"; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(dbURL, dbIO, dbPassword); } catch (Exception e) { e.printStackTrace(); } } public int login(String userID, String userPasswaord) { String SQL = "SELECT userPasswaord FROM USER WHERE userID = ?"; try { pstmt = conn.prepareStatement(SQL); pstmt.setString(1, userID); rs = pstmt.executeQuery(); if (rs.next()) { if (rs.getString(1).equals(userPasswaord)) { return 1; // login success } else { return 0; // wrong password } } return -1; // userID is not exist } catch (Exception e) { e.printStackTrace(); } return -2; // database error } public int join(User user) { String SQL = "INSERT INTO USER VALUES (?, ?, ?, ?, ?)"; try { pstmt = conn.prepareStatement(SQL); pstmt.setString(1, user.getUserID()); pstmt.setString(2, user.getUserPassword()); pstmt.setString(3, user.getUserName()); pstmt.setString(4, user.getUserGender()); pstmt.setString(5, user.getUserEmail()); return pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return -1; // database error } //추가한 부분 password를 passwaord라고 디비에 잘못 저장해서 그거 바꿔야해욥 ㅠ public User getUser(String userID) { String SQL = "SELECT * FROM User WHERE userID = ?"; try { PreparedStatement pstmt = conn.prepareStatement(SQL); pstmt.setString(1, userID); rs = pstmt.executeQuery(); if (rs.next()) { User user = new User(); user.setUserID(rs.getString(1)); user.setUserPassword(rs.getString(2)); user.setUserName(rs.getString(3)); user.setUserGender(rs.getString(4)); user.setUserEmail(rs.getString(5)); return user; } } catch (Exception e) { e.printStackTrace(); } return null; } public int update(String userPasswaord, String userName, String userEmail, String userID) { String SQL = "UPDATE User SET userPasswaord = ?, userName = ?, userEmail = ? WHERE userID = ?"; try { PreparedStatement pstmt = conn.prepareStatement(SQL); pstmt.setString(1, userPasswaord); pstmt.setString(2, userName); pstmt.setString(3, userEmail); pstmt.setString(4, userID); return pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return -1; // database error } //여기까지,, }
27.54902
153
0.679359
317b11ac033de91d2c2ddf0e377d57983f423275
1,901
package mezz.jei.test.lib; import javax.annotation.Nullable; import java.util.Collections; import mezz.jei.api.ingredients.IIngredientHelper; import mezz.jei.api.ingredients.subtypes.UidContext; public class TestIngredientHelper implements IIngredientHelper<TestIngredient> { @Override @Nullable @Deprecated public TestIngredient getMatch(Iterable<TestIngredient> ingredients, TestIngredient toMatch) { return getMatch(ingredients, toMatch, UidContext.Ingredient); } @Nullable @Override public TestIngredient getMatch(Iterable<TestIngredient> ingredients, TestIngredient ingredientToMatch, UidContext context) { for (TestIngredient ingredient : ingredients) { if (ingredient.getNumber() == ingredientToMatch.getNumber()) { String keyLhs = getUniqueId(ingredientToMatch, context); String keyRhs = getUniqueId(ingredient, context); if (keyLhs.equals(keyRhs)) { return ingredient; } } } return null; } @Override public String getDisplayName(TestIngredient ingredient) { return "Test Ingredient Display Name " + ingredient; } @Override public String getUniqueId(TestIngredient ingredient) { return "Test Ingredient Unique Id " + ingredient; } @Override public String getWildcardId(TestIngredient ingredient) { return "Test Ingredient Unique Id"; } @Override public String getModId(TestIngredient ingredient) { return "JEI Test Mod"; } @Override public Iterable<Integer> getColors(TestIngredient ingredient) { return Collections.singleton(0xFF000000); } @Override public String getResourceId(TestIngredient ingredient) { return "Test Ingredient Resource Id " + ingredient; } @Override public TestIngredient copyIngredient(TestIngredient ingredient) { return ingredient.copy(); } @Override public String getErrorInfo(@Nullable TestIngredient ingredient) { return "Test Ingredient Error Info " + ingredient; } }
26.402778
125
0.772225
eebc04d911fe0dd58536b1e2fea7cf31265b5d05
50,013
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package xni; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.Enumeration; import org.apache.xerces.parsers.XMLDocumentParser; import org.apache.xerces.util.ObjectFactory; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDTDContentModelHandler; import org.apache.xerces.xni.XMLDTDHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLErrorHandler; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.parser.XMLParseException; import org.apache.xerces.xni.parser.XMLParserConfiguration; /** * Provides a complete trace of XNI document and DTD events for * files parsed. * * @author Andy Clark, IBM * @author Arnaud Le Hors, IBM * * @version $Id: DocumentTracer.java,v 1.23 2003/04/10 19:40:27 neilg Exp $ */ public class DocumentTracer extends XMLDocumentParser implements XMLErrorHandler { // // Constants // // feature ids /** Namespaces feature id (http://xml.org/sax/features/namespaces). */ protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces"; /** Validation feature id (http://xml.org/sax/features/validation). */ protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation"; /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */ protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema"; /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */ protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking"; /** Character ref notification feature id (http://apache.org/xml/features/scanner/notify-char-refs). */ protected static final String NOTIFY_CHAR_REFS_FEATURE_ID = "http://apache.org/xml/features/scanner/notify-char-refs"; // default settings /** Default parser configuration (org.apache.xerces.parsers.XML11Configuration). */ protected static final String DEFAULT_PARSER_CONFIG = "org.apache.xerces.parsers.XML11Configuration"; /** Default namespaces support (true). */ protected static final boolean DEFAULT_NAMESPACES = true; /** Default validation support (false). */ protected static final boolean DEFAULT_VALIDATION = false; /** Default Schema validation support (false). */ protected static final boolean DEFAULT_SCHEMA_VALIDATION = false; /** Default Schema full checking support (false). */ protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false; /** Default character notifications (false). */ protected static final boolean DEFAULT_NOTIFY_CHAR_REFS = false; // // Data // /** Temporary QName. */ private QName fQName = new QName(); /** Print writer. */ protected PrintWriter fOut; /** Indent level. */ protected int fIndent; protected NamespaceContext fNamespaceContext; // // Constructors // /** Default constructor. */ public DocumentTracer() { this(null); } // <init>() /** Default constructor. */ public DocumentTracer(XMLParserConfiguration config) { super(config); setOutput(new PrintWriter(System.out)); fConfiguration.setErrorHandler(this); } // <init>(XMLParserConfiguration) // // Public methods // /** Sets the output stream for printing. */ public void setOutput(OutputStream stream, String encoding) throws UnsupportedEncodingException { if (encoding == null) { encoding = "UTF8"; } Writer writer = new OutputStreamWriter(stream, encoding); fOut = new PrintWriter(writer); } // setOutput(OutputStream,String) /** Sets the output writer. */ public void setOutput(Writer writer) { fOut = writer instanceof PrintWriter ? (PrintWriter)writer : new PrintWriter(writer); } // setOutput(Writer) // // XMLDocumentHandler methods // /** * The start of the document. * * @param systemId The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument(XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { fNamespaceContext = namespaceContext; fIndent = 0; printIndent(); fOut.print("startDocument("); fOut.print("locator="); if (locator == null) { fOut.print("null"); } else { fOut.print('{'); fOut.print("publicId="); printQuotedString(locator.getPublicId()); fOut.print(','); fOut.print("literal systemId="); printQuotedString(locator.getLiteralSystemId()); fOut.print(','); fOut.print("baseSystemId="); printQuotedString(locator.getBaseSystemId()); fOut.print(','); fOut.print("expanded systemId="); printQuotedString(locator.getExpandedSystemId()); fOut.print(','); fOut.print("lineNumber="); fOut.print(locator.getLineNumber()); fOut.print(','); fOut.print("columnNumber="); fOut.print(locator.getColumnNumber()); fOut.print('}'); } fOut.print(','); fOut.print("encoding="); printQuotedString(encoding); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // XMLLocator() /** XML Declaration. */ public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { printIndent(); fOut.print("xmlDecl("); fOut.print("version="); printQuotedString(version); fOut.print(','); fOut.print("encoding="); printQuotedString(encoding); fOut.print(','); fOut.print("standalone="); printQuotedString(standalone); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); } // xmlDecl(String,String,String,String) /** Doctype declaration. */ public void doctypeDecl(String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { printIndent(); fOut.print("doctypeDecl("); fOut.print("rootElement="); printQuotedString(rootElement); fOut.print(','); fOut.print("publicId="); printQuotedString(publicId); fOut.print(','); fOut.print("systemId="); printQuotedString(systemId); fOut.println(')'); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.flush(); } // doctypeDecl(String,String,String) /** Start element. */ public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { printInScopeNamespaces(); printIndent(); fOut.print("startElement("); printElement(element, attributes); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startElement(QName,XMLAttributes) /** Empty element. */ public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { printInScopeNamespaces(); printIndent(); fOut.print("emptyElement("); printElement(element, attributes); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); printEndNamespaceMapping(); } // emptyElement(QName,XMLAttributes) public void characters(XMLString text, Augmentations augs) throws XNIException { printIndent(); fOut.print("characters("); fOut.print("text="); printQuotedString(text.ch, text.offset, text.length); /*** if (augs != null) { ElementPSVI element = (ElementPSVI)augs.getItem(Constants.ELEMENT_PSVI); fOut.print(",schemaNormalized="); printQuotedString(element.getSchemaNormalizedValue()); } /***/ if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // characters(XMLString) /** Ignorable whitespace. */ public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { printIndent(); fOut.print("ignorableWhitespace("); fOut.print("text="); printQuotedString(text.ch, text.offset, text.length); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // ignorableWhitespace(XMLString) /** End element. */ public void endElement(QName element, Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endElement("); fOut.print("element="); fOut.print('{'); fOut.print("prefix="); printQuotedString(element.prefix); fOut.print(','); fOut.print("localpart="); printQuotedString(element.localpart); fOut.print(','); fOut.print("rawname="); printQuotedString(element.rawname); fOut.print(','); fOut.print("uri="); printQuotedString(element.uri); fOut.print('}'); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); printEndNamespaceMapping(); } // endElement(QName) /** Start CDATA section. */ public void startCDATA(Augmentations augs) throws XNIException { printIndent(); fOut.print("startCDATA("); if (augs != null) { printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startCDATA() /** End CDATA section. */ public void endCDATA(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endCDATA("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endCDATA() /** Start entity. */ public void startGeneralEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { printIndent(); fOut.print("startGeneralEntity("); fOut.print("name="); printQuotedString(name); fOut.print(','); fOut.print("identifier="); fOut.print(identifier); fOut.print(','); fOut.print("encoding="); printQuotedString(encoding); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startEntity(String,String,String,String) /** Text declaration. */ public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { printIndent(); fOut.print("textDecl("); fOut.print("version="); printQuotedString(version); fOut.print(','); fOut.print("encoding="); printQuotedString(encoding); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // textDecl(String,String) /** Comment. */ public void comment(XMLString text, Augmentations augs) throws XNIException { printIndent(); fOut.print("comment("); fOut.print("text="); printQuotedString(text.ch, text.offset, text.length); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // comment(XMLText) /** Processing instruction. */ public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { printIndent(); fOut.print("processingInstruction("); fOut.print("target="); printQuotedString(target); fOut.print(','); fOut.print("data="); printQuotedString(data.ch, data.offset, data.length); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // processingInstruction(String,XMLString) /** End entity. */ public void endGeneralEntity(String name, Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endGeneralEntity("); fOut.print("name="); printQuotedString(name); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endEntity(String) /** End document. */ public void endDocument(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endDocument("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endDocument(); // // XMLDTDHandler // /** Start DTD. */ public void startDTD(XMLLocator locator, Augmentations augs) throws XNIException { printIndent(); fOut.print("startDTD("); fOut.print("locator="); if (locator == null) { fOut.print("null"); } else { fOut.print('{'); fOut.print("publicId="); printQuotedString(locator.getPublicId()); fOut.print(','); fOut.print("literal systemId="); printQuotedString(locator.getLiteralSystemId()); fOut.print(','); fOut.print("baseSystemId="); printQuotedString(locator.getBaseSystemId()); fOut.print(','); fOut.print("expanded systemId="); printQuotedString(locator.getExpandedSystemId()); fOut.print(','); fOut.print("lineNumber="); fOut.print(locator.getLineNumber()); fOut.print(','); fOut.print("columnNumber="); fOut.print(locator.getColumnNumber()); fOut.print('}'); } if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startDTD(XMLLocator) /** Start external subset. */ public void startExternalSubset(XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { printIndent(); fOut.print("startExternalSubset("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startExternalSubset(Augmentations) /** End external subset. */ public void endExternalSubset(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endExternalSubset("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endExternalSubset(Augmentations) /** Characters.*/ public void ignoredCharacters(XMLString text, Augmentations augs) throws XNIException { printIndent(); fOut.print("ignoredCharacters("); fOut.print("text="); printQuotedString(text.ch, text.offset, text.length); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // characters(XMLString) /** Start entity. */ public void startParameterEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { printIndent(); fOut.print("startParameterEntity("); fOut.print("name="); printQuotedString(name); fOut.print(','); fOut.print("identifier="); fOut.print(identifier); fOut.print(','); fOut.print("encoding="); printQuotedString(encoding); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startEntity(String,String,String,String) /** End entity. */ public void endParameterEntity(String name, Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endParameterEntity("); fOut.print("name="); printQuotedString(name); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endEntity(String) /** Element declaration. */ public void elementDecl(String name, String contentModel, Augmentations augs) throws XNIException { printIndent(); fOut.print("elementDecl("); fOut.print("name="); printQuotedString(name); fOut.print(','); fOut.print("contentModel="); printQuotedString(contentModel); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // elementDecl(String,String) /** Start attribute list. */ public void startAttlist(String elementName, Augmentations augs) throws XNIException { printIndent(); fOut.print("startAttlist("); fOut.print("elementName="); printQuotedString(elementName); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startAttlist(String) /** Attribute declaration. */ public void attributeDecl(String elementName, String attributeName, String type, String[] enumeration, String defaultType, XMLString defaultValue, XMLString nonNormalizedDefaultValue, Augmentations augs) throws XNIException { printIndent(); fOut.print("attributeDecl("); fOut.print("elementName="); printQuotedString(elementName); fOut.print(','); fOut.print("attributeName="); printQuotedString(attributeName); fOut.print(','); fOut.print("type="); printQuotedString(type); fOut.print(','); fOut.print("enumeration="); if (enumeration == null) { fOut.print("null"); } else { fOut.print('{'); for (int i = 0; i < enumeration.length; i++) { printQuotedString(enumeration[i]); if (i < enumeration.length - 1) { fOut.print(','); } } fOut.print('}'); } fOut.print(','); fOut.print("defaultType="); printQuotedString(defaultType); fOut.print(','); fOut.print("defaultValue="); if (defaultValue == null) { fOut.print("null"); } else { printQuotedString(defaultValue.ch, defaultValue.offset, defaultValue.length); } fOut.print(','); fOut.print("nonNormalizedDefaultValue="); if (nonNormalizedDefaultValue == null) { fOut.print("null"); } else { printQuotedString(nonNormalizedDefaultValue.ch, nonNormalizedDefaultValue.offset, nonNormalizedDefaultValue.length); } if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // attributeDecl(String,String,String,String[],String,XMLString) /** End attribute list. */ public void endAttlist(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endAttlist("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endAttlist() /** Internal entity declaration. */ public void internalEntityDecl(String name, XMLString text, XMLString nonNormalizedText, Augmentations augs) throws XNIException { printIndent(); fOut.print("internalEntityDecl("); fOut.print("name="); printQuotedString(name); fOut.print(','); fOut.print("text="); printQuotedString(text.ch, text.offset, text.length); fOut.print(','); fOut.print("nonNormalizedText="); printQuotedString(nonNormalizedText.ch, nonNormalizedText.offset, nonNormalizedText.length); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // internalEntityDecl(String,XMLString) /** External entity declaration. */ public void externalEntityDecl(String name,XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { printIndent(); fOut.print("externalEntityDecl("); fOut.print("name="); printQuotedString(name); fOut.print(','); fOut.print("publicId="); printQuotedString(identifier.getPublicId()); fOut.print(','); fOut.print("systemId="); printQuotedString(identifier.getLiteralSystemId()); fOut.print(','); fOut.print("baseSystemId="); printQuotedString(identifier.getBaseSystemId()); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // externalEntityDecl(String,String,String) /** Unparsed entity declaration. */ public void unparsedEntityDecl(String name, XMLResourceIdentifier identifier, String notation, Augmentations augs) throws XNIException { printIndent(); fOut.print("unparsedEntityDecl("); fOut.print("name="); printQuotedString(name); fOut.print(','); fOut.print("publicId="); printQuotedString(identifier.getPublicId()); fOut.print(','); fOut.print("systemId="); printQuotedString(identifier.getLiteralSystemId()); fOut.print(','); fOut.print("baseSystemId="); printQuotedString(identifier.getBaseSystemId()); fOut.print(','); fOut.print("notation="); printQuotedString(notation); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // unparsedEntityDecl(String,String,String,String) /** Notation declaration. */ public void notationDecl(String name, XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { printIndent(); fOut.print("notationDecl("); fOut.print("name="); printQuotedString(name); fOut.print(','); fOut.print("publicId="); printQuotedString(identifier.getPublicId()); fOut.print(','); fOut.print("systemId="); printQuotedString(identifier.getLiteralSystemId()); fOut.print(','); fOut.print("baseSystemId="); printQuotedString(identifier.getBaseSystemId()); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // notationDecl(String,String,String) /** Start conditional section. */ public void startConditional(short type, Augmentations augs) throws XNIException { printIndent(); fOut.print("startConditional("); fOut.print("type="); switch (type) { case XMLDTDHandler.CONDITIONAL_IGNORE: { fOut.print("CONDITIONAL_IGNORE"); break; } case XMLDTDHandler.CONDITIONAL_INCLUDE: { fOut.print("CONDITIONAL_INCLUDE"); break; } default: { fOut.print("??? ("+type+')'); } } if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startConditional(short) /** End conditional section. */ public void endConditional(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endConditional("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endConditional() /** End DTD. */ public void endDTD(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endDTD("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endDTD() // // XMLDTDContentModelHandler methods // /** Start content model. */ public void startContentModel(String elementName, Augmentations augs) throws XNIException { printIndent(); fOut.print("startContentModel("); fOut.print("elementName="); printQuotedString(elementName); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // startContentModel(String) /** Any. */ public void any(Augmentations augs) throws XNIException { printIndent(); fOut.print("any("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // any() /** Empty. */ public void empty(Augmentations augs) throws XNIException { printIndent(); fOut.print("empty("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // empty() /** Start group. */ public void startGroup(Augmentations augs) throws XNIException { printIndent(); fOut.print("startGroup("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); fIndent++; } // childrenStartGroup() /** #PCDATA. */ public void pcdata(Augmentations augs) throws XNIException { printIndent(); fOut.print("pcdata("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // pcdata() /** Element. */ public void element(String elementName, Augmentations augs) throws XNIException { printIndent(); fOut.print("element("); fOut.print("elementName="); printQuotedString(elementName); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // element(String) /** separator. */ public void separator(short separator, Augmentations augs) throws XNIException { printIndent(); fOut.print("separator("); fOut.print("separator="); switch (separator) { case XMLDTDContentModelHandler.SEPARATOR_CHOICE: { fOut.print("SEPARATOR_CHOICE"); break; } case XMLDTDContentModelHandler.SEPARATOR_SEQUENCE: { fOut.print("SEPARATOR_SEQUENCE"); break; } default: { fOut.print("??? ("+separator+')'); } } if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // separator(short) /** Occurrence. */ public void occurrence(short occurrence, Augmentations augs) throws XNIException { printIndent(); fOut.print("occurrence("); fOut.print("occurrence="); switch (occurrence) { case XMLDTDContentModelHandler.OCCURS_ONE_OR_MORE: { fOut.print("OCCURS_ONE_OR_MORE"); break; } case XMLDTDContentModelHandler.OCCURS_ZERO_OR_MORE: { fOut.print("OCCURS_ZERO_OR_MORE"); break; } case XMLDTDContentModelHandler.OCCURS_ZERO_OR_ONE: { fOut.print("OCCURS_ZERO_OR_ONE"); break; } default: { fOut.print("??? ("+occurrence+')'); } } if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // occurrence(short) /** End group. */ public void endGroup(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endGroup("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // childrenEndGroup() /** End content model. */ public void endContentModel(Augmentations augs) throws XNIException { fIndent--; printIndent(); fOut.print("endContentModel("); if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.println(')'); fOut.flush(); } // endContentModel() // // XMLErrorHandler methods // /** Warning. */ public void warning(String domain, String key, XMLParseException ex) throws XNIException { printError("Warning", ex); } // warning(String,String,XMLParseException) /** Error. */ public void error(String domain, String key, XMLParseException ex) throws XNIException { printError("Error", ex); } // error(String,String,XMLParseException) /** Fatal error. */ public void fatalError(String domain, String key, XMLParseException ex) throws XNIException { printError("Fatal Error", ex); throw ex; } // fatalError(String,String,XMLParseException) // // Protected methods // protected void printInScopeNamespaces(){ int count = fNamespaceContext.getDeclaredPrefixCount(); if (count>0){ for (int i = 0; i < count; i++) { printIndent(); fOut.print("declaredPrefix("); fOut.print("prefix="); String prefix = fNamespaceContext.getDeclaredPrefixAt(i); printQuotedString(prefix); fOut.print(','); fOut.print("uri="); printQuotedString(fNamespaceContext.getURI(prefix)); fOut.println(')'); fOut.flush(); } } } protected void printEndNamespaceMapping(){ int count = fNamespaceContext.getDeclaredPrefixCount(); if (count > 0) { for (int i = 0; i < count; i++) { printIndent(); fOut.print("endPrefix("); fOut.print("prefix="); String prefix = fNamespaceContext.getDeclaredPrefixAt(i); printQuotedString(prefix); fOut.println(')'); fOut.flush(); } } } /** Prints an element. */ protected void printElement(QName element, XMLAttributes attributes) { fOut.print("element="); fOut.print('{'); fOut.print("prefix="); printQuotedString(element.prefix); fOut.print(','); fOut.print("localpart="); printQuotedString(element.localpart); fOut.print(','); fOut.print("rawname="); printQuotedString(element.rawname); fOut.print(','); fOut.print("uri="); printQuotedString(element.uri); fOut.print('}'); fOut.print(','); fOut.print("attributes="); if (attributes == null) { fOut.println("null"); } else { fOut.print('{'); int length = attributes.getLength(); for (int i = 0; i < length; i++) { if (i > 0) { fOut.print(','); } attributes.getName(i, fQName); String attrType = attributes.getType(i); String attrValue = attributes.getValue(i); String attrNonNormalizedValue = attributes.getNonNormalizedValue(i); Augmentations augs = attributes.getAugmentations(i); fOut.print("name="); fOut.print('{'); fOut.print("prefix="); printQuotedString(fQName.prefix); fOut.print(','); fOut.print("localpart="); printQuotedString(fQName.localpart); fOut.print(','); fOut.print("rawname="); printQuotedString(fQName.rawname); fOut.print(','); fOut.print("uri="); printQuotedString(fQName.uri); fOut.print('}'); fOut.print(','); fOut.print("type="); printQuotedString(attrType); fOut.print(','); fOut.print("value="); printQuotedString(attrValue); fOut.print(','); fOut.print("nonNormalizedValue="); printQuotedString(attrNonNormalizedValue); if (attributes.isSpecified(i) == false ) { fOut.print("(default)"); } if (augs != null) { fOut.print(','); printAugmentations(augs); } fOut.print('}'); } fOut.print('}'); } } // printElement(QName,XMLAttributes) /** Prints augmentations. */ protected void printAugmentations(Augmentations augs) { fOut.print("augs={"); java.util.Enumeration keys = augs.keys(); while (keys.hasMoreElements()) { String key = (String)keys.nextElement(); Object value = augs.getItem(key); fOut.print(key); fOut.print('#'); fOut.print(String.valueOf(value)); } fOut.print('}'); } // printAugmentations(Augmentations) /** Print quoted string. */ protected void printQuotedString(String s) { if (s == null) { fOut.print("null"); return; } fOut.print('"'); int length = s.length(); for (int i = 0; i < length; i++) { char c = s.charAt(i); normalizeAndPrint(c); } fOut.print('"'); } // printQuotedString(String) /** Print quoted string. */ protected void printQuotedString(char[] ch, int offset, int length) { fOut.print('"'); for (int i = 0; i < length; i++) { normalizeAndPrint(ch[offset + i]); } fOut.print('"'); } // printQuotedString(char[],int,int) /** Normalize and print. */ protected void normalizeAndPrint(char c) { switch (c) { case '\n': { fOut.print("\\n"); break; } case '\r': { fOut.print("\\r"); break; } case '\t': { fOut.print("\\t"); break; } case '\\': { fOut.print("\\\\"); break; } case '"': { fOut.print("\\\""); break; } default: { fOut.print(c); } } } // normalizeAndPrint(char) /** Prints the error message. */ protected void printError(String type, XMLParseException ex) { System.err.print("["); System.err.print(type); System.err.print("] "); String systemId = ex.getExpandedSystemId(); if (systemId != null) { int index = systemId.lastIndexOf('/'); if (index != -1) systemId = systemId.substring(index + 1); System.err.print(systemId); } System.err.print(':'); System.err.print(ex.getLineNumber()); System.err.print(':'); System.err.print(ex.getColumnNumber()); System.err.print(": "); System.err.print(ex.getMessage()); System.err.println(); System.err.flush(); } // printError(String,XMLParseException) /** Prints the indent. */ protected void printIndent() { for (int i = 0; i < fIndent; i++) { fOut.print(' '); } } // printIndent() // // MAIN // /** Main. */ public static void main(String[] argv) throws Exception { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables XMLDocumentParser parser = null; XMLParserConfiguration parserConfig = null; boolean namespaces = DEFAULT_NAMESPACES; boolean validation = DEFAULT_VALIDATION; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean notifyCharRefs = DEFAULT_NOTIFY_CHAR_REFS; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } String parserName = argv[i]; // create parser try { parserConfig = (XMLParserConfiguration)ObjectFactory.newInstance(parserName, ObjectFactory.findClassLoader(), true); parser = null; } catch (Exception e) { parserConfig = null; System.err.println("error: Unable to instantiate parser configuration ("+parserName+")"); } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("c")) { notifyCharRefs = option.equals("c"); continue; } if (option.equals("h")) { printUsage(); continue; } } // use default parser? if (parserConfig == null) { // create parser try { parserConfig = (XMLParserConfiguration)ObjectFactory.newInstance(DEFAULT_PARSER_CONFIG, ObjectFactory.findClassLoader(), true); } catch (Exception e) { System.err.println("error: Unable to instantiate parser configuration ("+DEFAULT_PARSER_CONFIG+")"); continue; } } // set parser features if (parser == null) { parser = new DocumentTracer(parserConfig); } try { parserConfig.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (XMLConfigurationException e) { System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")"); } try { parserConfig.setFeature(VALIDATION_FEATURE_ID, validation); } catch (XMLConfigurationException e) { System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")"); } try { parserConfig.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (XMLConfigurationException e) { if (e.getType() == XMLConfigurationException.NOT_SUPPORTED) { System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")"); } } try { parserConfig.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (XMLConfigurationException e) { if (e.getType() == XMLConfigurationException.NOT_SUPPORTED) { System.err.println("warning: Parser does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } } try { parserConfig.setFeature(NOTIFY_CHAR_REFS_FEATURE_ID, notifyCharRefs); } catch (XMLConfigurationException e) { if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) { //e.printStackTrace(); System.err.println("warning: Parser does not recognize feature ("+NOTIFY_CHAR_REFS_FEATURE_ID+")"); } else { System.err.println("warning: Parser does not support feature ("+NOTIFY_CHAR_REFS_FEATURE_ID+")"); } } // parse file try { parser.parse(new XMLInputSource(null, arg, null)); } catch (XMLParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); if (e instanceof XNIException) { e = ((XNIException)e).getException(); } e.printStackTrace(System.err); } } } // main(String[]) // // Private static methods // /** Prints the usage. */ private static void printUsage() { System.err.println("usage: java xni.DocumentTracer (options) uri ..."); System.err.println(); System.err.println("options:"); System.out.println(" -p name Specify parser configuration by name."); System.err.println(" -n | -N Turn on/off namespace processing."); System.err.println(" -v | -V Turn on/off validation."); System.err.println(" -s | -S Turn on/off Schema validation support."); System.err.println(" NOTE: Not supported by all parser configurations."); System.err.println(" -f | -F Turn on/off Schema full checking."); System.err.println(" NOTE: Requires use of -s and not supported by all parsers."); System.err.println(" -c | -C Turn on/off character notifications"); System.err.println(" -h This help screen."); System.err.println(); System.err.println("defaults:"); System.out.println(" Config: "+DEFAULT_PARSER_CONFIG); System.out.print(" Namespaces: "); System.err.println(DEFAULT_NAMESPACES ? "on" : "off"); System.out.print(" Validation: "); System.err.println(DEFAULT_VALIDATION ? "on" : "off"); System.out.print(" Schema: "); System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off"); System.err.print(" Schema full checking: "); System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off"); System.out.print(" Char refs: "); System.err.println(DEFAULT_NOTIFY_CHAR_REFS ? "on" : "off" ); } // printUsage() } // class DocumentTracer
31.534048
121
0.545478
52fa5f13d98402eb5837ccdf7e5f1ec64b01b6b2
254
package poem; public class DisplayPoem { /** * This class displays a developer-supplied poem of variable length. * * @author {YOUR NAME HERE} */ public static void main(String[] args) { // TODO Replace with multi-line comment. } }
19.538462
70
0.65748
deb62ea839cd8600a7b9e80c435fa8ae1ad7f5f7
1,582
package com.yscoco.uppernest; import android.app.Activity; import com.squareup.leakcanary.LeakCanary; import com.yscoco.uppernest.commonlibrary.base.activity.BaseActivity; import com.yscoco.uppernest.commonlibrary.global.GlobalApplication; import me.jessyan.autosize.AutoSize; import me.jessyan.autosize.AutoSizeConfig; import me.jessyan.autosize.external.ExternalAdaptInfo; import me.jessyan.autosize.onAdaptListener; /** * Created by ZhangZeZhi on 2018-11-19. */ public class MyApplication extends GlobalApplication { public static MyApplication app; @Override public void onCreate() { super.onCreate(); app = this; initThreeService(); } private void initThreeService() { if (LeakCanary.isInAnalyzerProcess(this)) { return; } LeakCanary.install(this); AutoSizeConfig.getInstance() .setCustomFragment(true) .setOnAdaptListener(new onAdaptListener() { @Override public void onAdaptBefore(Object target, Activity activity) { } @Override public void onAdaptAfter(Object target, Activity activity) { } }); AutoSize.initCompatMultiProcess(this); customAdaptForExternal(); } private void customAdaptForExternal() { AutoSizeConfig.getInstance().getExternalAdaptManager() .addExternalAdaptInfoOfActivity(BaseActivity.class, new ExternalAdaptInfo(true, 400)); } }
26.366667
102
0.649178
5a0c2519488313f9f81f816e0bc2e7406d04620d
1,245
package com.twu.biblioteca; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ReturnBookOptionTest { private Library library; private Console console; private ReturnBookOption returnBookOption; @Before public void setUp() throws Exception { library = mock(Library.class); console = mock(Console.class); returnBookOption = new ReturnBookOption(library, console); when(console.getUserInput()).thenReturn("1"); } @Test public void shouldDisplayCheckedOutBooksOnExecute() { returnBookOption.execute(); verify(library).displayCheckedOutBooksWithNumbers(); } @Test public void shouldPromptUserOnExecute() { returnBookOption.execute(); verify(console).displayChooseBookPromptMessage(); } @Test public void shouldGetInputFromConsoleOnExecute() { returnBookOption.execute(); verify(console).getUserInput(); } @Test public void shouldReturnBook1WhenExecuteCalledWithInput1(){ returnBookOption.execute(); verify(library).returnBook(1); } }
23.055556
66
0.694779
ec6238b49d105605983f7b3051c0887bb622d74e
2,119
package hulkstore_.controller.document; import hulkstore_.model.dao.DaoFactory; import hulkstore_.model.dao.document.DocumentDao; import hulkstore_.model.dao.document.DocumentDaoException; import hulkstore_.model.dto.document.DocumentDto; import hulkstore_.view.document.UIInsertDocument; import javax.swing.JOptionPane; import javax.swing.JTextField; /** * Document Insertion Controller * * Receive and validate data on a new document record * * @author Luis Mercado * @version 0.1 * @since 2020-03-11 */ public final class CInsertDocument { private final UIInsertDocument window; private final DocumentDao documentDao = DaoFactory.createDocumentDao(); /** * Empty Contructor. */ public CInsertDocument() { window = new UIInsertDocument(this); } /** * Upload the document_Id to the form. * * @param txtDocumentId */ public void upload(JTextField txtDocumentId) { try { txtDocumentId.setText(documentDao.findNextDocumentId()); } catch (DocumentDaoException exeption) {} } /** * Register the new document. * * @param txtDocumentId * @param txtDescription */ public void accept(JTextField txtDocumentId, JTextField txtDescription) { try { DocumentDto dto = new DocumentDto(Integer.parseInt(txtDocumentId.getText()), txtDescription.getText()); if(!documentDao.insert(dto).isDocumentIdNull()){ JOptionPane.showMessageDialog(null, "Se ha agregado el registro nuevo", "INSERCION", JOptionPane.INFORMATION_MESSAGE); CDocument cDocument = new CDocument(); window.dispose(); } else { JOptionPane.showMessageDialog(null, "No se registro", "ERROR", JOptionPane.ERROR_MESSAGE); } } catch (DocumentDaoException ex) {} } /** * Cancel the operation and return to the documents menu. */ public void cancel() { CDocument cDocument = new CDocument(); window.dispose(); } }
29.027397
134
0.646531
7a6a5baaf59b30eab7b95c54a60f8bc0583aa257
663
package com.android.covid19.model.vaccination; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class VaccinationDistricts { @SerializedName("districts") @Expose private List<District> districts = null; @SerializedName("ttl") @Expose private Integer ttl; public List<District> getDistricts() { return districts; } public void setDistricts(List<District> districts) { this.districts = districts; } public Integer getTtl() { return ttl; } public void setTtl(Integer ttl) { this.ttl = ttl; } }
19.5
56
0.669683
870f50aa43b517a0c0be8b22a3bd352bc37673e3
877
package net.minidev.ovh.api.dedicated.server.backup; /** * A structure describing informations about the backup cloud feature */ public class OvhBackupContainer { /** * Quota on the current container * * canBeNull */ public OvhBackupQuota quota; /** * Container name. * * canBeNull */ public String name; /** * Sftp connection info * * canBeNull */ public OvhBackupSftp sftp; /** * Container id (can also be used to retrieve the resource in the /cloud api). * * canBeNull */ public String id; /** * The cloud region which the container belongs to. * * canBeNull */ public String region; /** * /cloud project which the container belongs to. * * canBeNull */ public OvhBackupProject cloudProject; /** * Swift related information to reach the container * * canBeNull */ public OvhBackupSwift swift; }
15.660714
79
0.665906
5855e56331e2eb1af68ec6e237d76e27fee78e0d
5,193
package org.ifelse.ui; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.view.Display; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import org.ifelse.vl.NLog; import org.ifelse.wordspelling.R; import java.util.Timer; import java.util.Vector; /** * TODO: document your custom view class. */ public class DDialog extends Dialog { public int tag; public Timer timer; public View contentView; public DDialog(Context context) { super(context); } public DDialog(Context context, int themeResId) { super(context, themeResId); } protected DDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } public View findViewById(int id){ if( contentView != null ) return contentView.findViewById(id); else return null; } public void setRunable(Runnable runable) { new Thread(runable).start(); } public static class ButtonListener{ private int viewid; private OnClickListener listener; public ButtonListener(int viewid, OnClickListener listener){ this.viewid = viewid; this.listener = listener; } } public static interface ViewInitListener{ public void ViewInit(View view); } public static DDialog ddialog; @Override public void dismiss() { try { if (DDialog.ddialog.timer != null) DDialog.ddialog.timer.cancel(); DDialog.ddialog.timer = null; if( isShowing() ) super.dismiss(); DDialog.ddialog = null; }catch (Exception e){ NLog.e(e); } } public static void fdimiss(){ try { if (DDialog.ddialog != null && DDialog.ddialog.isShowing()) { DDialog.ddialog.dismiss(); } }catch (Exception e){ } } public static class Builder { private Context context; private int layout; ViewInitListener viewListener; OnDismissListener onDismissListener; private Vector<ButtonListener> buttons = new Vector<>(); private boolean cancelable = false; private int tag; private int style = R.style.ConfirmDialog; public Builder setStyle(int styleid){ style = styleid; return this; } public Builder setTag(int t){ tag = t; return this; } public Builder setCancelable(boolean can){ cancelable = can; return this; } public Builder setInitListener(ViewInitListener listener){ viewListener = listener; return this; } public Builder setOnDimissListener(OnDismissListener l){ onDismissListener = l; return this; } public Builder(Context context) { this.context = context; } public Builder addButtonListener(int viewid, OnClickListener listener){ buttons.add(new ButtonListener(viewid,listener) ); return this; } public Builder setContentView(int layout){ this.layout = layout; return this; } public DDialog create() { fdimiss(); // instantiate the dialog with the custom Theme final DDialog dialog = new DDialog(context, style); View contentView = View.inflate(context, layout, null); for(final ButtonListener bl : buttons){ contentView.findViewById(bl.viewid).setOnClickListener( new View.OnClickListener(){ @Override public void onClick(View v) { NLog.i("DDialog click button:%s",v); bl.listener.onClick( dialog,bl.viewid ); } } ); } if( onDismissListener != null ) dialog.setOnDismissListener(onDismissListener); dialog.setCancelable(this.cancelable); if( viewListener != null ) viewListener.ViewInit(contentView); dialog.setContentView(contentView); Window dialogWindow = dialog.getWindow(); WindowManager m = ((Activity)context).getWindowManager(); Display d = m.getDefaultDisplay(); WindowManager.LayoutParams p = dialogWindow.getAttributes(); p.height = LayoutParams.MATCH_PARENT; p.width = LayoutParams.MATCH_PARENT; p.gravity = Gravity.CENTER; dialogWindow.setAttributes(p); DDialog.ddialog = dialog; ddialog.tag = tag; dialog.contentView = contentView; return dialog; } } }
22.097872
93
0.568458
ad6caf08d318b6c0cf5f00366e78380bdde192a2
4,942
package cn.org.dianjiu.job.controller; import cn.org.dianjiu.job.common.req.TUserReq; import cn.org.dianjiu.job.common.resp.TUserResp; import cn.org.dianjiu.job.common.vo.RespVO; import cn.org.dianjiu.job.service.TUserServiceI; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import java.util.List; /** * (TUser)表控制层 * * @author dianjiu * @since 2020-07-01 00:07:34 */ @RestController @RequestMapping("/tUser") public class TUserController { /** * 服务对象 */ @Autowired private TUserServiceI tUserService; /** * 通过Id查询单个对象 * * @param id 主键 * @return 实例对象 */ @GetMapping(value = "/get/{id}",produces = MediaType.APPLICATION_JSON_VALUE) public RespVO<TUserResp> getById(@PathVariable Integer id) { RespVO<TUserResp> result = new RespVO<>(); TUserResp tUserResp = tUserService.getById(id); if(null == tUserResp){ result.setCode("400"); result.setMsg("没有查到数据!"); return result; } result.setCode("200"); result.setMsg("查询成功!"); result.setData(tUserResp); return result; } /** * 通过实体不为空的属性作为筛选条件查询单个对象 * * @param tUserReq * @return 实例对象 */ @GetMapping(value = "/get",produces = MediaType.APPLICATION_JSON_VALUE) public RespVO<TUserResp> getByEntity(TUserReq tUserReq) { RespVO<TUserResp> result = new RespVO<>(); TUserResp tUserResp = tUserService.getByEntity(tUserReq); if(null == tUserResp){ result.setCode("400"); result.setMsg("没有查到数据!"); return result; } result.setCode("200"); result.setMsg("查询成功!"); result.setData(tUserResp); return result; } /** * 通过实体不为空的属性作为筛选条件查询对象列表 * * @param tUserReq 实例对象 * @return 对象列表 */ @GetMapping(value = "/list",produces = MediaType.APPLICATION_JSON_VALUE) public RespVO<List> list(TUserReq tUserReq) { RespVO<List> result = new RespVO<>(); List<TUserResp> tUserRespList = tUserService.listByEntity(tUserReq); if(null == tUserRespList || tUserRespList.isEmpty()){ result.setCode("400"); result.setMsg("没有查到数据!"); return result; } result.setCode("200"); result.setMsg("请求成功!"); result.setData(tUserRespList); return result; } /** * 新增实体属性不为null的记录 * * @param tUserReq 实例对象 * @return 实例对象 */ @PostMapping(value = "/insert",produces = MediaType.APPLICATION_JSON_VALUE) public RespVO<TUserResp> insert(@RequestBody @Validated TUserReq tUserReq){ RespVO<TUserResp> result = new RespVO<>(); int insert = tUserService.insert(tUserReq); if(insert !=1 ){ result.setCode("400"); result.setMsg("新增数据失败!"); return result; } result.setCode("200"); result.setMsg("新增数据成功!"); return result; } /** * 通过表字段修改实体属性不为null的列 * * @param tUserReq 实例对象 * @return 实例对象 */ @PutMapping(value = "/update",produces = MediaType.APPLICATION_JSON_VALUE) public RespVO<TUserResp> update(@RequestBody @Validated TUserReq tUserReq){ RespVO<TUserResp> result = new RespVO<>(); int update = tUserService.update(tUserReq); if(update != 1){ result.setCode("400"); result.setMsg("更新数据失败!"); return result; } result.setCode("200"); result.setMsg("更新数据成功!"); return result; } /** * 通过主键删除数据 * * @param id 主键 * @return 实例对象 */ @DeleteMapping(value = "/delete/{id}",produces = MediaType.APPLICATION_JSON_VALUE) public RespVO<TUserResp> deleteOne(@PathVariable Integer id){ RespVO<TUserResp> result = new RespVO<>(); int delete = tUserService.deleteById(id); if(delete != 1){ result.setCode("400"); result.setMsg("删除数据失败!"); return result; } result.setCode("200"); result.setMsg("删除数据成功!"); return result; } /** * 通过主键列表删除,列表长度不能为0 * * @param ids 实例对象 * @return 实例对象 */ @DeleteMapping(value = "/delete",produces = MediaType.APPLICATION_JSON_VALUE) public RespVO<TUserResp> deleteBatch(@RequestBody List<Integer> ids){ RespVO<TUserResp> result = new RespVO<>(); int dels = 0; if (ids!=null&&ids.size()>0) { dels = tUserService.deleteByIds(ids); } if(dels <= 0){ result.setCode("400"); result.setMsg("批量删除数据失败!"); return result; } result.setCode("200"); result.setMsg("批量删除数据成功!"); return result; } }
28.24
86
0.591866
a38b9c1c08c86a9e33112de3148d2350dc2df1ac
20,929
package uk.gov.justice.digital.delius.service; import lombok.AllArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import uk.gov.justice.digital.delius.controller.NotFoundException; import uk.gov.justice.digital.delius.data.api.Contact; import uk.gov.justice.digital.delius.data.api.ContactSummary; import uk.gov.justice.digital.delius.jpa.filters.ContactFilter; import uk.gov.justice.digital.delius.jpa.standard.entity.ContactType; import uk.gov.justice.digital.delius.jpa.standard.entity.Event; import uk.gov.justice.digital.delius.jpa.standard.entity.Offender; import uk.gov.justice.digital.delius.jpa.standard.entity.OffenderManager; import uk.gov.justice.digital.delius.jpa.standard.entity.OrderManager; import uk.gov.justice.digital.delius.jpa.standard.entity.PrisonOffenderManager; import uk.gov.justice.digital.delius.jpa.standard.entity.ProbationArea; import uk.gov.justice.digital.delius.jpa.standard.entity.Staff; import uk.gov.justice.digital.delius.jpa.standard.entity.StandardReference; import uk.gov.justice.digital.delius.jpa.standard.entity.Team; import uk.gov.justice.digital.delius.jpa.standard.repository.ContactRepository; import uk.gov.justice.digital.delius.jpa.standard.repository.ContactTypeRepository; import uk.gov.justice.digital.delius.transformers.ContactTransformer; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Optional; import static java.util.stream.Collectors.toList; import static org.springframework.data.domain.Sort.Direction.DESC; import static uk.gov.justice.digital.delius.jpa.standard.entity.Contact.*; @Service @AllArgsConstructor public class ContactService { private static final String PRISONER_OFFENDER_MANAGER_ALLOCATION_CONTACT_TYPE = "EPOMAT"; private static final String PRISONER_OFFENDER_MANAGER_INTERNAL_ALLOCATION_CONTACT_TYPE = "EPOMIN"; private static final String PRISONER_OFFENDER_MANAGER_EXTERNAL_ALLOCATION_CONTACT_TYPE = "EPOMEX"; private static final String RESPONSIBLE_OFFICER_CHANGE_CONTACT_TYPE = "ROC"; private static final String PRISON_LOCATION_CHANGE_CONTACT_TYPE = "ETCP"; private static final String CUSTODY_AUTO_UPDATE_CONTACT_TYPE = "EDSS"; private static final String TIER_UPDATE_CONTACT_TYPE = "ETCH20"; public static final String DELIUS_DATE_FORMAT = "E MMM dd yyyy"; // e.g. "Tue Nov 24 2020" private final ContactRepository contactRepository; private final ContactTypeRepository contactTypeRepository; public List<Contact> contactsFor(final Long offenderId, final ContactFilter filter) { return ContactTransformer.contactsOf(contactRepository.findAll(filter.toBuilder().offenderId(offenderId).build())); } public Page<ContactSummary> contactSummariesFor(final Long offenderId, final ContactFilter filter, final int page, final int pageSize) { final var pagination = PageRequest.of(page, pageSize, Sort.by(DESC, "contactDate", "contactStartTime", "contactEndTime")); return contactRepository.findAll(filter.toBuilder().offenderId(offenderId).build(), pagination) .map(ContactTransformer::contactSummaryOf); } @Transactional public void addContactForPOMAllocation(final PrisonOffenderManager newPrisonOffenderManager) { contactRepository.save(contactForPOMAllocation(newPrisonOffenderManager)); } @Transactional public void addContactForPOMAllocation(final PrisonOffenderManager newPrisonOffenderManager, final PrisonOffenderManager existingPrisonOffenderManager) { final var contact = contactForPOMAllocation(newPrisonOffenderManager); contactRepository.save(contact .toBuilder() .notes(appendNoteForExistingPOMAllocation(contact.getNotes(), existingPrisonOffenderManager)) .build()); } @Transactional public void addContactForResponsibleOfficerChange(final PrisonOffenderManager newPrisonOffenderManager, final PrisonOffenderManager existingPrisonOffenderManager) { final var contactType = contactTypeForResponsibleOfficerChange(); contactRepository.save(builder() .contactDate(newPrisonOffenderManager.getAllocationDate()) .contactStartTime(LocalTime.now()) .offenderId(newPrisonOffenderManager.getOffenderId()) .notes(notesForResponsibleManager(newPrisonOffenderManager, existingPrisonOffenderManager)) .team(newPrisonOffenderManager.getTeam()) .staff(newPrisonOffenderManager.getStaff()) .probationArea(newPrisonOffenderManager.getProbationArea()) .staffEmployeeId(newPrisonOffenderManager.getStaff().getStaffId()) .teamProviderId(newPrisonOffenderManager.getTeam().getTeamId()) .contactType(contactType) .alertActive(contactType.getAlertFlag()) .build()); } @Transactional public void addContactForResponsibleOfficerChange(final OffenderManager newResponsibleOfficer, final PrisonOffenderManager existingResponisbleOfficer) { addContactForResponsibleOfficerChange(newResponsibleOfficer.getOffenderId(), notesForResponsibleManager(newResponsibleOfficer, existingResponisbleOfficer), newResponsibleOfficer.getTeam(), newResponsibleOfficer.getStaff(), newResponsibleOfficer.getProbationArea()); } @Transactional public void addContactForResponsibleOfficerChange(final PrisonOffenderManager newResponsibleOfficer, final OffenderManager existingResponsibleOfficer) { addContactForResponsibleOfficerChange(newResponsibleOfficer.getOffenderId(), notesForResponsibleManager(newResponsibleOfficer, existingResponsibleOfficer), newResponsibleOfficer.getTeam(), newResponsibleOfficer.getStaff(), newResponsibleOfficer.getProbationArea()); } @Transactional public void addContactForPrisonLocationChange(final Offender offender, final Event event) { addContactForCustodyChange(offender, event, contactTypeForPrisonLocationChange(), notesForPrisonLocationChange(event)); } @Transactional public void addContactForBookingNumberUpdate(final Offender offender, final Event event) { addContactForCustodyChange(offender, event, contactTypeForCustodyAutoUpdate(), notesForBookingNumbUpdate(event)); } @Transactional public void addContactForBulkCustodyKeyDateUpdate(final Offender offender, final Event event, final Map<String, LocalDate> datesAmendedOrUpdated, final Map<String, LocalDate> datesRemoved) { addContactForCustodyChange(offender, event, contactTypeForCustodyAutoUpdate(), notesForKeyDatesUpdate(datesAmendedOrUpdated, datesRemoved)); } @Transactional public void addContactForTierUpdate(final Long offenderId, final LocalDateTime date, final String tier, final String reason, final Staff staff, final Team team){ contactRepository.save(builder() .contactDate(LocalDate.now()) .offenderId(offenderId) .contactStartTime(LocalTime.now()) .notes(String.format( "Tier Change Date: %s\n" + "Tier: %s\n" + "Tier Change Reason: %s",DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").format(date),tier,reason)) .staff(staff) .staffEmployeeId(staff.getStaffId()) .teamProviderId(team.getTeamId()) .probationArea(team.getProbationArea()) .team(team) .contactType(contactTypeRepository.findByCode(TIER_UPDATE_CONTACT_TYPE).orElseThrow(() -> new NotFoundException("Cannot find contact type for tier update"))) .build()); } public List<uk.gov.justice.digital.delius.data.api.ContactType> getContactTypes(final List<String> categories) { return (CollectionUtils.isEmpty(categories) ? contactTypeRepository.findAllBySelectableTrue() : contactTypeRepository.findAllByContactCategoriesCodeValueInAndSelectableTrue(categories)) .stream().map(ContactTransformer::contactTypeOf).collect(toList()); } public Optional<ContactSummary> getContactSummary(final Long offenderId, final Long contactId) { return contactRepository.findByContactIdAndOffenderIdAndSoftDeletedIsFalse(contactId, offenderId).map(ContactTransformer::contactSummaryOf); } private String notesForKeyDatesUpdate(final Map<String, LocalDate> datesAmendedOrUpdated, final Map<String, LocalDate> datesRemoved) { final var notes = datesAmendedOrUpdated.entrySet().stream().map(entry -> String .format("%s: %s\n", entry.getKey(), entry.getValue() .format(DateTimeFormatter.ofPattern("dd/MM/yyyy")))) .reduce("", (original, it) -> original + it); return datesRemoved.entrySet().stream().map(entry -> String .format("Removed %s: %s\n", entry.getKey(), entry.getValue() .format(DateTimeFormatter.ofPattern("dd/MM/yyyy")))) .reduce(notes, (original, it) -> original + it); } private void addContactForCustodyChange(final Offender offender, final Event event, final ContactType contactType, final String notes) { final var mayBeOrderManager = event.getOrderManagers() .stream() .filter(OrderManager::isActive) .findFirst(); contactRepository.save(builder() .contactDate(LocalDate.now()) .contactStartTime(LocalTime.now()) .offenderId(offender.getOffenderId()) .notes(notes) .team(mayBeOrderManager.map(OrderManager::getTeam).orElse(null)) .staff(mayBeOrderManager.map(OrderManager::getStaff).orElse(null)) .probationArea(mayBeOrderManager.map(OrderManager::getProbationArea).orElse(null)) .staffEmployeeId(mayBeOrderManager.flatMap(orderManager -> Optional.ofNullable(orderManager.getStaff())).map(Staff::getStaffId).orElse(null)) .teamProviderId(mayBeOrderManager.flatMap(orderManager -> Optional.ofNullable(orderManager.getTeam())).map(Team::getTeamId).orElse(null)) .contactType(contactType) .alertActive(contactType.getAlertFlag()) .event(event) .build()); } private uk.gov.justice.digital.delius.jpa.standard.entity.Contact contactForPOMAllocation(final PrisonOffenderManager newPrisonOffenderManager) { final var contactType = contactTypeForPOMAllocationOf(newPrisonOffenderManager.getAllocationReason()); return builder() .contactDate(newPrisonOffenderManager.getAllocationDate()) .contactStartTime(LocalTime.now()) .offenderId(newPrisonOffenderManager.getOffenderId()) .notes(notesForPOMAllocation(newPrisonOffenderManager)) .team(newPrisonOffenderManager.getTeam()) .staff(newPrisonOffenderManager.getStaff()) .probationArea(newPrisonOffenderManager.getProbationArea()) .staffEmployeeId(newPrisonOffenderManager.getStaff().getStaffId()) .teamProviderId(newPrisonOffenderManager.getTeam().getTeamId()) .contactType(contactType) .alertActive(contactType.getAlertFlag()) .build(); } private ContactType contactTypeForPOMAllocationOf(final StandardReference allocationReason) { switch (allocationReason.getCodeValue()) { case ReferenceDataService.POM_AUTO_TRANSFER_ALLOCATION_REASON_CODE: return contactTypeRepository.findByCode(PRISONER_OFFENDER_MANAGER_ALLOCATION_CONTACT_TYPE).orElseThrow(); case ReferenceDataService.POM_INTERNAL_TRANSFER_ALLOCATION_REASON_CODE: return contactTypeRepository.findByCode(PRISONER_OFFENDER_MANAGER_INTERNAL_ALLOCATION_CONTACT_TYPE).orElseThrow(); case ReferenceDataService.POM_EXTERNAL_TRANSFER_ALLOCATION_REASON_CODE: return contactTypeRepository.findByCode(PRISONER_OFFENDER_MANAGER_EXTERNAL_ALLOCATION_CONTACT_TYPE).orElseThrow(); default: throw new RuntimeException(String.format("Don't know what sort of contact type for POM allocation reason %s", allocationReason.getCodeValue())); } } private ContactType contactTypeForResponsibleOfficerChange() { return contactTypeRepository.findByCode(RESPONSIBLE_OFFICER_CHANGE_CONTACT_TYPE).orElseThrow(); } private ContactType contactTypeForPrisonLocationChange() { return contactTypeRepository.findByCode(PRISON_LOCATION_CHANGE_CONTACT_TYPE).orElseThrow(); } private ContactType contactTypeForCustodyAutoUpdate() { return contactTypeRepository.findByCode(CUSTODY_AUTO_UPDATE_CONTACT_TYPE).orElseThrow(); } private String notesForPOMAllocation(final PrisonOffenderManager newPrisonOffenderManager) { return "Transfer Reason: " + newPrisonOffenderManager.getAllocationReason().getCodeDescription() + "\n" + "Transfer Date: " + newPrisonOffenderManager.getAllocationDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "\n"; } private String notesForResponsibleManager(final PrisonOffenderManager newPrisonOffenderManager, final PrisonOffenderManager existingPrisonOffenderManager) { return String.format( "New Details:\n" + "%s\n" + "Previous Details:\n" + "%s\n", notesForResponsibleManagerOf(newPrisonOffenderManager), notesForResponsibleManagerOf(existingPrisonOffenderManager)); } private String notesForResponsibleManager(final OffenderManager newOffenderManager, final PrisonOffenderManager existingPrisonOffenderManager) { return String.format( "New Details:\n" + "%s\n" + "Previous Details:\n" + "%s\n", notesForResponsibleManagerOf(newOffenderManager), notesForResponsibleManagerOf(existingPrisonOffenderManager)); } private String notesForResponsibleManager(final PrisonOffenderManager newPrisonOffenderManager, final OffenderManager existingCommunityOffenderManager) { return String.format( "New Details:\n" + "%s\n" + "Previous Details:\n" + "%s\n", notesForResponsibleManagerOf(newPrisonOffenderManager), notesForResponsibleManagerOf(existingCommunityOffenderManager)); } private String notesForResponsibleManagerOf(final PrisonOffenderManager prisonOffenderManager) { return String.format( "Responsible Officer Type: Prison Offender Manager\n" + "Responsible Officer: %s\n" + "Start Date: %s\n" + "%s" + "Allocation Reason: %s\n", responsibleOfficerOf(prisonOffenderManager), prisonOffenderManager.getLatestResponsibleOfficer().getStartDateTime().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")), Optional.ofNullable(prisonOffenderManager.getLatestResponsibleOfficer().getEndDateTime()).map(dateTime -> dateTime.format(DateTimeFormatter.ofPattern("'End Date: 'dd/MM/yyyy HH:mm:ss'\n'"))).orElse(""), prisonOffenderManager.getAllocationReason().getCodeDescription()) ; } private String notesForResponsibleManagerOf(final OffenderManager offenderManager) { return String.format( "Responsible Officer Type: Offender Manager\n" + "Responsible Officer: %s\n" + "Start Date: %s\n" + "%s" + "Allocation Reason: %s\n", responsibleOfficerOf(offenderManager), offenderManager.getLatestResponsibleOfficer().getStartDateTime().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")), Optional.ofNullable(offenderManager.getLatestResponsibleOfficer().getEndDateTime()).map(dateTime -> dateTime.format(DateTimeFormatter.ofPattern("'End Date: 'dd/MM/yyyy HH:mm:ss'\n'"))).orElse(""), offenderManager.getAllocationReason().getCodeDescription()) ; } private String responsibleOfficerOf(final PrisonOffenderManager pom) { return Optional.ofNullable(pom.getStaff()).map(staff -> String.format("%s (%s, %s)", displayNameOf(staff), pom.getTeam().getDescription(), pom.getProbationArea().getDescription())) .orElse(""); } private String responsibleOfficerOf(final OffenderManager com) { return Optional.ofNullable(com.getStaff()).map(staff -> String.format("%s (%s, %s)", displayNameOf(staff), com.getTeam().getDescription(), com.getProbationArea().getDescription())) .orElse(""); } private String appendNoteForExistingPOMAllocation(final String notes, final PrisonOffenderManager existingPrisonOffenderManager) { return notes + Optional.ofNullable(existingPrisonOffenderManager.getTeam()).map(team -> "\n" + Optional .ofNullable(existingPrisonOffenderManager.getTeam().getProbationArea()) .map(probationArea -> String.format("From Establishment Provider: %s\n", existingPrisonOffenderManager.getTeam().getProbationArea().getDescription())) .orElse("") + String.format("From Team: %s\n", existingPrisonOffenderManager.getTeam().getDescription()) + Optional .ofNullable(existingPrisonOffenderManager.getStaff()) .map(staff -> String.format("From Officer: %s\n", displayNameOf(existingPrisonOffenderManager.getStaff()))) .orElse("")).orElse(""); } private String displayNameOf(final Staff staff) { if (staff.isUnallocated()) { return "Unallocated"; } if (staff.isInActive()) { return "Inactive"; } return staff.getSurname() + ", " + staff.getForename() + " " + Optional.ofNullable(staff.getForname2()).orElse(""); } private String notesForPrisonLocationChange(final Event event) { final var custody = event.getDisposal().getCustody(); return String.format("%s%s%s-------------------------------", Optional.ofNullable(custody.getCustodialStatus()).map(status -> String.format("Custodial Status: %s\n", status.getCodeDescription())).orElse(""), Optional.ofNullable(custody.getInstitution()).map(institution -> String.format("Custodial Establishment: %s\n", institution.getDescription())).orElse(""), Optional.ofNullable(custody.getLocationChangeDate()).map(date -> String.format("Location Change Date: %s\n", date.format(DateTimeFormatter.ofPattern(DELIUS_DATE_FORMAT)))).orElse("")); } private String notesForBookingNumbUpdate(final Event event) { return String.format("Prison Number: %s\n", event.getDisposal().getCustody().getPrisonerNumber()); } private void addContactForResponsibleOfficerChange(Long offenderId, String notes, Team team, Staff staff, ProbationArea probationArea) { final var contactType = contactTypeForResponsibleOfficerChange(); contactRepository.save(builder() .contactDate(LocalDate.now()) .contactStartTime(LocalTime.now()) .offenderId(offenderId) .notes(notes) .team(team) .staff(staff) .probationArea(probationArea) .staffEmployeeId(staff.getStaffId()) .teamProviderId(team.getTeamId()) .contactType(contactType) .alertActive(contactType.getAlertFlag()) .build()); } }
54.502604
218
0.684983
372a98f6e033cea7ead5e81cbae9f6ee2fea02fa
980
package com.bugsnag; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import java.util.HashMap; import java.util.Map; import com.bugsnag.functions.*; public class ANEBugsnagContext extends FREContext { @Override public void dispose() { } @Override public Map<String, FREFunction> getFunctions() { Map<String, FREFunction> functionMap = new HashMap<String, FREFunction>(); functionMap.put("initialize", new Initialize()); functionMap.put("setContext", new SetContext()); functionMap.put("crash", new Crash()); functionMap.put("addAttribute", new AddAttribute()); functionMap.put("removeAttribute", new RemoveAttribute()); functionMap.put("removeTab", new RemoveTab()); functionMap.put("getOSVersion", new GetOSVersion()); functionMap.put("getDeviceModel", new GetDeviceModel()); functionMap.put("getDeviceId", new GetDeviceId()); functionMap.put("getDeviceManufacturer", new GetDeviceManufacturer()); return functionMap; } }
27.222222
76
0.74898
4967f27dce03b98e7bad04317023ec173a46ae34
2,850
package com.nf147.platform.shiro.realm; import com.nf147.platform.entity.GePermission; import com.nf147.platform.entity.GeUser; import com.nf147.platform.service.GeUserService; import com.nf147.platform.shiro.JWTCredentialsMatcher; import com.nf147.platform.shiro.JWTToken; import com.nf147.platform.shiro.JwtUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ByteSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import java.util.ArrayList; import java.util.List; /** * @author 陈卓悦 */ public class JWTShiroRealm extends AuthorizingRealm { private final Logger log = LoggerFactory.getLogger(JWTShiroRealm.class); @Autowired protected GeUserService geUserService; public JWTShiroRealm(){ this.setCredentialsMatcher(new JWTCredentialsMatcher()); } @Override public boolean supports(AuthenticationToken token) { return token instanceof JWTToken; } /** * 认证信息.(身份验证) : Authentication 是用来验证用户身份 * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。 * 跟controller登录一样,也是获取用户的salt值,给到shiro,由shiro来调用matcher来做认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException { JWTToken jwtToken = (JWTToken) authToken; String token = jwtToken.getToken(); GeUser user = geUserService.selectByNumber(JwtUtils.getNumber(token)); if(user == null) { throw new AuthenticationException(); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, ByteSource.Util.bytes(user.getNumber()), "jwtRealm"); return authenticationInfo; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Subject subject = SecurityUtils.getSubject(); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); GeUser u = (GeUser) subject.getPrincipal(); List<String> list = new ArrayList<>(); for (GePermission permission : u.getRole().getPermissionList()) { list.add(permission.getWildcard()); } simpleAuthorizationInfo.addStringPermissions(list); return simpleAuthorizationInfo; } }
35.625
142
0.758947
310eb5c363ab8d0af24f9979bace10f56233f41f
564
package adsen.scarpet.interpreter.parser; import adsen.scarpet.interpreter.parser.exception.ScarpetExpressionException; import adsen.scarpet.interpreter.parser.exception.ExpressionException; /** * The class which you use to add your own functions, events, variables etc. to scarpet. */ public class APIExpression { private final Expression expr; /** * @param expression expression */ public APIExpression(String expression) { this.expr = new Expression(expression); } Expression getExpr() { return expr; } }
24.521739
88
0.716312
855b2b89c09ad2ff332570e38423dbcd70c7d011
3,092
package com.github.mygreen.expression.el.tld; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * TLDファイルを読み込むクラス。 * * @since 1.5 * @author T.TSUCHIE * */ public class TldLoader { /** * TLDファイルを読み込む * @param in * @return * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public Taglib load(final InputStream in) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(in); return parseTaglib(doc.getDocumentElement()); } private Taglib parseTaglib(final Element element) { final Taglib taglib = new Taglib(); taglib.setDescription(getFirstElemenetValue(element, "description")); taglib.setDisplayName(getFirstElemenetValue(element, "display-name")); taglib.setTlibVersion(getFirstElemenetValue(element, "tlib-version")); taglib.setShortName(trimToEmpty(getFirstElemenetValue(element, "short-name"))); taglib.setUri(trimToEmpty(getFirstElemenetValue(element, "uri"))); final NodeList list = element.getElementsByTagName("function"); for(int i=0; i < list.getLength(); i++) { Function function = parseFunction((Element) list.item(i)); taglib.add(function); } return taglib; } private Function parseFunction(final Element element) { final Function function = new Function(); function.setDescription(getFirstElemenetValue(element, "description")); function.setName(trimToEmpty(getFirstElemenetValue(element, "name"))); function.setFunctionClass(trimToEmpty(getFirstElemenetValue(element, "function-class"))); function.setFunctionSignature(trimToEmpty(getFirstElemenetValue(element, "function-signature"))); return function; } /** * 指定したタグの値を取得する。 * 一致するタグが複数存在する場合は、初めの要素の値を返す。 * @param parent 親の要素 * @param tagName タグ名 * @return 指定したタグを持たない場合は、nullを返す。 */ private String getFirstElemenetValue(final Element parent, final String tagName) { final NodeList list = parent.getElementsByTagName(tagName); if(list.getLength() == 0) { return null; } Element element = (Element) list.item(0); return element.getTextContent(); } /** * 文字列をトリムする。 * ただし、値がnullの場合、空文字を返す。 * @param str * @return */ private String trimToEmpty(final String str) { return str == null ? "" : str.trim(); } }
30.019417
109
0.648448
d94c712f97c2e7339698e1c70f2ed1df3d34828e
684
package edu.stanford.protege.webprotege.forms.field; public interface FormControlDescriptorDtoVisitor<R> { R visit(TextControlDescriptorDto textControlDescriptorDto); R visit(SingleChoiceControlDescriptorDto singleChoiceControlDescriptorDto); R visit(MultiChoiceControlDescriptorDto multiChoiceControlDescriptorDto); R visit(NumberControlDescriptorDto numberControlDescriptorDto); R visit(ImageControlDescriptorDto imageControlDescriptorDto); R visit(GridControlDescriptorDto gridControlDescriptorDto); R visit(SubFormControlDescriptorDto subFormControlDescriptorDto); R visit(EntityNameControlDescriptorDto entityNameControlDescriptorDto); }
32.571429
79
0.845029
b14589904530a587bf783f3064e87b95982ef348
1,626
package ru.mail.jira.plugins.groovy.impl.jql.function.builtin.expression; import com.atlassian.jira.issue.index.DocumentConstants; import com.atlassian.jira.issue.statistics.util.FieldDocumentHitCollector; import groovy.lang.Script; import lombok.Getter; import org.apache.lucene.document.Document; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ExpressionIssueIdCollector extends FieldDocumentHitCollector { @Getter private final Set<String> issueIds = new HashSet<>(); private final Map<String, LuceneFieldValueExtractor> extractorMap; private final Set<String> indexFieldsToLoad; private final Script script; public ExpressionIssueIdCollector(Set<String> fieldsToLoad, Script script, Map<String, LuceneFieldValueExtractor> extractorMap) { this.indexFieldsToLoad = fieldsToLoad; this.script = script; this.extractorMap = extractorMap; } @Override protected Set<String> getFieldsToLoad() { return this.indexFieldsToLoad; } @Override public void collect(Document document) { // add all document field values as properties extractorMap.keySet().forEach(indexFieldName -> { LuceneFieldValueExtractor extractor = extractorMap.get(indexFieldName); if (extractor != null) script.setProperty(indexFieldName, extractor.extract(document)); }); Object result = script.run(); if (result.equals(Boolean.TRUE)) issueIds.add(document.getField(DocumentConstants.ISSUE_ID).stringValue()); } }
34.595745
133
0.726322
193f7d073cd813c8b2c5d78d20ec2e9f7c551391
1,028
/******************************************************************************* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013,2014 by Peter Pilgrim, Addiscombe, Surrey, XeNoNiQUe UK * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU GPL v3.0 * which accompanies this distribution, and is available at: * http://www.gnu.org/licenses/gpl-3.0.txt * * Developers: * Peter Pilgrim -- design, development and implementation * -- Blog: http://www.xenonique.co.uk/blog/ * -- Twitter: @peter_pilgrim * * Contributors: * *******************************************************************************/ package je7hb; import javax.persistence.EntityManager; /** * The type Utils * * @author Peter Pilgrim */ public class Utils { private Utils() {} public static void clearEntityManager(EntityManager em) { if (em != null ) { em.clear(); } } }
27.052632
81
0.549611
c4bf2e194f684b64d7a553fa24252e42b027e60f
267
package org.smartcolors.marshal; import com.google.common.hash.HashCode; /** * Created by devrandom on 2014-Nov-19. */ public interface SerializerHelper<T> { void serialize(Serializer ser, T obj) throws SerializationException; HashCode getHash(T obj); }
20.538462
72
0.745318
53c2cf3e8d017516fee53b3e53422e5899e39d6d
2,451
package com.seven.dust.controllers; import com.google.gson.Gson; import com.seven.dust.responses.RestRep; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class ApiController { protected HttpServletRequest req; protected HttpServletResponse rep; public void setReq(HttpServletRequest req) { this.req = req; } public void setRep(HttpServletResponse rep) { this.rep = rep; } public void initRequest(HttpServletRequest req, HttpServletResponse rep) { this.setReq(req); this.setRep(rep); } /** * 操作成功返回json格式 * @param message * @throws IOException */ public <T> void success(String message) { RestRep<T> data = this.<T>setData(2000, message); this.<T>sendData(data); return; } public <T> void success(String message, T data){ RestRep<T> one = this.setData(2000, message, data); this.<T>sendData(one); } public <T> void success(T data) { RestRep<T> one = this.setData(2000, "请求成功", data); this.<T> sendData(one); } /** * 400呀 */ public void youFucked() { this.rep.setStatus(400); } /** * 404呀 not find */ public void notFind() { this.rep.setStatus(404); } /** * 500 呀 */ public void iFucked() { this.rep.setStatus(500); } private <T> RestRep<T> setData(int code, String message) { RestRep<T> rep = new RestRep<>(code, message, null); return rep; } private <T> RestRep<T> setData(int code, String message, T data){ RestRep<T> rep = new RestRep<>(code, message, data); return rep; } private <T> void sendData(RestRep<T> data){ Gson gson = new Gson(); String json = gson.toJson(data); this.rep.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器 this.rep.setContentType("application/json;charset=UTF-8"); PrintWriter out; try { out = this.rep.getWriter(); out.write(json); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); this.iFucked(); return; } } }
26.641304
79
0.558956
59803fe8b57ef362a0df400abc6aed4b51a4b4eb
335
package de.jformchecker.utils; @SuppressWarnings("serial") public class DoubleLabelException extends RuntimeException{ public DoubleLabelException(String elementName) { super("You defined two Labels (Label AND LabelTranslationKey) on one element: '" + elementName + "' \nUse either @Label OR @LabelTranslationKey. Not both"); } }
37.222222
158
0.78209
e0475980e45a2725515aa66135b819a83b51288c
45,502
package org.firstinspires.ftc.teamcode; import static org.firstinspires.ftc.robotcore.external.navigation.AngleUnit.DEGREES; import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.XYZ; import static org.firstinspires.ftc.robotcore.external.navigation.AxesReference.EXTRINSIC; import android.graphics.Color; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.DistanceSensor; import com.qualcomm.robotcore.hardware.NormalizedColorSensor; import com.qualcomm.robotcore.hardware.NormalizedRGBA; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.SwitchableLight; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix; import org.firstinspires.ftc.robotcore.external.navigation.Acceleration; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvPipeline; import java.util.Locale; @Autonomous(name = "Redside") public class RedsideStay extends LinearOpMode { // Declaring Motors & Servos private DcMotorEx leftFront; //port 0 private DcMotorEx rightFront; //port 1 private DcMotorEx leftBack; //port 1 private DcMotorEx rightBack; //port 3 private DcMotorEx spinner; private DcMotorEx arm; private Servo wrist; //port 0 private Servo fingers; //port 0 //Webcam Back private WebcamName Webcam2; //Declaring Distance Sensor Variables private DistanceSensor leftDistance; private DistanceSensor rightDistance; //Declaring Color Sensor Variables NormalizedColorSensor lfColorSensor; NormalizedColorSensor rfColorSensor; NormalizedRGBA colors; NormalizedRGBA colors2; boolean foundRed = false; boolean foundWhite = false; //Declaring IMU Variables BNO055IMU imu; Orientation angles; Acceleration gravity; double cumulativeHeading; boolean turned = false; //Declaring Camera Variables OpenCvCamera webcam; OpenCVTest.SamplePipeline pipeline; private static final String VUFORIA_KEY = "ARxaOAX/////AAABmR91q9ci+kNYqGb/NElhuhBQa5klidYZ5jKk5hFYJ6qAQOtCGKSEZXn1qYawipXKEEpJh+vP3GNnOUvabO2blz4vkymDnu8LUocLc6/rMpQdLwBt80JVdgWWkd/4j1DmwDdRRP4f/jP78furjgexjT7HgmC37xLP+msr78zAeWwkrsT2X1yjnL6nyiGcRKlBw6+EcUIcZYiiuXwbILds8rl4Fu7AuecLaygDft6XIUFg/qQm51UF45l5pYT8AoNTUhP9GTksKkmHgde7iGlo3CfIYu9QanjPHreT/+JZLJWG22jWC7Nnzch/1HC6s3s2jzkrFV6sRVA4lL9COLIonjRBYPhbxCF06c5fUMy9sj/e"; private static final float mmPerInch = 25.4f; private static final float mmTargetHeight = 6 * mmPerInch; // the height of the center of the target image above the floor private static final float halfField = 72 * mmPerInch; private static final float halfTile = 12 * mmPerInch; private static final float oneAndHalfTile = 36 * mmPerInch; // Class Members private OpenGLMatrix lastLocation = null; private VuforiaLocalizer vuforia = null; private VuforiaTrackables targets = null; private WebcamName webcamName = null; private boolean targetVisible = false; //int cameraMonitorViewId2 = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); //VuforiaLocalizer.Parameters parameters2 = new VuforiaLocalizer.Parameters(cameraMonitorViewId2); final float CAMERA_FORWARD_DISPLACEMENT = 0.0f * mmPerInch; // eg: Enter the forward distance from the center of the robot to the camera lens final float CAMERA_VERTICAL_DISPLACEMENT = 6.0f * mmPerInch; // eg: Camera is 6 Inches above ground final float CAMERA_LEFT_DISPLACEMENT = 0.0f * mmPerInch; // eg: Enter the left distance from the center of the robot to the camera lens //OpenGLMatrix cameraLocationOnRobot = OpenGLMatrix // .translation(CAMERA_FORWARD_DISPLACEMENT, CAMERA_LEFT_DISPLACEMENT, CAMERA_VERTICAL_DISPLACEMENT) // .multiplied(Orientation.getRotationMatrix(EXTRINSIC, XZY, DEGREES, 90, 90, 0)); @Override public void runOpMode() { initialize(); while (opModeIsActive()) { encoders("off"); if (pipeline.getType1().toString().equals("REDSQUARE") || pipeline.getType2().toString().equals("REDSQUARE") || pipeline.getType3().toString().equals("REDSQUARE")) { //On Blue Side if (true) { //Distance Sensor on Right < x //On Carousel Side if (pipeline.getType1().toString().equals("DUCK")) { //Duck in Field 1 telemetry.addData("Duck: ", "Field 1"); telemetry.addData("Robot: ", "Blue Carousel"); duckyData(); //fingers face forward, wrist opens, arm on bottom level fingers.setPosition(0.1); wrist.setPosition(0.25); arm(21); //start moving moveInches(36,16); turn(0.35,-80,"right",0.35); //moveInches(4,16); //drop off block sleep(500); fingers.setPosition(0.4); //to wall moveInches(-26,16); //to ducky turn(0.35,-20,"left",0.5); moveInches(-30,16); //deliver ducky spinner(47.1238898038,10); //fold in arm fingers.setPosition(0.1); wrist.setPosition(0.9); //nap time sleep(30000); } else if (pipeline.getType2().toString().equals("DUCK")) { //Duck in Field 2 telemetry.addData("Duck: ", "Field 2"); telemetry.addData("Robot: ", "Blue Carousel"); duckyData(); //fingers face forward, wrist opens, arm on bottom level fingers.setPosition(0.1); wrist.setPosition(0.3); arm(26.5); //start moving moveInches(10,16); turn(0.35,-30,"right",0.5); moveInches(18,16); //drop off block sleep(500); fingers.setPosition(0.3); //to wall moveInches(-18,16); //to ducky turn(0.35,-55,"right",0.5); moveInches(-26.5,16); //deliver ducky spinner(47.1238898038,10); //fold in arm fingers.setPosition(0.1); wrist.setPosition(0.9); //nap time sleep(30000); } else if (pipeline.getType3().toString().equals("DUCK")) { //Duck in Field 3 telemetry.addData("Duck: ", "Field 3"); telemetry.addData("Robot: ", "Blue Carousel"); duckyData(); //fingers face forward, wrist opens, arm on bottom level fingers.setPosition(0.1); wrist.setPosition(0.3); arm(29.5); //start moving moveInches(10,16); turn(0.35,-30,"right",0.5); moveInches(18,16); //drop off block sleep(500); fingers.setPosition(0.3); //to wall moveInches(-16,16); //to ducky turn(0.35,-55,"right",0.5); moveInches(-26,16); moveInches(-2,8); //deliver ducky spinner(47.1238898038,10); //fold in arm fingers.setPosition(0.1); wrist.setPosition(0.9); //nap time sleep(30000); } } else if (false) { //Distance Sensor on Right > x //On Storage Side if (pipeline.getType1().toString().equals("DUCK")) { //Duck in Field 1 } else if (pipeline.getType2().toString().equals("DUCK")) { //Duck in Field 2 } else if (pipeline.getType3().toString().equals("DUCK")) { //Duck in Field 3 } } } else if (pipeline.getType1().toString().equals("BLUESQUARE") || pipeline.getType2().toString().equals("BLUESQUARE") || pipeline.getType3().toString().equals("BLUESQUARE")) { //On Red Side if (true) { //Distance Sensor on Left < x //On Carousel Side if (pipeline.getType1().toString().equals("DUCK")) { //Duck in Field 1 telemetry.addData("Duck: ", "Field 1"); telemetry.addData("Robot: ", "Red Carousel"); duckyData(); fingers.setPosition(0.1); wrist.setPosition(0.1); arm(3.5); moveInches(10,16); turn(-0.35,-45,"right",0.33); moveInches(22,16); fingers.setPosition(0.3); } else if (pipeline.getType2().toString().equals("DUCK")) { //Duck in Field 2 telemetry.addData("Duck: ", "Field 2"); telemetry.addData("Robot: ", "Red Carousel"); duckyData(); fingers.setPosition(0.1); wrist.setPosition(0.1); arm(9); //moveInches(10,16); turn(-0.35,-45,"right",0.33); moveInches(28,16); fingers.setPosition(0.3); } else if (pipeline.getType3().toString().equals("DUCK")) { //Duck in Field 3 telemetry.addData("Duck: ", "Field 3"); telemetry.addData("Robot: ", "Red Carousel"); duckyData(); fingers.setPosition(0.1); wrist.setPosition(0.1); arm(3.5); moveInches(18,16); turn(-0.35,-80,"right",0.33); moveInches(15,16); wrist.setPosition(0.6); sleep(500); fingers.setPosition(0.3); } } else if (false) { //Distance Sensor on Left > x //On Storage Side if (pipeline.getType1().toString().equals("DUCK")) { //Duck in Field 1 } else if (pipeline.getType2().toString().equals("DUCK")) { //Duck in Field 2 } else if (pipeline.getType3().toString().equals("DUCK")) { //Duck in Field 3 } } } } } public void duckyData() { telemetry.addLine(); telemetry.addLine(); telemetry.addData("Field 1", pipeline.getType1()); telemetry.addData("AverageY", pipeline.getAverageY()); telemetry.addData("AverageCr", pipeline.getAverageCr()); telemetry.addData("AverageCb", pipeline.getAverageCb()); telemetry.addLine(); telemetry.addData("Field 2", pipeline.getType2()); telemetry.addData("AverageY", pipeline.getAverageY2()); telemetry.addData("AverageCr", pipeline.getAverageCr2()); telemetry.addData("AverageCb", pipeline.getAverageCb2()); telemetry.addLine(); telemetry.addData("Field 3", pipeline.getType3()); telemetry.addData("AverageY", pipeline.getAverageY3()); telemetry.addData("AverageCr", pipeline.getAverageCr3()); telemetry.addData("AverageCb", pipeline.getAverageCb3()); telemetry.update(); } String formatAngle(AngleUnit angleUnit, double angle) { return formatDegrees(AngleUnit.DEGREES.fromUnit(angleUnit, angle)); } String formatDegrees(double degrees){ return String.format(Locale.getDefault(), "%.1f", AngleUnit.DEGREES.normalize(degrees)); } //Method to Completely Stop ALL Robot Movement Excluding Servos private void forceStop() { leftFront.setPower(0); rightFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0); spinner.setPower(0); arm.setPower(0); } //Method to Move Robot @ Designated Speed & Duration public void move(double speed, long dur) { leftFront.setPower(speed); rightFront.setPower(speed); leftBack.setPower(speed); rightBack.setPower(speed); sleep(dur); } double getBlueRedRatio(double ratio){ return ratio; } double getBlueRedRatio2(double ratio2){ return ratio2; } //Method to Find & Move to a White, Red, or Blue Line void senseLine(String color, double speed, String side) { final float[] hsvValues = new float[3]; final float[] hsvValues2 = new float[3]; angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); double initialHeading = Double.parseDouble(formatAngle(angles.angleUnit, angles.firstAngle)); foundRed = false; foundWhite = false; int countRed = 0; int countWhite = 0; boolean shouldBreak = false; //If the "foundRed" Boolean is False, Run Loop while ((!shouldBreak) && opModeIsActive()) { angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); //Needed (updating) Variables NormalizedRGBA colors = lfColorSensor.getNormalizedColors(); NormalizedRGBA colors2 = rfColorSensor.getNormalizedColors(); Color.colorToHSV(colors.toColor(), hsvValues); Color.colorToHSV(colors2.toColor(), hsvValues2); double heading = Double.parseDouble(formatAngle(angles.angleUnit, angles.firstAngle)) - initialHeading; double P = Math.abs(0.025 * heading); //If-Else-If Statement to Drive Forward or Backwards in a Straight Line if (heading < -0.1 && heading > -90) { leftFront.setPower(speed - P); leftBack.setPower(speed - P); rightFront.setPower(speed + P); rightBack.setPower(speed + P); } else if (heading > 0.1 && heading < 90) { leftFront.setPower(speed + P); leftBack.setPower(speed + P); rightFront.setPower(speed - P); rightBack.setPower(speed - P); } else { leftFront.setPower(speed); leftBack.setPower(speed); rightFront.setPower(speed); rightBack.setPower(speed); } double BlueRedRatio = colors.blue / colors.red; double BlueRedRatio2 = colors2.blue / colors2.red; if (side.equals("left")) { if ((BlueRedRatio < 0.83 || BlueRedRatio > 2.032)) { telemetry.addLine("lfColorSensor says:"); if (BlueRedRatio <= 0.83 && (color.equals("red") || color.equals("Red"))) { telemetry.addLine("Red Line Has Been Found! :)"); shouldBreak = true; } else if ((BlueRedRatio >= 2.032) && (color.equals("blue") || color.equals("Blue"))) { telemetry.addLine("Blue Line Has Been Found! :)"); shouldBreak = true; } } else if ((colors.green * 1000 >= 9.041) && (color.equals("white") || color.equals("White"))) { telemetry.addLine("lfColorSensor says:"); telemetry.addLine("White Line Has Been Found! :)"); shouldBreak = true; } else{ telemetry.addLine("lfColorSensor says:"); telemetry.addLine("Just Gray Tile :("); } telemetry.addLine(); } else if (side.equals("right")) { if (BlueRedRatio2 < 0.83 || BlueRedRatio2 > 2.032) { telemetry.addLine("rfColorSensor says:"); if (BlueRedRatio2 <= 0.83 && (color.equals("red") || color.equals("red"))) { telemetry.addLine("Red Line Has Been Found! :)"); shouldBreak = true; } else if (BlueRedRatio2 >= 2.032 && (color.equals("blue") || color.equals("Blue"))) { telemetry.addLine("Blue Line Has Been Found! :)"); shouldBreak = true; } } else if (colors2.green * 1000 >= 9.041 && (color.equals("white") || color.equals("White"))) { telemetry.addLine("rfColorSensor says:"); telemetry.addLine("White Line Has Been Found! :)"); shouldBreak = true; } else{ telemetry.addLine("rfColorSensor says:"); telemetry.addLine("Just Gray Tile :("); } } telemetry.addLine(); telemetry.addLine(); telemetry.addLine("lfColorSensor: "); telemetry.addLine() .addData("Red", "%.3f", colors.red * 1000) .addData("Green", "%.3f", colors.green * 1000) .addData("Blue", "%.3f", colors.blue * 1000); telemetry.addData("Blue/Red Ratio: ", Math.floor(getBlueRedRatio(BlueRedRatio)*1000)/1000); telemetry.addLine(); telemetry.addLine("rfColorSensor: "); telemetry.addLine() .addData("Red", "%.3f", colors2.red * 1000) .addData("Green", "%.3f", colors2.green * 1000) .addData("Blue", "%.3f", colors2.blue * 1000); telemetry.addData("Blue/Red Ratio: ", Math.floor(getBlueRedRatio2(BlueRedRatio2) * 1000)/1000); telemetry.addLine(); //Telemetry Info for Diagnostics telemetry.addLine() .addData("Heading Output", "%.3f", heading) .addData("Loop Count", countRed); telemetry.update(); } rightFront.setPower(0); leftFront.setPower(0); rightBack.setPower(0); leftBack.setPower(0); } //Method to Turn Robot Using IMU void turn(double speed, double angleMeasure, String direction, double tolerance) { double startHeading = Double.parseDouble(formatAngle(angles.angleUnit, angles.firstAngle)); boolean turnLeft; boolean turnRight; if (direction.equals("left")||direction.equals("Left")) { turnLeft = true; turnRight = false; } else { turnLeft = false; turnRight = true; } turned = false; while (opModeIsActive() && !turned) { angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); startHeading = Double.parseDouble(formatAngle(angles.angleUnit, angles.firstAngle)); telemetry.addData("approaching", angleMeasure); telemetry.addData("heading", startHeading); telemetry.update(); if (turnLeft) { //turn left if ((angleMeasure - startHeading) >= 0) { if ((startHeading <= (angleMeasure + tolerance)) && (startHeading >= (angleMeasure - tolerance))) { forceStop(); turned = true; } else if (startHeading >= (0.9 * angleMeasure) && startHeading < (angleMeasure - tolerance)) { rightFront.setPower(0.5 * speed); leftFront.setPower(0.5 * -speed); rightBack.setPower(0.5 * speed); leftBack.setPower(0.5 * -speed); } else { rightFront.setPower(speed); leftFront.setPower(-speed); rightBack.setPower(speed); leftBack.setPower(-speed); } } else { if ((startHeading <= (angleMeasure + tolerance)) && (startHeading >= (angleMeasure - tolerance))) { forceStop(); turned = true; } else if (startHeading >= (0.9 * angleMeasure) && startHeading > (angleMeasure - tolerance)) { rightFront.setPower(0.5 * speed); leftFront.setPower(0.5 * -speed); rightBack.setPower(0.5 * speed); leftBack.setPower(0.5 * -speed); } else { rightFront.setPower(speed); leftFront.setPower(-speed); rightBack.setPower(speed); leftBack.setPower(-speed); } } } else if (turnRight) { //turn right if ((angleMeasure - startHeading) >= 0) { if ((startHeading <= (angleMeasure + tolerance)) && (startHeading >= (angleMeasure - tolerance))) { forceStop(); turned = true; } else if (startHeading >= (0.9 * angleMeasure) && startHeading < (angleMeasure - tolerance)) { rightFront.setPower(0.5 * -speed); leftFront.setPower(0.5 * speed); rightBack.setPower(0.5 * -speed); leftBack.setPower(0.5 * speed); } else { rightFront.setPower(-speed); leftFront.setPower(speed); rightBack.setPower(-speed); leftBack.setPower(speed); } } else { if (startHeading <= angleMeasure + tolerance && startHeading >= angleMeasure - tolerance) { forceStop(); turned = true; } else if (startHeading >= (0.9 * angleMeasure) && startHeading < (angleMeasure - tolerance)) { rightFront.setPower(0.5 * -speed); leftFront.setPower(0.5 * speed); rightBack.setPower(0.5 * -speed); leftBack.setPower(0.5 * speed); } else { rightFront.setPower(-speed); leftFront.setPower(speed); rightBack.setPower(-speed); leftBack.setPower(speed); } } } } } //Determine Whether To Run With Encoder public void encoders(String status) { if (status.equals("on")) { leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); spinner.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); arm.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); spinner.setMode(DcMotor.RunMode.RUN_USING_ENCODER); arm.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } else if (status.equals("off")) { leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); spinner.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); arm.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); leftBack.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); spinner.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); arm.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } } void spinner (double distance, double velocity) { encoders("on"); double calcRotation = -distance * 122.073; int setRotation = (int) Math.round(calcRotation); double calcVel = velocity * 122.073; int setVel =(int) Math.round(calcVel); spinner.setTargetPosition(setRotation); spinner.setMode(DcMotor.RunMode.RUN_TO_POSITION); spinner.setVelocity(setVel); while (opModeIsActive() && spinner.isBusy()) { telemetry.addData("position", spinner.getCurrentPosition()); telemetry.update(); } spinner.setVelocity(0); encoders("off"); } void arm (double distance) { encoders("on"); double calcUp = -66.9174 + (75.7517 * distance) + (17.8479 * distance * distance) + (-1.75956 * distance * distance * distance) + (0.0462714 * distance * distance * distance * distance);// (100 * (distance + 0.76442)) / 1.00529; int setUp = (int) Math.round(calcUp); double calcInc = (1000) ; int setInc =(int) Math.round(calcInc); if (distance < 0){ setInc = (int) -Math.round(calcInc); } arm.setTargetPosition(setUp); arm.setMode(DcMotor.RunMode.RUN_TO_POSITION); arm.setVelocity(setInc); while (opModeIsActive() && arm.isBusy()) { telemetry.addData("position", arm.getCurrentPosition()); telemetry.update(); } arm.setVelocity(0); encoders("off"); } //Method to Move Robot Using Encoders void moveInches(double distance, double velocity) { encoders("on"); double calcPosition = distance * 100.531; int setPosition = (int) Math.round(calcPosition); double calcVelocity = velocity * 100.531; int setVelocity = (int) Math.round(calcVelocity); leftFront.setTargetPosition(setPosition); rightFront.setTargetPosition(setPosition); leftBack.setTargetPosition(setPosition); rightBack.setTargetPosition(setPosition); leftFront.setMode(DcMotor.RunMode.RUN_TO_POSITION); rightFront.setMode(DcMotor.RunMode.RUN_TO_POSITION); leftBack.setMode(DcMotor.RunMode.RUN_TO_POSITION); rightBack.setMode(DcMotor.RunMode.RUN_TO_POSITION); leftFront.setVelocity(setVelocity); rightFront.setVelocity(setVelocity); leftBack.setVelocity(setVelocity); rightBack.setVelocity(setVelocity); while (opModeIsActive() && leftFront.isBusy() && rightFront.isBusy() ) { telemetry.addData("position", leftFront.getCurrentPosition()); telemetry.addData("position", rightFront.getCurrentPosition()); telemetry.addData("position", leftBack.getCurrentPosition()); telemetry.addData("position", rightBack.getCurrentPosition()); telemetry.addData("is at target", !leftFront.isBusy()); telemetry.update(); } leftFront.setVelocity(0); rightFront.setVelocity(0); leftBack.setVelocity(0); rightBack.setVelocity(0); encoders("off"); } public static class SamplePipeline extends OpenCvPipeline { private static final Scalar BLUE = new Scalar(0, 0, 255); Point topLeft = new Point(0, 160); Point bottomRight = new Point(50, 210); Point topLeft2 = new Point(130, 150); Point bottomRight2 = new Point(180, 200); Point topLeft3 = new Point(265, 140); Point bottomRight3 = new Point(315, 190); Mat region1_Y; Mat region1_Cr; Mat region1_Cb; Mat region2_Y; Mat region2_Cr; Mat region2_Cb; Mat region3_Y; Mat region3_Cr; Mat region3_Cb; Mat YCrCb = new Mat(); Mat Y = new Mat(); Mat Cr = new Mat(); Mat Cb = new Mat(); private volatile int averageY; private volatile int averageCr; private volatile int averageCb; private volatile int averageY2; private volatile int averageCr2; private volatile int averageCb2; private volatile int averageY3; private volatile int averageCr3; private volatile int averageCb3; private volatile OpenCVTest.SamplePipeline.TYPE type1 = OpenCVTest.SamplePipeline.TYPE.NULL; private volatile OpenCVTest.SamplePipeline.TYPE type2 = OpenCVTest.SamplePipeline.TYPE.NULL; private volatile OpenCVTest.SamplePipeline.TYPE type3 = OpenCVTest.SamplePipeline.TYPE.NULL; private void inputToY(Mat input) { Imgproc.cvtColor(input, YCrCb, Imgproc.COLOR_RGB2YCrCb); Core.extractChannel(YCrCb, Y, 0); } private void inputToCr(Mat input) { Imgproc.cvtColor(input, YCrCb, Imgproc.COLOR_RGB2YCrCb); Core.extractChannel(YCrCb, Cr, 1); } private void inputToCb(Mat input) { Imgproc.cvtColor(input, YCrCb, Imgproc.COLOR_RGB2YCrCb); Core.extractChannel(YCrCb, Cb, 2); } @Override public void init(Mat input) { inputToY(input); inputToCr(input); inputToCb(input); region1_Y = Y.submat(new Rect(topLeft, bottomRight)); region1_Cr = Cr.submat(new Rect(topLeft, bottomRight)); region1_Cb = Cb.submat(new Rect(topLeft, bottomRight)); region2_Y = Y.submat(new Rect(topLeft2, bottomRight2)); region2_Cr = Cr.submat(new Rect(topLeft2, bottomRight2)); region2_Cb = Cb.submat(new Rect(topLeft2, bottomRight2)); region3_Y = Y.submat(new Rect(topLeft3, bottomRight3)); region3_Cr = Cr.submat(new Rect(topLeft3, bottomRight3)); region3_Cb = Cb.submat(new Rect(topLeft3, bottomRight3)); } @Override public Mat processFrame(Mat input) { inputToY(input); inputToCr(input); inputToCb(input); averageY = (int) Core.mean(region1_Y).val[0]; averageCr = (int) Core.mean(region1_Cr).val[0]; averageCb = (int) Core.mean(region1_Cb).val[0]; averageY2 = (int) Core.mean(region2_Y).val[0]; averageCr2 = (int) Core.mean(region2_Cr).val[0]; averageCb2 = (int) Core.mean(region2_Cb).val[0]; averageY3 = (int) Core.mean(region3_Y).val[0]; averageCr3 = (int) Core.mean(region3_Cr).val[0]; averageCb3 = (int) Core.mean(region3_Cb).val[0]; Imgproc.rectangle(input, topLeft, bottomRight, BLUE, 2); Imgproc.rectangle(input, topLeft2, bottomRight2, BLUE, 2); Imgproc.rectangle(input, topLeft3, bottomRight3, BLUE, 2); if (((double)getAverageCb())/(double)getAverageCr() < 0.9547) { type1 = OpenCVTest.SamplePipeline.TYPE.REDSQUARE; } else if (((double)getAverageCb())/(double)getAverageCr() < 1.1234) { type1 = OpenCVTest.SamplePipeline.TYPE.DUCK; } else if (((double)getAverageCb())/(double)getAverageCr() < 150) { type1 = OpenCVTest.SamplePipeline.TYPE.BLUESQUARE; } else { type1 = OpenCVTest.SamplePipeline.TYPE.NULL; } if (((double)getAverageCb2())/(double)getAverageCr2() < 0.9547) { type2 = OpenCVTest.SamplePipeline.TYPE.REDSQUARE; } else if (((double)getAverageCb2())/(double)getAverageCr2() < 1.1234) { type2 = OpenCVTest.SamplePipeline.TYPE.DUCK; } else if ((((double)getAverageCb2())/(double)getAverageCr2()) < 150) { type2 = OpenCVTest.SamplePipeline.TYPE.BLUESQUARE; } else { type2 = OpenCVTest.SamplePipeline.TYPE.NULL; } if ((((double)getAverageCb3())/(double)getAverageCr3()) < 0.9547) { type3 = OpenCVTest.SamplePipeline.TYPE.REDSQUARE; } else if ((((double)getAverageCb3())/(double)getAverageCr3()) <1.1234) { type3 = OpenCVTest.SamplePipeline.TYPE.DUCK; } else if ((((double)getAverageCb3())/(double)getAverageCr3()) < 150) { type3 = OpenCVTest.SamplePipeline.TYPE.BLUESQUARE; } else { type3 = OpenCVTest.SamplePipeline.TYPE.NULL; } return input; } public OpenCVTest.SamplePipeline.TYPE getType1() { return type1; } public OpenCVTest.SamplePipeline.TYPE getType2() { return type2; } public OpenCVTest.SamplePipeline.TYPE getType3() { return type3; } public int getAverageY() { return averageY; } public int getAverageCr() { return averageCr; } public int getAverageCb() { return averageCb; } public int getAverageY2() { return averageY2; } public int getAverageCr2() { return averageCr2; } public int getAverageCb2() { return averageCb2; } public int getAverageY3() { return averageY3; } public int getAverageCr3() { return averageCr3; } public int getAverageCb3() { return averageCb3; } public enum TYPE { BALL, BLUESQUARE, CUBE, DUCK, NULL, REDSQUARE } } void identifyTarget(int targetIndex, String targetName, float dx, float dy, float dz, float rx, float ry, float rz) { VuforiaTrackable aTarget = targets.get(targetIndex); aTarget.setName(targetName); aTarget.setLocation(OpenGLMatrix.translation(dx, dy, dz) .multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, rx, ry, rz))); } public void initialize() { telemetry.addData("Stat", "Initializing..."); telemetry.update(); //Mapping Motors rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightBack = hardwareMap.get(DcMotorEx.class, "rightBack"); leftBack = hardwareMap.get(DcMotorEx.class, "leftBack"); spinner = hardwareMap.get(DcMotorEx.class, "spinner"); arm = hardwareMap.get(DcMotorEx.class, "arm"); //webcamName = hardwareMap.get(WebcamName.class, "Webcam 2"); //Mapping Servos wrist = hardwareMap.servo.get("wrist"); fingers = hardwareMap.servo.get("fingers"); // Extra Motor Steps leftFront.setDirection(DcMotorSimple.Direction.REVERSE); //Reverse leftBack.setDirection(DcMotorSimple.Direction.REVERSE); //Reverse //Mapping Distance Sensors leftDistance = hardwareMap.get(DistanceSensor.class, "leftDistance"); rightDistance = hardwareMap.get(DistanceSensor.class, "rightDistance"); //Mapping Color Sensors lfColorSensor = hardwareMap.get(NormalizedColorSensor.class, "lfColorSensor"); if (lfColorSensor instanceof SwitchableLight) { ((SwitchableLight) lfColorSensor).enableLight(true); } rfColorSensor = hardwareMap.get(NormalizedColorSensor.class, "rfColorSensor"); if (rfColorSensor instanceof SwitchableLight) { ((SwitchableLight) rfColorSensor).enableLight(true); } //IMU Mapping and Set-Up BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); //Initialize Camera int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); webcam = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); //OpenCv Set-Up pipeline = new OpenCVTest.SamplePipeline(); webcam.setPipeline(pipeline); webcam.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { webcam.startStreaming(320, 240, OpenCvCameraRotation.UPRIGHT); } @Override public void onError(int errorCode) { } }); // Connect to the camera we are to use. This name must match what is set up in Robot Configuration //webcamName = hardwareMap.get(WebcamName.class, "Webcam 2"); /* * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine. * We can pass Vuforia the handle to a camera preview resource (on the RC screen); * If no camera-preview is desired, use the parameter-less constructor instead (commented out below). * Note: A preview window is required if you want to view the camera stream on the Driver Station Phone. */ // VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); // parameters2.vuforiaLicenseKey = VUFORIA_KEY; // We also indicate which camera we wish to use. // parameters2.cameraName = webcamName; // Turn off Extended tracking. Set this true if you want Vuforia to track beyond the target. // parameters2.useExtendedTracking = false; // Instantiate the Vuforia engine // vuforia = ClassFactory.getInstance().createVuforia(parameters2); // Load the data sets for the trackable objects. These particular data // sets are stored in the 'assets' part of our application. //targets = this.vuforia.loadTrackablesFromAsset("FreightFrenzy"); /** * In order for localization to work, we need to tell the system where each target is on the field, and * where the phone resides on the robot. These specifications are in the form of <em>transformation matrices.</em> * Transformation matrices are a central, important concept in the math here involved in localization. * See <a href="https://en.wikipedia.org/wiki/Transformation_matrix">Transformation Matrix</a> * for detailed information. Commonly, you'll encounter transformation matrices as instances * * If you are standing in the Red Alliance Station looking towards the center of the field, * - The X axis runs from your left to the right. (positive from the center to the right) * - The Y axis runs from the Red Alliance Station towards the other side of the field * where the Blue Alliance Station is. (Positive is from the center, towards the BlueAlliance station) * - The Z axis runs from the floor, upwards towards the ceiling. (Positive is above the floor) * * Before being transformed, each target image is conceptually located at the origin of the field's * coordinate system (the center of the field), facing up. */ // Name and locate each trackable object //identifyTarget(0, "Blue Storage", -halfField, oneAndHalfTile, mmTargetHeight, 90, 0, 90); //identifyTarget(1, "Blue Alliance Wall", halfTile, halfField, mmTargetHeight, 90, 0, 0); //identifyTarget(2, "Red Storage", -halfField, -oneAndHalfTile, mmTargetHeight, 90, 0, 90); //identifyTarget(3, "Red Alliance Wall", halfTile, -halfField, mmTargetHeight, 90, 0, 180); /* * Create a transformation matrix describing where the camera is on the robot. * * Info: The coordinate frame for the robot looks the same as the field. * The robot's "forward" direction is facing out along X axis, with the LEFT side facing out along the Y axis. * Z is UP on the robot. This equates to a bearing angle of Zero degrees. * * For a WebCam, the default starting orientation of the camera is looking UP (pointing in the Z direction), * with the wide (horizontal) axis of the camera aligned with the X axis, and * the Narrow (vertical) axis of the camera aligned with the Y axis * * But, this example assumes that the camera is actually facing forward out the front of the robot. * So, the "default" camera position requires two rotations to get it oriented correctly. * 1) First it must be rotated +90 degrees around the X axis to get it horizontal (its now facing out the right side of the robot) * 2) Next it must be be rotated +90 degrees (counter-clockwise) around the Z axis to face forward. * * Finally the camera can be translated to its actual mounting position on the robot. * In this example, it is centered on the robot (left-to-right and front-to-back), and 6 inches above ground level. */ /** Let all the trackable listeners know where the camera is. */ /* * WARNING: * In this sample, we do not wait for PLAY to be pressed. Target Tracking is started immediately when INIT is pressed. * This sequence is used to enable the new remote DS Camera Preview feature to be used with this sample. * CONSEQUENTLY do not put any driving commands in this loop. * To restore the normal opmode structure, just un-comment the following line: */ //Reset Encoders leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); //Initialization Complete telemetry.addData("Stat", "Start Program"); telemetry.update(); //Waiting for start via Player waitForStart(); } }
42.565014
429
0.574898
d2b186e0a6792c89344152a464197f338198b373
2,580
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.alm.plugin.idea.common.utils; import com.microsoft.alm.plugin.idea.common.resources.TfPluginBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Date; /** * Helps with converting dates to friendly formats */ public class DateHelper { private final static Logger logger = LoggerFactory.getLogger(DateHelper.class); public static String getFriendlyDateTimeString(final Date date) { final Date now = new Date(); return (getFriendlyDateTimeString(date, now)); } protected static String getFriendlyDateTimeString(final Date date, final Date now) { if (date == null) { return ""; } try { final long diff = now.getTime() - date.getTime(); //in milliseconds if (diff < 0) { return date.toString(); //input date is not in the past } final long diffMinutes = diff / (1000 * 60); if (diffMinutes < 1) { return TfPluginBundle.message(TfPluginBundle.KEY_VCS_PR_DATE_LESS_THAN_A_MINUTE_AGO); } else if (diffMinutes == 1) { return TfPluginBundle.message(TfPluginBundle.KEY_VCS_PR_DATE_ONE_MINUTE_AGO); } else if (diffMinutes < 60) { return TfPluginBundle.message(TfPluginBundle.KEY_VCS_PR_DATE_MINUTES_AGO, diffMinutes); } final long diffHours = diff / (1000 * 60 * 60); if (diffHours <= 1) { return TfPluginBundle.message(TfPluginBundle.KEY_VCS_PR_DATE_ONE_HOUR_AGO); } else if (diffHours <= 24) { return TfPluginBundle.message(TfPluginBundle.KEY_VCS_PR_DATE_HOURS_AGO, diffHours); } final long diffDays = diff / (1000 * 60 * 60 * 24); if (diffDays <= 2) { return TfPluginBundle.message(TfPluginBundle.KEY_VCS_PR_DATE_YESTERDAY); } else if (diffDays < 7) { return TfPluginBundle.message(TfPluginBundle.KEY_VCS_PR_DATE_DAYS_AGO, diffDays); } else { final SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); return format.format(date); } } catch (Throwable t) { logger.warn("getFriendlyDateTimeString unexpected error with input date {}", date.toString(), t); return date.toString(); } } }
38.507463
109
0.625969
c0d175e86276df2a5db77e9e13d12c1397c7b9c3
490
package org.xcolab.client.user; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.xcolab.client.user.pojo.wrapper.SsoClientDetailsWrapper; @FeignClient("xcolab-user-service") public interface ISsoClientDetailsClient { @GetMapping("/ssoClientDetails/{clientId}") SsoClientDetailsWrapper getSsoClientDetails(@PathVariable String clientId); }
30.625
79
0.828571
b00c9eb0d135040e77f1b43c1fffd83994221fbf
2,087
/* * Copyright 2019-2021 Egor Nepomnyaschih, Cody Ebberson. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.squigglesql.squigglesql.syntax; import com.github.squigglesql.squigglesql.Matchable; import com.github.squigglesql.squigglesql.QueryCompiler; import com.github.squigglesql.squigglesql.TableReference; abstract class CommonSqlSyntax implements AbstractSqlSyntax { abstract char getIdentifierQuote(); @Override public char getTableQuote() { return getIdentifierQuote(); } @Override public char getTableReferenceQuote() { return getIdentifierQuote(); } @Override public char getColumnQuote() { return getIdentifierQuote(); } @Override public char getResultColumnQuote() { return getIdentifierQuote(); } @Override public char getFunctionQuote() { return getIdentifierQuote(); } @Override public char getTextQuote() { return '\''; } @Override public void compileIsDistinctFrom(QueryCompiler compiler, Matchable left, Matchable right) { compiler.write(left).write(" IS DISTINCT FROM ").write(right); } @Override public void compileIsNotDistinctFrom(QueryCompiler compiler, Matchable left, Matchable right) { compiler.write(left).write(" IS NOT DISTINCT FROM ").write(right); } @Override public void compileDeleteFrom(QueryCompiler compiler, TableReference tableReference) { compiler.writeln("DELETE FROM").indent().writeln(tableReference).unindent(); } }
29.394366
99
0.711548
2e45c3b2daaece09b4d35249ada68232ef170870
87
/** * Created by xschen on 12/8/2017. */ package com.github.chen0040.leetcode.day17;
17.4
43
0.701149
6eff2dbb70d23b3e757289906c9ca4150b25236d
1,518
package com.devonfw.ide.sonarqube.common.impl.check; import org.junit.Test; import org.sonar.java.checks.verifier.JavaCheckVerifier; /** * Test of {@link DevonArchitecturePackageCheck}. */ public class DevonArchitecturePackageCheckTest { /** * Test the {@link DevonArchitecturePackageCheck}. */ @Test public void testNoScope() { JavaCheckVerifier.verify("src/test/files/DevonArchitecturePackageCheck_NoScope.java", new DevonArchitecturePackageCheck()); } /** * Test the {@link DevonArchitecturePackageCheck}. */ @Test public void testIllegalLayer() { JavaCheckVerifier.verify("src/test/files/DevonArchitecturePackageCheck_IllegalLayer.java", new DevonArchitecturePackageCheck()); } /** * Test the {@link DevonArchitecturePackageCheck}. */ @Test public void testIllegalRoot() { JavaCheckVerifier.verify("src/test/files/DevonArchitecturePackageCheck_IllegalRoot.java", new DevonArchitecturePackageCheck()); } /** * Test the {@link DevonArchitecturePackageCheck}. */ @Test public void testNoIssue() { JavaCheckVerifier.verifyNoIssue("src/test/files/DevonArchitecturePackageCheck_OK.java", new DevonArchitecturePackageCheck()); } /** * Test the {@link DevonArchitecturePackageCheck}. */ @Test public void testNoIssueSpringBootApp() { JavaCheckVerifier.verifyNoIssue("src/test/files/DevonArchitecturePackageCheck_OK_SpringBootApp.java", new DevonArchitecturePackageCheck()); } }
24.885246
105
0.729908
7305fc2f918758eaca4b633a693f5f2eab7fd2ae
240
package colesico.framework.rpc.clientapi; import colesico.framework.rpc.RpcError; public interface RpcErrorHandler<E extends RpcError> { /** * Create exception from error */ RuntimeException createException(E error); }
20
54
0.7375
705aedc6d5a4f7b205aa7d9e29c53af44785b580
16,204
package com.genye.myapplication.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Tools for handler picture */ public final class ImageUtils { /** * drawable转bitmap * Transfer drawable to bitmap * param drawable * return */ public static Bitmap drawableToBitmap(Drawable drawable) { int w = drawable.getIntrinsicWidth(); int h = drawable.getIntrinsicHeight(); Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565; Bitmap bitmap = Bitmap.createBitmap(w, h, config); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, w, h); drawable.draw(canvas); return bitmap; } /** * Bitmap to drawable * Bitmap 转 drawable * param bitmap * return */ public static Drawable bitmapToDrawable(Resources res, Bitmap bitmap) { return new BitmapDrawable(res, bitmap); } /** * Input stream to bitmap * input 转bitmap * param inputStream * return * * @throws Exception */ public static Bitmap inputStreamToBitmap(InputStream inputStream) throws Exception { return BitmapFactory.decodeStream(inputStream); } /** * Byte transfer to bitmap * * @param byteArray * @return */ public static Bitmap byteToBitmap(byte[] byteArray) { return byteArray.length != 0 ? BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length) : null; } /** * Byte transfer to drawable * <p/> * param byteArray * return */ public static Drawable byteToDrawable(byte[] byteArray) { ByteArrayInputStream ins = null; if (byteArray != null) { ins = new ByteArrayInputStream(byteArray); } return Drawable.createFromStream(ins, null); } /** * Bitmap transfer to bytes * * @param bm * @return */ public static byte[] bitmapToBytes(Bitmap bm) { byte[] bytes = null; if (bm != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); bytes = baos.toByteArray(); } return bytes; } /** * Drawable transfer to bytes * * @param drawable * @return */ public static byte[] drawableToBytes(Drawable drawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Bitmap bitmap = bitmapDrawable.getBitmap(); byte[] bytes = bitmapToBytes(bitmap); return bytes; } /** * Base64 to byte[] // */ // public static byte[] base64ToBytes(String base64) throws IOException { // byte[] bytes = Base64.decode(base64); // return bytes; // } // // /** // * Byte[] to base64 // */ // public static String bytesTobase64(byte[] bytes) { // String base64 = Base64.encode(bytes); // return base64; // } /** * Create reflection images * * @param bitmap * @return */ public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) { final int reflectionGap = 4; int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w, h / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, h + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, h, w, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } /** * Get rounded corner images * * @param bitmap * @param roundPx 5 10 * @return */ public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, w, h); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } /** * Resize the bitmap * * @param bitmap * @param width * @param height * @return */ public static Bitmap zoomBitmap(Bitmap bitmap, float width, float height) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = width / w; float scaleHeight = height / h; matrix.postScale(scaleWidth, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); return newbmp; } /** * Resize the drawable * * @param drawable * @param w * @param h * @return */ @SuppressWarnings("deprecation") public static Drawable zoomDrawable(Drawable drawable, int w, int h) { int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap oldbmp = drawableToBitmap(drawable); Matrix matrix = new Matrix(); float sx = ((float) w / width); float sy = ((float) h / height); matrix.postScale(sx, sy); Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true); return new BitmapDrawable(newbmp); } /** * Get images from SD card by path and the name of image * * @param photoName * @return */ public static Bitmap getPhotoFromSDCard(String path, String photoName) { Bitmap photoBitmap = BitmapFactory.decodeFile(path + "/" + photoName + ".png"); return photoBitmap; } /** * Check the SD card * * @return */ public static boolean checkSDCardAvailable() { return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); } /** * Get image from SD card by path and the name of image * * @param path * @param photoName * @return */ public static boolean findPhotoFromSDCard(String path, String photoName) { boolean flag = false; if (checkSDCardAvailable()) { File dir = new File(path); if (dir.exists()) { File folders = new File(path); File photoFile[] = folders.listFiles(); for (int i = 0; i < photoFile.length; i++) { String fileName = photoFile[i].getName().split("\\.")[0]; if (fileName.equals(photoName)) { flag = true; } } } else { flag = false; } } else { flag = false; } return flag; } /** * Save image to the SD card * * @param photoBitmap * @param photoName * @param path */ public static void savePhotoToSDCard(Bitmap photoBitmap, String path, String photoName) { if (checkSDCardAvailable()) { File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } File photoFile = new File(path, photoName + ".png"); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(photoFile); if (photoBitmap != null) { if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) { fileOutputStream.flush(); // fileOutputStream.close(); } } } catch (IOException e) { photoFile.delete(); e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } } /** * Delete the image from SD card * * @param path file:///sdcard/temp.jpg */ public static void deleteAllPhoto(String path) { if (checkSDCardAvailable()) { File folder = new File(path); File[] files = folder.listFiles(); for (int i = 0; i < files.length; i++) { files[i].delete(); } } } public static void deletePhotoAtPathAndName(String path, String fileName) { if (checkSDCardAvailable()) { File folder = new File(path); File[] files = folder.listFiles(); for (File file : files) { if (file.getName().equals(fileName)) { file.delete(); } } } } /** * 读取图片属性:旋转的角度 * * @param path 图片绝对路径 * @return degree旋转的角度 */ public static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * 旋转Bitmap * param b * param rotateDegree * param filter * 当进行的不只是平移变换时,filter参数为true可以进行滤波处理,有助于改善新图像质量;flase时,计算机不做过滤处理。 * return */ public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree, boolean filter) { try { Matrix matrix = new Matrix(); matrix.postRotate(rotateDegree); return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, filter); } catch (OutOfMemoryError e) { return null; } } /** * 保存图片到指定路径 * param context * param bitmap * param path */ public synchronized static boolean saveImageToMe(Context context, Bitmap bitmap, String path) { String filename = System.currentTimeMillis() + ".jpg"; return saveImageToMe(context, bitmap, path, filename); } public static boolean saveImage(Context context, Bitmap bitmap, String path) { String filename = System.currentTimeMillis() + ".jpg"; return saveImage(context, bitmap, path, filename); } public static boolean saveImage(Context context, Bitmap bitmap, String path, String imageName) { if (bitmap == null) return false; File appDir = FileUtils.getChileFile(path); File file = new File(appDir, imageName); try { FileOutputStream fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); return false; } context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE , Uri.parse("file://" + file.getAbsolutePath()))); return true; } /** * 保存图片到指定路径并保存到相册 * param context * param bitmap * param path */ public synchronized static boolean saveImageToMe(Context context, Bitmap bitmap, String path, String imageName) { if (bitmap == null) return false; File appDir = FileUtils.getChileFile(path); File file = new File(appDir, imageName); try { FileOutputStream fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); return false; } try { MediaStore.Images.Media.insertImage(context.getContentResolver() , file.getAbsolutePath(), imageName, null); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE , Uri.parse("file://" + file.getAbsolutePath()))); return true; } public static void intentImgLib(Activity activity, int requestCode) { Intent intent = new Intent(); intent.setType("image/*"); if (Build.VERSION.SDK_INT < 19) { intent.setAction(Intent.ACTION_GET_CONTENT); } else { intent.setAction(Intent.ACTION_OPEN_DOCUMENT); } activity.startActivityForResult(intent, requestCode); } // 截取图片 兼容大小图片裁剪,大图片不返回bitmap,而是返回uri来获取截取的图片,配置如下 public static void cropImage(Uri uri, int outputX, int outputY, int requestCode, Activity activity) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("outputFormat", "JPEG"); intent.putExtra("scale", true); intent.putExtra("scaleUpIfNeeded", true); intent.putExtra("noFaceDetection", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); activity.startActivityForResult(intent, requestCode); } }
31.403101
125
0.588744
24a59794d54b11ccfbeb0dbea38007a06911cc1e
8,279
package ir.fassih.workshopautomation.repository; import ir.fassih.workshopautomation.entity.order.OrderEntity; import ir.fassih.workshopautomation.entity.order.StateOfOrderEntity; import ir.fassih.workshopautomation.entity.orderstate.OrderStateEntity; import ir.fassih.workshopautomation.entity.user.UserEntity; import ir.fassih.workshopautomation.manager.OrderManager; import ir.fassih.workshopautomation.manager.UserManager; import ir.fassih.workshopautomation.repository.report.CountByTimeModel; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") @Transactional public class StateOfOrderRepositoryTest { @Autowired private StateOfOrderRepository repo; @Autowired private OrderStateRepository orderStateRepository; @Autowired private OrderManager orderManager; @Autowired private UserManager userManager; @Test public void testReportWithStateAndUser() throws ParseException { UserEntity u = new UserEntity(); u.setUsername("111"); u.setPassword("111"); userManager.save(u); UserEntity u2 = new UserEntity(); u2.setUsername("222"); u2.setPassword("11221"); userManager.save(u2); OrderEntity orderEntity = new OrderEntity(); orderEntity.setCreator(u); orderManager.save( orderEntity ); OrderEntity orderEntity2 = new OrderEntity(); orderEntity2.setCreator(u2); orderManager.save( orderEntity2 ); SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm"); OrderStateEntity os = new OrderStateEntity(); os.setTitle( "123"); os.setCode("123"); orderStateRepository.save(os); repo.save( createState(parser.parse("2016-10-10 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-11 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-12 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-12 12:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-12 12:42"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-12 13:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-14 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os, orderEntity) ); repo.save( createState(parser.parse("2016-10-10 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-11 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-12 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-12 12:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-12 12:42"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-12 13:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-14 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os, orderEntity2) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os, orderEntity2) ); List<CountByTimeModel<Long>> result = repo.reportByStateAndUser(os.getId(), u.getId(), parser.parse("2016-10-11 00:00"), parser.parse("2016-10-15 00:00")); assertEquals(4, result.size()); for (CountByTimeModel<Long> r : result ) { Date groupedDate = r.getGroupedDate(); if( groupedDate.equals( parser.parse("2016-10-11 00:00") ) ) { assertEquals(1, r.getCount().longValue()); } else if( groupedDate.equals( parser.parse("2016-10-12 00:00") ) ) { assertEquals(4, r.getCount().longValue()); } else if( groupedDate.equals( parser.parse("2016-10-13 00:00") ) ) { assertEquals(3, r.getCount().longValue()); } else if( groupedDate.equals( parser.parse("2016-10-14 00:00") ) ) { assertEquals(1, r.getCount().longValue()); } else { fail("should go in one of those"); } } } @Test public void testInsertWithoutUser() throws ParseException { OrderStateEntity os = new OrderStateEntity(); os.setTitle( "123"); os.setCode("123"); orderStateRepository.save(os); SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm"); repo.save( createState(parser.parse("2016-10-10 11:22"), os) ); repo.save( createState(parser.parse("2016-10-11 11:22"), os) ); repo.save( createState(parser.parse("2016-10-12 11:22"), os) ); repo.save( createState(parser.parse("2016-10-12 12:22"), os) ); repo.save( createState(parser.parse("2016-10-12 12:42"), os) ); repo.save( createState(parser.parse("2016-10-12 13:22"), os) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os) ); repo.save( createState(parser.parse("2016-10-13 11:22"), os) ); repo.save( createState(parser.parse("2016-10-14 11:22"), os) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os) ); repo.save( createState(parser.parse("2016-10-15 11:22"), os) ); List<CountByTimeModel<Long>> result = repo.reportByState(os.getId(), parser.parse("2016-10-11 00:00"), parser.parse("2016-10-15 00:00")); assertEquals(4, result.size()); for (CountByTimeModel<Long> r : result ) { Date groupedDate = r.getGroupedDate(); if( groupedDate.equals( parser.parse("2016-10-11 00:00") ) ) { assertEquals(1, r.getCount().longValue()); } else if( groupedDate.equals( parser.parse("2016-10-12 00:00") ) ) { assertEquals(4, r.getCount().longValue()); } else if( groupedDate.equals( parser.parse("2016-10-13 00:00") ) ) { assertEquals(3, r.getCount().longValue()); } else if( groupedDate.equals( parser.parse("2016-10-14 00:00") ) ) { assertEquals(1, r.getCount().longValue()); } else { fail("should go in one of those"); } } List<CountByTimeModel<Long>> result2 = repo.reportByState(55, parser.parse("2016-10-11 00:00"), parser.parse("2016-10-15 00:00")); assertTrue(result2.isEmpty()); } private StateOfOrderEntity createState(Date d, OrderStateEntity state, OrderEntity orderEntity) { StateOfOrderEntity en = new StateOfOrderEntity(); en.setCreateDate( d ); en.setState( state ); en.setOrder(orderEntity); return en; } private StateOfOrderEntity createState(Date d, OrderStateEntity state) { return createState(d, state, null); } }
36.311404
133
0.642952
fb0f503870a847960a0b1d8be44e7cc0df23af67
2,097
package sgui; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingWorker; import javax.swing.border.BevelBorder; import sgui.mappanel.MapPanel; import sgui.menupanel.MenuPanel; public class SGUI { //Enum for selecting points on the map. public enum MapPointSelectMode{NULL, START, FINISH}; private JFrame mainframe; private MapPanel mapPanel; private MenuPanel menuPanel; private MapPointSelectMode selectMode = MapPointSelectMode.NULL; public SGUI(int width, int height){ //Create JFrame. mainframe = new JFrame(); //Create main panel. JPanel mainpanel = new JPanel(new GridBagLayout()); mainframe.add(mainpanel); GridBagConstraints gbc = new GridBagConstraints(); //Create menu panel. menuPanel = new MenuPanel(width, this); gbc.gridx = 0; gbc.gridy = 0; mainpanel.add(menuPanel, gbc); //Create map panel. mapPanel = new MapPanel(new Dimension(width, height), this); gbc.gridx = 0; gbc.gridy = 1; mainpanel.add(mapPanel, gbc); //Finalize. mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainframe.pack(); mainframe.setResizable(false); } public void setVisible(boolean v){ mainframe.setVisible(v); } /** * Set map point select mode. * @param mode */ public void setMapPointSelectMode(MapPointSelectMode mode){ selectMode = mode; } /** * Get the gui's current select mode. * @return */ public MapPointSelectMode getMapPointSelectMode(){ return selectMode; } /** * Reset the menu panel's select buttons. */ public void resetSelectMode(){ //Reset select mode. this.setMapPointSelectMode(MapPointSelectMode.NULL); //Reset buttons. menuPanel.resetSelectButtons(); } /** * Calls for a repaint of the map panel. */ public void repaintMap(){ mapPanel.refresh(); } /** * Call to start the map draw panel to refresh its frame. */ public void startAutoRefresh(){ mapPanel.startAutoRefresh(); } }
20.762376
65
0.718646
d254aabbb55b5eb370fde0204b7d470714d226f4
246
package com.itstyle.quartz.dao; import com.itstyle.quartz.entity.DsGoods; import java.util.List; /** * (DsCategory)表数据库访问层 * * @author makejava * @since 2020-05-14 21:03:56 */ public interface DsGoodsDao { List<DsGoods> findValid(); }
16.4
41
0.707317
87f64f8c84852e3ce1d7645ee17af12c9a136310
59
package de.samyocord.bongomcbot.utils; public class d { }
11.8
38
0.762712
8644a1afa158f4dda1139935ba1a714748b2a22e
3,028
package com.oureda.thunder.pobooks.manager; import android.graphics.Color; import com.oureda.thunder.pobooks.utils.SharedPreferenceUtil; /** * Created by thunder on 17-5-2. */ public class SettingManager { private static volatile SettingManager manager; private int backgroundBitmap; private boolean isCreatBoot; private boolean isNight; private String getChapterKey(String paramString) { return paramString + "-chapter"; } private String getEndPosKey(String paramString) { return paramString + "-endPos"; } public static SettingManager getInstance() { if (manager == null) { manager = new SettingManager(); } return manager; } private String getStartPosKey(String paramString) { return paramString + "-startPos"; } public int getFontSize() { return SharedPreferenceUtil.getInstance().getInt("textSize", 30); } public int getFontSizeProgress() { return SharedPreferenceUtil.getInstance().getInt("sizeProgress", 1); } public int getPaddingSize() { return SharedPreferenceUtil.getInstance().getInt("paddingSize", 6); } public int getPaddingSizeProgress() { return SharedPreferenceUtil.getInstance().getInt("paddingProgress", 1); } public int getReadColor() { return SharedPreferenceUtil.getInstance().getInt("readColor", Color.WHITE); } public int[] getReadProgress(String bookId) { return new int[] { SharedPreferenceUtil.getInstance().getInt(getChapterKey(bookId), 1), SharedPreferenceUtil.getInstance().getInt(getStartPosKey(bookId), 0), SharedPreferenceUtil.getInstance().getInt(getEndPosKey(bookId), 0) }; } public int getTextColor() { return SharedPreferenceUtil.getInstance().getInt("textColor", Color.BLACK); } public void saveFontSize(int fontSize) { SharedPreferenceUtil.getInstance().putInt("textSize", fontSize); } public void saveFontSizeProgress(int fontSize) { SharedPreferenceUtil.getInstance().putInt("sizeProgress",fontSize); } public void savePaddingSize(int paddingSize) { SharedPreferenceUtil.getInstance().putInt("paddingSize", paddingSize); } public void savePaddingSizeProgress(int paddingSizeProgress) { SharedPreferenceUtil.getInstance().putInt("paddingProgress", paddingSizeProgress); } public void saveReadColor(int readColor) { SharedPreferenceUtil.getInstance().putInt("readColor", readColor); } public void saveReadProgress(String bookId, int chapter, int end, int start) { SharedPreferenceUtil.getInstance().putInt(getChapterKey(bookId), chapter).putInt(getEndPosKey(bookId), end).putInt(getStartPosKey(bookId), start); } public void saveTextColor(int textColor) { SharedPreferenceUtil.getInstance().putInt("textColor", textColor); } public void setIsNight() {} }
27.035714
235
0.682629
ac8a1cd9d0707280d2e3a13e3756a91972b90426
1,365
package problem.p190reversebits; /** * 190. Reverse Bits * * https://leetcode-cn.com/problems/reverse-bits/ * * Reverse bits of a given 32 bits unsigned integer. * * Note: * * Note that in some languages such as Java, there is no unsigned integer type. In this case, * both input and output will be given as a signed integer type. They should not affect your implementation, * as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using 2's complement notation. Therefore, * in Example 2 above, the input represents the signed integer -3 * and the output represents the signed integer -1073741825. * * Follow up: * * If this function is called many times, how would you optimize it? */ public class Solution { public int reverseBits(int n) { int rs = n < 0 ? 1 : 0; for (int i = 0; i < 32; i++) { rs = (rs << 1) | ((n >> i) & 0x1); } return rs; } public static void main(String[] args) { assert new Solution().reverseBits(43261596) == 964176192; assert new Solution().reverseBits((int) (4294967293L & 0xffffffffL)) == (int)(3221225471L & 0xffffffffL); assert new Solution().reverseBits((int) (3856704768L & 0xffffffffL)) == (int)(964176192L & 0xffffffffL); } }
33.292683
113
0.663736
19c680cebf47f615f7c47178779c46805077532d
658
package com.hotel.book.mapper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.hotel.book.config.RoomConfig; import com.hotel.book.pojo.GuestBook; public class GuestBookMapper { public static Map<Integer,List<GuestBook>> rooms=new ConcurrentHashMap<Integer,List<GuestBook>>(); public static List<GuestBook> guestBooks = Collections.synchronizedList(new ArrayList<GuestBook>()); static { for(Integer roomNum =1;roomNum<=RoomConfig.ROOM_NUMS;roomNum++) { rooms.put(roomNum, new ArrayList<GuestBook>()); } } }
22.689655
102
0.753799
07184f49e1d718db6c44d6311bb486baac2bec00
3,568
package uk.gov.hmcts.reform.dg.template.management.resource; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.BDDMockito; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import uk.gov.hmcts.reform.auth.checker.core.SubjectResolver; import uk.gov.hmcts.reform.auth.checker.core.user.User; import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; import uk.gov.hmcts.reform.dg.template.management.Application; import uk.gov.hmcts.reform.dg.template.management.repository.LocalTemplateBinaryRepository; import uk.gov.hmcts.reform.dg.template.management.repository.LocalTemplateListRepository; import java.util.Base64; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class TemplateResourceTest { @MockBean private AuthTokenGenerator authTokenGenerator; @MockBean private SubjectResolver<User> userResolver; private MockMvc mvc; @Before public void setup() { MockitoAnnotations.initMocks(this); mvc = MockMvcBuilders.standaloneSetup( new TemplateResource( new LocalTemplateListRepository(), new LocalTemplateBinaryRepository() ) ).build(); } @Test public void templates() throws Exception { BDDMockito.given(authTokenGenerator.generate()).willReturn("s2s"); BDDMockito.given(userResolver.getTokenDetails("jwt")).willReturn(new User("id", null)); mvc.perform(get("/api/templates")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$[1].name").value("FL-FRM-APP-ENG-00002.docx")) .andExpect(jsonPath("$[2].name").value("FL-FRM-GOR-ENG-00007.docx")) .andExpect(jsonPath("$[3].name").value("PostponementRequestGenericTest.docx")); } @Test public void template() throws Exception { BDDMockito.given(authTokenGenerator.generate()).willReturn("s2s"); BDDMockito.given(userResolver.getTokenDetails("jwt")).willReturn(new User("id", null)); String id = Base64.getEncoder().encodeToString("TB-IAC-APP-ENG-00003 Template Tornado.docx".getBytes()); MvcResult result = mvc.perform(get("/api/templates/" + id)) .andExpect(status().isOk()) .andReturn(); String content = result.getResponse().getContentAsString(); Assert.assertTrue(content.contains("customXml/itemProps1")); } @Test public void template404() throws Exception { BDDMockito.given(authTokenGenerator.generate()).willReturn("s2s"); BDDMockito.given(userResolver.getTokenDetails("jwt")).willReturn(new User("id", null)); String id = Base64.getEncoder().encodeToString("missing template".getBytes()); mvc.perform(get("/api/templates/" + id)) .andExpect(status().isNotFound()) .andReturn(); } }
40.089888
112
0.720572
60924f0ac1365d55ed07d2e17f46a1197d242eea
1,052
package com.example.android.camera2basic; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class CameraActivity_preset extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera_preset); Camera2BasicFragment_preset f=new Camera2BasicFragment_preset(); getFragmentManager().beginTransaction() .replace(R.id.container1, f) .commit(); } @Override public void onBackPressed() { } }
25.658537
72
0.756654
e205a3b195c39bc374921332a0b83443962e760d
630
package ai.ameron.sidecar.integration.reporter.stream; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; @Getter @Setter(value = AccessLevel.PACKAGE) @ConditionalOnProperty( value="app.prediction-event.consumer", havingValue = "stream") @Configuration public class StreamPredictionEventConsumerConfiguration { @Value("${app.prediction-event.consumer.binding.name}") private String bindingName; }
31.5
78
0.822222
77eaaf2924c94d8e199a76147c2de1ac918a7722
1,782
package fr.romainmoreau.gassensor.client.mhz19; import java.io.IOException; import fr.romainmoreau.gassensor.client.common.AbstractGasSensorClient; import fr.romainmoreau.gassensor.client.common.ByteUtils; import fr.romainmoreau.gassensor.client.common.ChecksumGasSensorEventValidator; import fr.romainmoreau.gassensor.client.common.ChecksumUtils; import fr.romainmoreau.gassensor.client.common.FixedLengthGasSensorEventAnalyser; import fr.romainmoreau.gassensor.client.common.GasSensing; import fr.romainmoreau.gassensor.client.common.GasSensorEvent; import fr.romainmoreau.gassensor.client.common.GasSensorEventListener; import fr.romainmoreau.gassensor.client.common.GasSensorExceptionHandler; import fr.romainmoreau.gassensor.client.common.GasSensorReaderFactory; import fr.romainmoreau.gassensor.client.common.GenericGasSensorEvent; public class MhZ19GasSensorClient extends AbstractGasSensorClient<GasSensorEvent> { public MhZ19GasSensorClient(String description, GasSensorReaderFactory<GasSensorEvent> gasSensorReaderFactory, GasSensorEventListener<GasSensorEvent> gasSensorEventListener, GasSensorExceptionHandler gasSensorExceptionHandler) throws IOException { super(description != null ? MhZ19.SENSOR_NAME + description : MhZ19.SENSOR_NAME, gasSensorReaderFactory, gasSensorEventListener, gasSensorExceptionHandler, new FixedLengthGasSensorEventAnalyser(MhZ19.EVENT_LENGTH), new ChecksumGasSensorEventValidator( MhZ19.CHECKSUM_LENGTH, event -> new byte[] { ChecksumUtils.notSum(event) }), MhZ19.HEADER); } @Override protected GasSensorEvent eventToGasSensorEvent(byte[] event) { return new GenericGasSensorEvent(new GasSensing(MhZ19.CO2_DESCRIPTION, ByteUtils.highByteLowByteToBigDecimal(event[2], event[3]), MhZ19.CO2_UNIT)); } }
52.411765
111
0.847363
79956cf0bb45b4299da564732282c5e27163c99e
2,986
package org.jetbrains.tfsIntegration.ui.servertree; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeStructure; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.ui.treeStructure.SimpleTreeStructure; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import java.util.Comparator; public class TfsTreeBuilder extends AbstractTreeBuilder { private static final Logger LOG = Logger.getInstance(TfsTreeBuilder.class.getName()); private static final Comparator<NodeDescriptor<?>> COMPARATOR = (o1, o2) -> { if (o1 instanceof TfsErrorTreeNode) { return o2 instanceof TfsErrorTreeNode ? ((TfsErrorTreeNode)o1).getMessage().compareTo(((TfsErrorTreeNode)o2).getMessage()) : -1; } else if (o2 instanceof TfsErrorTreeNode) { return 1; } final TfsTreeNode n1 = (TfsTreeNode)o1; final TfsTreeNode n2 = (TfsTreeNode)o2; if (n1.isDirectory() && !n2.isDirectory()) { return -1; } else if (!n1.isDirectory() && n2.isDirectory()) { return 1; } return n1.getFileName().compareToIgnoreCase(n2.getFileName()); }; public static TfsTreeBuilder createInstance(@NotNull TfsTreeNode root, @NotNull JTree tree) { final DefaultTreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode(root)); tree.setModel(treeModel); return new TfsTreeBuilder(tree, treeModel, new SimpleTreeStructure.Impl(root) { @Override public boolean isToBuildChildrenInBackground(@NotNull Object element) { return true; } @Override public boolean isAlwaysLeaf(@NotNull Object element) { if (element instanceof TfsTreeNode) { return !((TfsTreeNode)element).isDirectory(); } else { LOG.assertTrue(element instanceof TfsErrorTreeNode); return true; } } }); } public TfsTreeBuilder(JTree tree, DefaultTreeModel treeModel, AbstractTreeStructure treeStructure) { super(tree, treeModel, treeStructure, COMPARATOR); } @Override protected void runBackgroundLoading(@NotNull Runnable runnable) { if (isDisposed()) return; runnable.run(); } @Override protected boolean isAutoExpandNode(NodeDescriptor nodeDescriptor) { if (nodeDescriptor instanceof TfsErrorTreeNode) { return true; } if (nodeDescriptor instanceof TfsTreeNode) { return !((TfsTreeNode)nodeDescriptor).isDirectory() || ((TfsTreeNode)nodeDescriptor).isRoot(); } return false; } @Override protected boolean isAlwaysShowPlus(NodeDescriptor descriptor) { if (descriptor instanceof TfsTreeNode) { return ((TfsTreeNode)descriptor).isDirectory(); } else { LOG.assertTrue(descriptor instanceof TfsErrorTreeNode); return false; } } }
31.431579
134
0.716008
f0693f957d270f3c2538d8178acc3b2a4db40d48
724
package net.kodar.restaurantui.config; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; public class CustomResponseRequestWrapper extends HttpServletResponseWrapper{ public CustomResponseRequestWrapper(HttpServletResponse response) { super(response); // Authentication authentication = Optional.ofNullable(apiCredentials.getAuthentication()).orElse(null); // if(authentication != null) { // CustomUsernamePasswordAuthentication auth = (CustomUsernamePasswordAuthentication) apiCredentials.getAuthentication(); // // String authToken = auth.getAuthToken(); // response.addHeader(Constants.AUTHENTICATION_TOKEN, authToken ); // } } }
34.47619
123
0.78453
b972601b6f12e9c29b839e2e7180cee99bc6d509
7,388
/* * OpenWhisk REST API * API for OpenWhisk * * OpenAPI spec version: 0.1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ActivationResult; import java.io.IOException; /** * Activation */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-24T21:18:05.110+07:00") public class Activation { @SerializedName("namespace") private String namespace = null; @SerializedName("name") private String name = null; @SerializedName("version") private String version = null; @SerializedName("publish") private Boolean publish = null; @SerializedName("subject") private String subject = null; @SerializedName("activationId") private String activationId = null; @SerializedName("start") private String start = null; @SerializedName("end") private String end = null; @SerializedName("result") private ActivationResult result = null; @SerializedName("logs") private String logs = null; public Activation namespace(String namespace) { this.namespace = namespace; return this; } /** * Namespace of the associated item * @return namespace **/ @ApiModelProperty(required = true, value = "Namespace of the associated item") public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public Activation name(String name) { this.name = name; return this; } /** * Name of the item * @return name **/ @ApiModelProperty(required = true, value = "Name of the item") public String getName() { return name; } public void setName(String name) { this.name = name; } public Activation version(String version) { this.version = version; return this; } /** * Semantic version of the item * @return version **/ @ApiModelProperty(required = true, value = "Semantic version of the item") public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Activation publish(Boolean publish) { this.publish = publish; return this; } /** * Whether to publish the item or not * @return publish **/ @ApiModelProperty(required = true, value = "Whether to publish the item or not") public Boolean getPublish() { return publish; } public void setPublish(Boolean publish) { this.publish = publish; } public Activation subject(String subject) { this.subject = subject; return this; } /** * The subject that activated the item * @return subject **/ @ApiModelProperty(required = true, value = "The subject that activated the item") public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public Activation activationId(String activationId) { this.activationId = activationId; return this; } /** * Id of the activation * @return activationId **/ @ApiModelProperty(required = true, value = "Id of the activation") public String getActivationId() { return activationId; } public void setActivationId(String activationId) { this.activationId = activationId; } public Activation start(String start) { this.start = start; return this; } /** * Time when the activation began * @return start **/ @ApiModelProperty(required = true, value = "Time when the activation began") public String getStart() { return start; } public void setStart(String start) { this.start = start; } public Activation end(String end) { this.end = end; return this; } /** * Time when the activation completed * @return end **/ @ApiModelProperty(required = true, value = "Time when the activation completed") public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public Activation result(ActivationResult result) { this.result = result; return this; } /** * Get result * @return result **/ @ApiModelProperty(required = true, value = "") public ActivationResult getResult() { return result; } public void setResult(ActivationResult result) { this.result = result; } public Activation logs(String logs) { this.logs = logs; return this; } /** * Logs generated by the activation * @return logs **/ @ApiModelProperty(required = true, value = "Logs generated by the activation") public String getLogs() { return logs; } public void setLogs(String logs) { this.logs = logs; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Activation activation = (Activation) o; return Objects.equals(this.namespace, activation.namespace) && Objects.equals(this.name, activation.name) && Objects.equals(this.version, activation.version) && Objects.equals(this.publish, activation.publish) && Objects.equals(this.subject, activation.subject) && Objects.equals(this.activationId, activation.activationId) && Objects.equals(this.start, activation.start) && Objects.equals(this.end, activation.end) && Objects.equals(this.result, activation.result) && Objects.equals(this.logs, activation.logs); } @Override public int hashCode() { return Objects.hash(namespace, name, version, publish, subject, activationId, start, end, result, logs); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Activation {\n"); sb.append(" namespace: ").append(toIndentedString(namespace)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" version: ").append(toIndentedString(version)).append("\n"); sb.append(" publish: ").append(toIndentedString(publish)).append("\n"); sb.append(" subject: ").append(toIndentedString(subject)).append("\n"); sb.append(" activationId: ").append(toIndentedString(activationId)).append("\n"); sb.append(" start: ").append(toIndentedString(start)).append("\n"); sb.append(" end: ").append(toIndentedString(end)).append("\n"); sb.append(" result: ").append(toIndentedString(result)).append("\n"); sb.append(" logs: ").append(toIndentedString(logs)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
24.463576
125
0.665133
5247ced5494a6997921714725b9ce1e5a1a84433
1,158
/* * Copyright 2020 Erik Amzallag * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dajlab.bricksetapi.v3.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class AgeRange { private Integer min; private Integer max; /** * @return the min */ public Integer getMin() { return min; } /** * @param min the min to set */ public void setMin(Integer min) { this.min = min; } /** * @return the max */ public Integer getMax() { return max; } /** * @param max the max to set */ public void setMax(Integer max) { this.max = max; } }
21.054545
80
0.696891
c21cc07f104c8af430ce0b2b639974fd9a49d67a
6,546
package com.security.thread.task; import android.os.AsyncTask; import android.os.Environment; import android.text.TextUtils; import com.security.thread.listener.DownloadListener; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * 异步下载任务; */ public class DownloadTask extends AsyncTask<String,Integer,Integer> { private final static long CONNECT_TIMEOUT = 60;//超时时间,秒 private final static long READ_TIMEOUT = 60;//读取时间,秒 private final static long WRITE_TIMEOUT = 60;//写入时间,秒 public static final int TYPE_SUCCESS=0; public static final int TYPE_FAILED=1; public static final int TYPE_PAUSED=2; public static final int TYPE_CANCELED=3; private String DEFAULT_FILE_DIR;//默认下载目录 private DownloadListener listener;//下载进度监听; private boolean isCanceled=false;//取消下载 private boolean isPaused=false;//暂停下载; private int lastProgress;//上次的下载进度; public DownloadTask(DownloadListener listener){ this.listener=listener; } /** * 在子线程中运行; * @param params:运行线程需要的参数; * @return :线程执行后的结果,如TYPE_SUCCESS、TYPE_FAILED等; */ @Override protected Integer doInBackground(String... params) { InputStream is=null; RandomAccessFile savedFile=null; File file=null; try { long downloadedLength=0;//记录已下载的文件的长度; String downloadUrl=params[0];//下载任务地址; file=new File(getDefaultDownloadDirectory(),getFileName(downloadUrl));//文件保存地址; if(file.exists()){ downloadedLength=file.length();//若文件已存在,获取已下载文件的大小; } long contentLength=getContentLength(downloadUrl);//获取文件的总大小; if(contentLength==0){ return TYPE_FAILED;//文件下载失败; }else if(contentLength==downloadedLength){ return TYPE_SUCCESS;//已下载字节和文件总字节相等,说明已下载完成; } OkHttpClient client=getOkHttpClient(); //断点下载,指定从哪个字节开始下载; Request request=new Request.Builder() .addHeader("RANGE","bytes="+downloadedLength+"-") .url(downloadUrl).build(); Response response=client.newCall(request).execute(); if(response!=null&&response.isSuccessful()){//返回结果成功! is=response.body().byteStream(); savedFile=new RandomAccessFile(file,"rw"); savedFile.seek(downloadedLength);//跳转已下载的字节; byte[] buffer=new byte[1024]; int total=0; int len=0; while((len=is.read(buffer))!=-1){ if(isCanceled){ return TYPE_CANCELED; }else if(isPaused){ return TYPE_PAUSED; }else{ total+=len; savedFile.write(buffer,0,len); //计算已下载的百分比; int progress= (int) ((total+downloadedLength)*100/contentLength); //发布已下载的进度; publishProgress(progress); } } response.body().close(); return TYPE_SUCCESS; } } catch (Exception e) { e.printStackTrace(); } finally { try { if(is!=null){ is.close(); } if(savedFile!=null){ savedFile.close(); } if(isCanceled&&file!=null){//取消下载,并且已下载的文件存在,则删除已下载的文件; file.delete(); } } catch (IOException e) { e.printStackTrace(); } } return TYPE_FAILED; } /** * 更新下载进度; * @param values */ @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int progress=values[0]; if(progress>lastProgress){ listener.onProgress(progress); lastProgress=progress; } } /** * 下载完成的回调结果 * @param status:返回结果的回调; */ @Override protected void onPostExecute(Integer status) { super.onPostExecute(status); switch (status){ case TYPE_SUCCESS://下载成功! listener.onSuccess(); break; case TYPE_FAILED://下载失败; listener.onFailed(); break; case TYPE_PAUSED://暂停下载; listener.onPaused(); break; case TYPE_CANCELED://取消下载; listener.onCanceled(); break; } } /** * 暂停下载; */ public void pauseDownload(){ isPaused=true; } /** * 取消下载; */ public void cancelDownload(){ isCanceled=true; } /** * 获取文件的长度; * @param downloadUrl:下载地址; * @return */ private long getContentLength(String downloadUrl) throws IOException { OkHttpClient client = getOkHttpClient(); Request request=new Request.Builder().url(downloadUrl).build(); Response response=client.newCall(request).execute();//执行同步任务; if(response!=null&&response.isSuccessful()){//执行结果成功; long contentLength=response.body().contentLength(); response.close(); return contentLength; } return 0; } /** * 获取OkHttpClient; * @return :返回OkHttpClient; */ private OkHttpClient getOkHttpClient() { return new OkHttpClient.Builder() .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS) .readTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) .build(); } /** * 默认下载目录 * @return */ private String getDefaultDownloadDirectory() { if (TextUtils.isEmpty(DEFAULT_FILE_DIR)) { DEFAULT_FILE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ThreadDownloadTest" + File.separator; } return DEFAULT_FILE_DIR; } /** * 获取下载文件的名称 * @param url * @return */ public String getFileName(String url) { return url.substring(url.lastIndexOf("/") + 1); } }
29.093333
91
0.551329
497ad46c58f185d46aaabdc86736100f3de3faad
2,527
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.service.admin; import java.util.List; import java.util.Map; import com.zimbra.common.auth.ZAuthToken; import com.zimbra.common.service.ServiceException; import com.zimbra.common.util.ZimbraLog; import com.zimbra.common.soap.AdminConstants; import com.zimbra.common.soap.Element; import com.zimbra.cs.account.Provisioning; import com.zimbra.cs.account.Server; import com.zimbra.cs.account.accesscontrol.AdminRight; import com.zimbra.cs.account.accesscontrol.Rights.Admin; import com.zimbra.cs.zimlet.ZimletUtil; import com.zimbra.soap.ZimbraSoapContext; public class UndeployZimlet extends AdminDocumentHandler { private static class UndeployThread implements Runnable { String name; ZAuthToken auth; public UndeployThread(String na, ZAuthToken au) { name = na; auth = au; } public void run() { try { ZimletUtil.uninstallFromOtherServers(name, auth); } catch (Exception e) { ZimbraLog.zimlet.info("undeploy", e); } } } @Override public Element handle(Element request, Map<String, Object> context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); for (Server server : Provisioning.getInstance().getAllServers()) checkRight(zsc, context, server, Admin.R_deployZimlet); String name = request.getAttribute(AdminConstants.A_NAME); String action = request.getAttribute(AdminConstants.A_ACTION, null); ZAuthToken auth = null; if (action == null) auth = zsc.getRawAuthToken(); Element response = zsc.createElement(AdminConstants.UNDEPLOY_ZIMLET_RESPONSE); ZimletUtil.uninstallZimlet(name); new Thread(new UndeployThread(name, auth)).start(); return response; } @Override public void docRights(List<AdminRight> relatedRights, List<String> notes) { relatedRights.add(Admin.R_deployZimlet); notes.add("Need the " + Admin.R_deployZimlet.getName() + " right on all servers."); } }
32.818182
94
0.73051
01466a9ba5397e736f8e25196d2a4b857198568f
2,077
package com.knowledge_network.circle.vo; import com.knowledge_network.circle.entity.Notification; import com.knowledge_network.user.vo.UserInfoVO; import java.util.Date; /** * Created by wshish000 on 18-3-8 */ public class NotificationVO { private Integer id; private boolean scan; private UserInfoVO user; private UserInfoVO targetUser; private Date inTime; private String action; private TopicVO topic; private String content; public NotificationVO(){} public NotificationVO(Notification notification){ id = notification.getId(); scan = notification.isScan(); user = new UserInfoVO(notification.getUser()); targetUser = new UserInfoVO(notification.getTargetUser()); inTime = notification.getInTime(); action = notification.getAction(); topic = new TopicVO(notification.getTopic()); content = notification.getContent(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public boolean isScan() { return scan; } public void setScan(boolean read) { this.scan = read; } public UserInfoVO getUser() { return user; } public void setUser(UserInfoVO user) { this.user = user; } public UserInfoVO getTargetUser() { return targetUser; } public void setTargetUser(UserInfoVO targetUser) { this.targetUser = targetUser; } public Date getInTime() { return inTime; } public void setInTime(Date inTime) { this.inTime = inTime; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public TopicVO getTopic() { return topic; } public void setTopic(TopicVO topic) { this.topic = topic; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
19.59434
66
0.62157
a81246c21b2109744bf9bf4ff9b5d9aa0947e6d7
1,421
package frc.team7170.lib.fsm; import frc.team7170.lib.Name; import frc.team7170.lib.Named; import java.util.logging.Logger; public class Trigger implements Named { private static final Logger LOGGER = Logger.getLogger(Trigger.class.getName()); private final Name name; private final boolean permitMistrigger; private final FiniteStateMachine machine; Trigger(Name name, boolean permitMistrigger, FiniteStateMachine machine) { this.name = name; this.permitMistrigger = permitMistrigger; this.machine = machine; } public boolean execute(boolean log, Object... arguments) { boolean success = machine.executeTrigger(this, arguments); if (log) { if (success) { LOGGER.fine(String.format("Trigger '%s' executed successfully.", toString())); } else { LOGGER.fine(String.format("Trigger '%s' failed to execute.", toString())); } } return success; } public boolean execute(Object... arguments) { return execute(true, arguments); } public boolean getPermitMistrigger() { return permitMistrigger; } public FiniteStateMachine getMachine() { return machine; } @Override public String getName() { return name.getName(); } @Override public Name getNameObject() { return name; } }
25.375
94
0.633357
aa067c70360c13d5bebe4fe65d7d2733d85f2853
2,245
package com.android.renly.plusclub_rn.module.schedule.edu.set; import android.content.Intent; import android.os.Bundle; import android.widget.EditText; import android.widget.FrameLayout; import com.alibaba.fastjson.JSON; import com.android.renly.plusclub_rn.api.bean.Course; import com.android.renly.plusclub_rn.module.base.BaseActivity; import com.android.renly.plusclub_rn.R; import butterknife.BindView; public class ScheduleDetailSetActivity extends BaseActivity { @BindView(R.id.myToolBar) FrameLayout myToolBar; @BindView(R.id.et_setinfo) EditText etSetinfo; private Course object; public static final int requestCode = 256; @Override protected int getLayoutID() { return R.layout.activity_schedule_detail_set; } @Override protected void initData() { Intent intent = getIntent(); String JsonObj = intent.getStringExtra("JsonObj"); object = JSON.parseObject(JsonObj,Course.class); switch (intent.getStringExtra("set")){ case "courseName": initToolBar(true,"修改课名"); etSetinfo.setText(object.getCourseName()); break; case "class": initToolBar(true,"修改教室"); etSetinfo.setText(object.getCourseName()); break; case "weeks": initToolBar(true,"修改周数"); etSetinfo.setText(object.getStartWeek() + "~" + object.getEndWeek()); break; case "sdWeek": initToolBar(true,"修改单双周"); etSetinfo.setText(object.printSD_week()); break; case "js": initToolBar(true,"修改节数"); etSetinfo.setText(object.getCourseTime()); break; case "teacher": initToolBar(true,"修改老师"); etSetinfo.setText(object.getTeacher()); break; } } @Override protected void initView() { initSlidr(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onDestroy() { super.onDestroy(); } }
27.378049
85
0.600891
bc99fde6092fb7937ebf264737fcc521f651d669
1,649
package com.google.api.client.auth.openidconnect; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import java.util.Collection; import java.util.Collections; @Beta public class IdTokenVerifier { public static final long DEFAULT_TIME_SKEW_SECONDS = 300L; private final Clock clock; private final long acceptableTimeSkewSeconds; private final Collection issuers; private final Collection audience; public IdTokenVerifier() { this(new IdTokenVerifier$Builder()); } protected IdTokenVerifier(IdTokenVerifier$Builder builder) { this.clock = builder.clock; this.acceptableTimeSkewSeconds = builder.acceptableTimeSkewSeconds; this.issuers = builder.issuers == null ? null : Collections.unmodifiableCollection(builder.issuers); this.audience = builder.audience == null ? null : Collections.unmodifiableCollection(builder.audience); } public final Clock getClock() { return this.clock; } public final long getAcceptableTimeSkewSeconds() { return this.acceptableTimeSkewSeconds; } public final String getIssuer() { return this.issuers == null ? null : (String)this.issuers.iterator().next(); } public final Collection getIssuers() { return this.issuers; } public final Collection getAudience() { return this.audience; } public boolean verify(IdToken idToken) { return (this.issuers == null || idToken.verifyIssuer(this.issuers)) && (this.audience == null || idToken.verifyAudience(this.audience)) && idToken.verifyTime(this.clock.currentTimeMillis(), this.acceptableTimeSkewSeconds); } }
32.333333
228
0.731352
272a57f8e06c19245430503b4a0e068b72005e14
2,914
package com.github.jnrwinfspteam.jnrwinfsp.internal.util; import com.github.jnrwinfspteam.jnrwinfsp.api.NTStatusException; import com.github.jnrwinfspteam.jnrwinfsp.internal.lib.LibAdvapi32; import com.github.jnrwinfspteam.jnrwinfsp.internal.lib.LibWinFsp; import jnr.ffi.Pointer; import jnr.ffi.Runtime; import jnr.ffi.byref.PointerByReference; public class SecurityDescriptorUtils { public static byte[] toBytes(Pointer pSecurityDescriptor) { int length = LibAdvapi32.INSTANCE.GetSecurityDescriptorLength(pSecurityDescriptor); return PointerUtils.getBytes(pSecurityDescriptor, 0, length); } public static void fromBytes(Runtime runtime, byte[] securityDescriptor, Pointer outPSecurityDescriptor, Pointer outPSecurityDescriptorSize) throws NTStatusException { Pointer pSD = PointerUtils.fromBytes(runtime, securityDescriptor); try { // Put the converted security descriptor (and its size) in the output arguments if (outPSecurityDescriptorSize != null) { int sdSize = securityDescriptor.length; if (sdSize > outPSecurityDescriptorSize.getInt(0)) { // In case of overflow error, WinFsp will retry with a new // allocation based on `pSecurityDescriptorSize`. Hence we // must update this value to the required size. outPSecurityDescriptorSize.putInt(0, sdSize); throw new NTStatusException(0x80000005); // STATUS_BUFFER_OVERFLOW } outPSecurityDescriptorSize.putInt(0, sdSize); if (outPSecurityDescriptor != null) { outPSecurityDescriptor.transferFrom(0, pSD, 0, sdSize); } } } finally { PointerUtils.freeBytesPointer(pSD); } } public static byte[] modify(Runtime runtime, byte[] securityDescriptor, int securityInformation, Pointer pModificationDescriptor) throws NTStatusException { // Put the security descriptor string in a pointer Pointer pSD = PointerUtils.fromBytes(runtime, securityDescriptor); try { PointerByReference outDescriptor = new PointerByReference(); int status = LibWinFsp.INSTANCE.FspSetSecurityDescriptor( pSD, securityInformation, pModificationDescriptor, outDescriptor ); if (status != 0) throw new NTStatusException(status); return toBytes(outDescriptor.getValue()); } finally { PointerUtils.freeBytesPointer(pSD); // avoid memory leak } } }
41.628571
95
0.607756
13f8f1312cdb752fa0346939a15553a578609452
11,001
package org.reso.certification.codegen; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ss.usermodel.Sheet; import org.reso.commander.common.Utils; import org.reso.models.ReferenceStandardField; import static org.reso.certification.codegen.DDLProcessor.buildDbTableName; import static org.reso.certification.containers.WebAPITestContainer.EMPTY_STRING; public class ResourceInfoProcessor extends WorksheetProcessor { final static String ANNOTATION_TERM_DISPLAY_NAME = "RESO.OData.Metadata.StandardName", ANNOTATION_TERM_DESCRIPTION = "Core.Description", ANNOTATION_TERM_URL = "RESO.DDWikiUrl"; private static final Logger LOG = LogManager.getLogger(ResourceInfoProcessor.class); private static final String FILE_EXTENSION = ".java"; public void processResourceSheet(Sheet sheet) { super.processResourceSheet(sheet); markup.append(ResourceInfoTemplates.buildClassInfo(sheet.getSheetName(), null)); } @Override void processNumber(ReferenceStandardField row) { markup.append(ResourceInfoTemplates.buildNumberMarkup(row)); } @Override void processStringListSingle(ReferenceStandardField row) { markup.append(ResourceInfoTemplates.buildStringListSingleMarkup(row)); } @Override void processString(ReferenceStandardField row) { markup.append(ResourceInfoTemplates.buildStringMarkup(row)); } @Override void processBoolean(ReferenceStandardField row) { markup.append(ResourceInfoTemplates.buildBooleanMarkup(row)); } @Override void processStringListMulti(ReferenceStandardField row) { markup.append(ResourceInfoTemplates.buildStringListMultiMarkup(row)); } @Override void processDate(ReferenceStandardField row) { markup.append(ResourceInfoTemplates.buildDateMarkup(row)); } @Override void processTimestamp(ReferenceStandardField row) { markup.append(ResourceInfoTemplates.buildTimestampMarkup(row)); } @Override void processCollection(ReferenceStandardField row) { LOG.debug("Collection Type is not supported!"); } @Override void generateOutput() { LOG.info("Using reference worksheet: " + REFERENCE_WORKSHEET); LOG.info("Generating ResourceInfo .java files for the following resources: " + resourceTemplates.keySet().toString()); resourceTemplates.forEach((resourceName, content) -> { //put in local directory rather than relative to where the input file is Utils.createFile(getDirectoryName(), resourceName + "Definition" + FILE_EXTENSION, content); }); } @Override String getDirectoryName() { return startTimestamp + "-ResourceInfoModels"; } @Override public void afterResourceSheetProcessed(Sheet sheet) { assert sheet != null && sheet.getSheetName() != null; String resourceName = sheet.getSheetName(); String templateContent = markup.toString() + "\n" + " return " + resourceName + "Definition.fieldList;\n" + " }\n" + "}"; resourceTemplates.put(resourceName, templateContent); resetMarkupBuffer(); } public static final class ResourceInfoTemplates { /** * Contains various templates used for test generation * TODO: add a formatter rather than using inline spaces */ public static String buildClassInfo(String resourceName, String generatedTimestamp) { if (resourceName == null) return null; if (generatedTimestamp == null) generatedTimestamp = Utils.getIsoTimestamp(); final String definitionName = resourceName + "Definition"; return "package org.reso.service.data.definition;\n" + "\n" + "import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;\n" + "import org.reso.service.data.meta.FieldInfo;\n" + "import org.reso.service.data.meta.ResourceInfo;\n" + "\n" + "import java.util.ArrayList;\n" + "\n" + "// This class was autogenerated on: " + generatedTimestamp + "\n" + "public class " + definitionName + " extends ResourceInfo {\n" + " private static ArrayList<FieldInfo> fieldList = null;\n" + "\n" + " public " + definitionName + "() {" + "\n" + " this.tableName = " + buildDbTableName(resourceName) + ";\n" + " this.resourcesName = " + resourceName + ";\n" + " this.resourceName = " + resourceName + ";\n" + " }\n" + "\n" + " public ArrayList<FieldInfo> getFieldList() {\n" + " return " + definitionName + ".getStaticFieldList();\n" + " }\n" + "\n" + " public static ArrayList<FieldInfo> getStaticFieldList() {\n" + " if (null != " + definitionName + ".fieldList) {\n" + " return " + definitionName + ".fieldList;\n" + " }\n" + "\n" + " ArrayList<FieldInfo> list = new ArrayList<FieldInfo>();\n" + " " + definitionName + ".fieldList = list;\n" + " FieldInfo fieldInfo = null;\n"; } public static String buildBooleanMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; //TODO: refactor into one method that takes a type name and returns the appropriate content return "\n" + " fieldInfo = new FieldInfo(\"" + field.getStandardName() + "\", EdmPrimitiveTypeKind.Boolean.getFullQualifiedName());\n" + " fieldInfo.addAnnotation(\"" + field.getDisplayName() + "\", \"" + ANNOTATION_TERM_DISPLAY_NAME + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getDefinition() + "\", \"" + ANNOTATION_TERM_DESCRIPTION + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getWikiPageUrl() + "\", \"" + ANNOTATION_TERM_URL + "\");\n" + " list.add(fieldInfo);" + "\n"; } public static String buildDateMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; return "\n" + " fieldInfo = new FieldInfo(\"" + field.getStandardName() + "\", EdmPrimitiveTypeKind.Date.getFullQualifiedName());\n" + " fieldInfo.addAnnotation(\"" + field.getDisplayName() + "\", \"" + ANNOTATION_TERM_DISPLAY_NAME + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getDefinition() + "\", \"" + ANNOTATION_TERM_DESCRIPTION + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getWikiPageUrl() + "\", \"" + ANNOTATION_TERM_URL + "\");\n" + " list.add(fieldInfo);" + "\n"; } /** * Provides special routing for Data Dictionary numeric types, which may be Integer or Decimal * * @param field the numeric field to build type markup for * @return a string containing specific markup for the given field */ public static String buildNumberMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; if (field.getSuggestedMaxPrecision() != null) return buildDecimalMarkup(field); else return buildIntegerMarkup(field); } public static String buildDecimalMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; return "\n" + " fieldInfo = new FieldInfo(\"" + field.getStandardName() + "\", EdmPrimitiveTypeKind.Decimal.getFullQualifiedName());\n" + " fieldInfo.addAnnotation(\"" + field.getDisplayName() + "\", \"" + ANNOTATION_TERM_DISPLAY_NAME + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getDefinition() + "\", \"" + ANNOTATION_TERM_DESCRIPTION + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getWikiPageUrl() + "\", \"" + ANNOTATION_TERM_URL + "\");\n" + " list.add(fieldInfo);" + "\n"; //TODO: Length is actually scale for Decimal fields by the DD! :/ //TODO: Add setScale property to Decimal types in FieldInfo //TODO: Precision is actually Scale for Decimal fields by the DD! :/ //TODO: Add setPrecision property to Decimal types in FieldInfo } public static String buildIntegerMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; return "\n" + " fieldInfo = new FieldInfo(\"" + field.getStandardName() + "\", EdmPrimitiveTypeKind.Int64.getFullQualifiedName());\n" + " fieldInfo.addAnnotation(\"" + field.getDisplayName() + "\", \"" + ANNOTATION_TERM_DISPLAY_NAME + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getDefinition() + "\", \"" + ANNOTATION_TERM_DESCRIPTION + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getWikiPageUrl() + "\", \"" + ANNOTATION_TERM_URL + "\");\n" + " list.add(fieldInfo);" + "\n"; } private static String buildStandardEnumerationMarkup(String lookupName) { //TODO: add code to build Lookups return "\n /* TODO: buildStandardEnumerationMarkup */\n"; } public static String buildStringListMultiMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; //TODO: add multi lookup handler return "\n /* TODO: buildStringListMultiMarkup */\n"; } public static String buildStringListSingleMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; //TODO: add single lookup handler return "\n /* TODO: buildStringListSingleMarkup */\n"; } public static String buildStringMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; String content = "\n" + " fieldInfo = new FieldInfo(\"" + field.getStandardName() + "\", EdmPrimitiveTypeKind.String.getFullQualifiedName());\n" + " fieldInfo.addAnnotation(\"" + field.getDisplayName() + "\", \"" + ANNOTATION_TERM_DISPLAY_NAME + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getDefinition() + "\", \"" + ANNOTATION_TERM_DESCRIPTION + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getWikiPageUrl() + "\", \"" + ANNOTATION_TERM_URL + "\");\n"; if (field.getSuggestedMaxLength() != null) { content += " fieldInfo.setMaxLength(" + field.getSuggestedMaxLength() + ");\n"; } content += " list.add(fieldInfo);" + "\n"; return content; } public static String buildTimestampMarkup(ReferenceStandardField field) { if (field == null) return EMPTY_STRING; return "\n" + " fieldInfo = new FieldInfo(\"" + field.getStandardName() + "\", EdmPrimitiveTypeKind.DateTime.getFullQualifiedName());\n" + " fieldInfo.addAnnotation(\"" + field.getDisplayName() + "\", \"" + ANNOTATION_TERM_DISPLAY_NAME + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getDefinition() + "\", \"" + ANNOTATION_TERM_DESCRIPTION + "\");\n" + " fieldInfo.addAnnotation(\"" + field.getWikiPageUrl() + "\", \"" + ANNOTATION_TERM_URL + "\");\n" + " list.add(fieldInfo);" + "\n"; } } }
44.004
137
0.641487
2a3bf12d687f43f5e812c18fa8f25741682c716b
1,589
//package org.lxp.springboot.asm; // //import jdk.internal.org.objectweb.asm.ClassReader; //import jdk.internal.org.objectweb.asm.ClassVisitor; //import jdk.internal.org.objectweb.asm.MethodVisitor; // ///** // * Created by linxiaopeng on 2018-7-23. // */ //public class AsmMethodVisitorExample { // // public void examle1() throws Exception{ // new ClassReader(AsmTestBean.class.getName()).accept(new ClassVisitor() { // public MethodVisitor visitMethod(int access, String name, String desc, // String signature, String[] exceptions) { // if(name.equals("showlimit") { // We found a method named 'compareTo' // return new MethodVisitor() { // @Override // Callback for byte code method instructions // public void visitMethodInsn(int opcode, String owner, // String name, String desc) { // System.out.println("Method " + name + " was called on " + owner); // } // @Override // Callback for byte code field instructions // public void visitFieldInsn(int opcode, String owner, // String name, String desc) { // System.out.println("Field " + name + " was accessed on " + owner); // } // } // } // return null; // } // } // } //}
45.4
96
0.494021
de537cb6ae04cff400ee83a970e94c14dc3afb8f
13,964
package DataManipulation; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javafx.scene.control.Alert; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; /** * This class handles most of the queries with the data base. * @author Adrian Mora */ public class MountieQueries{ private String sql; private String searchString; private static Connection connection; private static final String URL = "jdbc:mysql://localhost:3306/mountie_lib_db"; private static String userDB= "pxndroid"; private static String passDB = "MOZA0589"; private PreparedStatement preparedStatment; private ResultSet resultSet; /** * Default Constructor with no-arguments. */ public MountieQueries() { } /** * Constructor with one argument; used mostly for SELECT * queries. * @param sql The SQL statement to be executed. */ public MountieQueries(String sql) { try{ setSQL(sql); connection = DriverManager.getConnection(URL, userDB, passDB); preparedStatment = connection.prepareStatement(sql); } catch (SQLException sqlException) { sqlException.printStackTrace(); displayAlert(Alert.AlertType.ERROR,"Error" , "Data base could not be loaded", searchString); System.exit(1); } }//end of constructor with 1 parameters /** * Constructor with SQL argument and a search argument; used to find specific * records. * @param sql The SQL statement to be executed. * @param searchString The specific record to be search for. */ public MountieQueries(String sql, String searchString) { try{ setSQL(sql); setSearchString(searchString); //get the connection to database connection = DriverManager.getConnection(URL, userDB, passDB); //prepatre statements preparedStatment = connection.prepareStatement(sql); //set parameters preparedStatment.setString(1, searchString); //execute query resultSet = preparedStatment.executeQuery(); } catch (SQLException sqlException) { sqlException.printStackTrace(); displayAlert(Alert.AlertType.ERROR,"Error" , "Data base could not be loaded", searchString); System.exit(1); } }//end of constructor with 2 parameters /** * Constructor with arguments; used to search a record that matched 2 parameter. * @param sql The SQL statement to be executed. * @param search1 The first specific record attribute to be search for. * @param search2 The second specific record attribute to be search for. */ public MountieQueries(String sql, String search1, String search2) { try{ setSQL(sql); //get the connection to database connection = DriverManager.getConnection(URL, userDB, passDB); //prepatre statements preparedStatment = connection.prepareStatement(sql); //set parameters preparedStatment.setString(1, search1); preparedStatment.setString(2, search2); //execute query resultSet = preparedStatment.executeQuery(); } catch (SQLException sqlException) { sqlException.printStackTrace(); displayAlert(Alert.AlertType.ERROR,"Error" , "Data base could not be loaded", searchString); System.exit(1); } }//end of constructor with 3 parameters /** * Sets the SQL statement to be executed. * @param sql the SQL statement. */ public void setSQL(String sql){ this.sql = sql; } /** * Sets the search argument. * @param setSearchString the search argument for the SQL statement. */ public void setSearchString(String setSearchString){ this.searchString = setSearchString; } /** * Sets the Result set. * @throws SQLException If the connection to the data base failed. */ public void setResultSet() throws SQLException{ try{ resultSet = preparedStatment.executeQuery(); } catch (SQLException sqlException) { sqlException.printStackTrace(); displayAlert(Alert.AlertType.ERROR,"Error" , "Data base could not be loaded", searchString); System.exit(1); } } /** * Gets the SQL statement. * @return a <code>String</code> specifying the SQL statement. */ public String getSQL() { return sql; } /** * Gets the search String argument. * @return a <code>String</code> specifying the search string. */ public String getSearchString() { return searchString; } /** * Gets the Result set. * @return a <code>ResulSet</code> specifying the result of the query. */ public ResultSet getResultSet() { return resultSet; } /** * Gets the preparedStament * @return a <code>PreparedStatement</code> specifying the SQL set. */ public PreparedStatement getPreparedStatment(){ return preparedStatment; } /** * Add an entry to the data base with the specified arguments. * @param fName_isbn the students first name or books isbn of new entry. * @param lName_title the students last name or books title of the book. * @param address_pubYear the students address or the books publication year. * @param phone_copies the students phone number or books number of copies. * @param email_author the students email or books author of the book. * @return an <code>integer</code> specifying if the query executed successfully. */ public int addEntry(String fName_isbn, String lName_title, String address_pubYear, String phone_copies, String email_author) { int success = 0; //0 means unsucesfully try { // set parameters preparedStatment.setString(1, fName_isbn); preparedStatment.setString(2, lName_title); preparedStatment.setString(3, address_pubYear); preparedStatment.setString(4, phone_copies); preparedStatment.setString(5, email_author); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Adds a check-out transaction to the data base. * @param transID the transaction id number. * @param isbn the books isbn number. * @param cardID the student id number. * @param dateIssue the date the book was check-out. * @param dateDue the date the book is due. * @return an <code>integer</code> specifying if the query executed successfully. */ public int addCheckOut(int transID, long isbn, int cardID, String dateIssue, String dateDue) { int success = 0; //0 means unsucesfully try { // set parameters preparedStatment.setInt(1, transID); preparedStatment.setLong(2, isbn); preparedStatment.setInt(3, cardID); preparedStatment.setString(4, dateIssue); preparedStatment.setString(5, dateDue); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Process the books check-in process. * @param isbn the books isbn number. * @param returnDate the day the book was returned. * @return an <code>integer</code> specifying if the query executed successfully. */ public int addCheckIn(long isbn, String returnDate) { int success = 0; //0 means unsucesfully try { // set parameters preparedStatment.setString(1, returnDate); preparedStatment.setLong(2, isbn); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Updates Students information in the data base. * @param fName Students first name. * @param lName Students last name. * @param address Students address. * @param phone Students phone number. * @param email Students email. * @param id Students id number. * @return an <code>integer</code> specifying if the query executed successfully. */ public int updateStudent(String fName, String lName, String address, String phone, String email, int id) { int success = 0; //0 means unsucesfully try {// set parameters preparedStatment.setString(1, fName); preparedStatment.setString(2, lName); preparedStatment.setString(3, address); preparedStatment.setString(4, phone); preparedStatment.setString(5, email); preparedStatment.setInt(6, id); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Updates the book information in the data base. * @param title Books title. * @param year Books publication year. * @param copies Books number of copies. * @param author Books author. * @param isbn Books isbn number. * @return an <code>integer</code> specifying if the query executed successfully. */ public int updateBook(String title, String year, int copies, String author, long isbn) { int success = 0; //0 means unsucesfully try {// set parameters preparedStatment.setString(1, title); preparedStatment.setString(2, year); preparedStatment.setInt(3, copies); preparedStatment.setString(4, author); preparedStatment.setLong(5, isbn); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Update avaliable copies in the data base. * @param isbn Books isbn number. * @param copies Books number of copies. * @return an <code>integer</code> specifying if the query executed successfully. */ public int updateBookCopies(long isbn, int copies) { int success = 0; //0 means unsucesfully try { // set parameters preparedStatment.setLong(1, copies); preparedStatment.setLong(2, isbn); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Deletes a student in the data base. * @param cardID Students id number. * @return an <code>integer</code> specifying if the query executed successfully. */ public int deleteStudent(int cardID) { int success = 0; //0 means unsucesfully try { preparedStatment.setInt(1, cardID); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Deletes a Book in the data base. * @param isbn Books isbn number. * @return an <code>integer</code> specifying if the query executed successfully. */ public int deleteBook(long isbn) { int success = 0; //0 means unsucesfully try { preparedStatment.setLong(1, isbn); return preparedStatment.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); return success; } } /** * Displays and alert window if the connection to the data base failed. * @param type Type of alert to be displayed. * @param title title of the alerts window. * @param messageHeader Message to be displayed on the alert window. * @param extraText extra text to display (optional) */ private void displayAlert(Alert.AlertType type, String title, String messageHeader, String extraText) { Alert alert = new Alert(type); //If database is not available alert.setTitle(title); alert.setHeaderText(messageHeader); Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image("images/db.png")); alert.setGraphic(new ImageView(("images/db.png"))); alert.showAndWait(); }//end of displayAlert }
34.650124
89
0.583357
8f507722e4eb48ccd52125738f84e3ccba6aff6b
2,610
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.dvcs.actions; import com.intellij.ide.ui.customization.CustomActionsSchema; import com.intellij.ide.ui.customization.CustomisedActionGroup; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.VcsActions; import com.intellij.openapi.vcs.actions.VcsQuickListContentProvider; import com.intellij.openapi.vcs.actions.VcsQuickListPopupAction; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public abstract class DvcsQuickListContentProvider implements VcsQuickListContentProvider { @Override @Nullable public List<AnAction> getVcsActions(@Nullable Project project, @Nullable AbstractVcs activeVcs, @Nullable DataContext dataContext) { if (activeVcs == null || !replaceVcsActionsFor(activeVcs, dataContext)) return null; final ActionManager manager = ActionManager.getInstance(); final List<AnAction> actions = new ArrayList<>(); ActionGroup vcsGroup = (ActionGroup)CustomActionsSchema.getInstance().getCorrectedAction(VcsActions.VCS_OPERATIONS_POPUP); ActionGroup vcsAwareGroup = (ActionGroup)ContainerUtil.find(vcsGroup.getChildren(null), action -> { if (action instanceof CustomisedActionGroup) action = ((CustomisedActionGroup)action).getOrigin(); return action instanceof VcsQuickListPopupAction.VcsAware; }); if (vcsAwareGroup != null) ContainerUtil.addAll(actions, vcsAwareGroup.getChildren(null)); List<AnAction> providerActions = collectVcsSpecificActions(manager); actions.removeAll(providerActions); actions.add(Separator.getInstance()); actions.addAll(providerActions); return actions; } @NotNull protected abstract String getVcsName(); protected abstract List<AnAction> collectVcsSpecificActions(@NotNull ActionManager manager); @Override public boolean replaceVcsActionsFor(@NotNull AbstractVcs activeVcs, @Nullable DataContext dataContext) { return getVcsName().equals(activeVcs.getName()); } protected static void add(String actionName, ActionManager manager, List<? super AnAction> actions) { final AnAction action = manager.getAction(actionName); assert action != null : "Can not find action " + actionName; actions.add(action); } }
43.5
140
0.778544
e0036fc7dcac314548729dd93b1d81239ace9fa5
31,423
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.reactor.client.v2.securitygroups; import org.cloudfoundry.client.v2.Metadata; import org.cloudfoundry.client.v2.jobs.JobEntity; import org.cloudfoundry.client.v2.securitygroups.AssociateSecurityGroupSpaceRequest; import org.cloudfoundry.client.v2.securitygroups.AssociateSecurityGroupSpaceResponse; import org.cloudfoundry.client.v2.securitygroups.CreateSecurityGroupRequest; import org.cloudfoundry.client.v2.securitygroups.CreateSecurityGroupResponse; import org.cloudfoundry.client.v2.securitygroups.DeleteSecurityGroupRequest; import org.cloudfoundry.client.v2.securitygroups.DeleteSecurityGroupResponse; import org.cloudfoundry.client.v2.securitygroups.GetSecurityGroupRequest; import org.cloudfoundry.client.v2.securitygroups.GetSecurityGroupResponse; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupRunningDefaultsRequest; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupRunningDefaultsResponse; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupSpacesRequest; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupSpacesResponse; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupStagingDefaultsRequest; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupStagingDefaultsResponse; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupsRequest; import org.cloudfoundry.client.v2.securitygroups.ListSecurityGroupsResponse; import org.cloudfoundry.client.v2.securitygroups.RemoveSecurityGroupRunningDefaultRequest; import org.cloudfoundry.client.v2.securitygroups.RemoveSecurityGroupSpaceRequest; import org.cloudfoundry.client.v2.securitygroups.RemoveSecurityGroupStagingDefaultRequest; import org.cloudfoundry.client.v2.securitygroups.RuleEntity; import org.cloudfoundry.client.v2.securitygroups.SecurityGroupEntity; import org.cloudfoundry.client.v2.securitygroups.SecurityGroupResource; import org.cloudfoundry.client.v2.securitygroups.SetSecurityGroupRunningDefaultRequest; import org.cloudfoundry.client.v2.securitygroups.SetSecurityGroupRunningDefaultResponse; import org.cloudfoundry.client.v2.securitygroups.SetSecurityGroupStagingDefaultRequest; import org.cloudfoundry.client.v2.securitygroups.SetSecurityGroupStagingDefaultResponse; import org.cloudfoundry.client.v2.securitygroups.UpdateSecurityGroupRequest; import org.cloudfoundry.client.v2.securitygroups.UpdateSecurityGroupResponse; import org.cloudfoundry.client.v2.spaces.SpaceEntity; import org.cloudfoundry.client.v2.spaces.SpaceResource; import org.cloudfoundry.reactor.InteractionContext; import org.cloudfoundry.reactor.TestRequest; import org.cloudfoundry.reactor.TestResponse; import org.cloudfoundry.reactor.client.AbstractClientApiTest; import org.junit.Test; import reactor.test.StepVerifier; import java.time.Duration; import java.util.Collections; import static io.netty.handler.codec.http.HttpMethod.DELETE; import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpMethod.POST; import static io.netty.handler.codec.http.HttpMethod.PUT; import static io.netty.handler.codec.http.HttpResponseStatus.ACCEPTED; import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static org.cloudfoundry.client.v2.securitygroups.Protocol.ALL; import static org.cloudfoundry.client.v2.securitygroups.Protocol.ICMP; import static org.cloudfoundry.client.v2.securitygroups.Protocol.TCP; import static org.cloudfoundry.client.v2.securitygroups.Protocol.UDP; public final class ReactorSecurityGroupsTest extends AbstractClientApiTest { private final ReactorSecurityGroups securityGroups = new ReactorSecurityGroups(CONNECTION_CONTEXT, this.root, TOKEN_PROVIDER, Collections.emptyMap()); @Test public void associateSpace() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(PUT).path("/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/spaces/1305ec2b-a31c-4d2e-adc8-d9b764237e96") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/security_groups/PUT_{id}_spaces_{space-id}_response.json") .build()) .build()); this.securityGroups .associateSpace(AssociateSecurityGroupSpaceRequest.builder() .securityGroupId("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .spaceId("1305ec2b-a31c-4d2e-adc8-d9b764237e96") .build()) .as(StepVerifier::create) .expectNext(AssociateSecurityGroupSpaceResponse.builder() .metadata(Metadata.builder() .createdAt("2016-06-08T16:41:21Z") .id("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .updatedAt("2016-06-08T16:41:26Z") .url("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .build()) .entity(SecurityGroupEntity.builder() .name("dummy1") .rules() .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/spaces") .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void create() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(POST).path("/security_groups") .payload("fixtures/client/v2/security_groups/POST_request.json") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/security_groups/POST_response.json") .build()) .build()); this.securityGroups .create(CreateSecurityGroupRequest.builder() .name("my_super_sec_group") .rule(RuleEntity.builder() .protocol(ICMP) .destination("0.0.0.0/0") .type(0) .code(1) .build()) .rule(RuleEntity.builder() .protocol(TCP) .destination("0.0.0.0/0") .ports("2048-3000") .log(true) .build()) .rule(RuleEntity.builder() .protocol(UDP) .destination("0.0.0.0/0") .ports("53, 5353") .build()) .rule(RuleEntity.builder() .protocol(ALL) .destination("0.0.0.0/0") .build()) .build()) .as(StepVerifier::create) .expectNext(CreateSecurityGroupResponse.builder() .metadata(Metadata.builder() .createdAt("2016-05-12T00:45:26Z") .id("966e7ac0-1c1a-4ca9-8a5f-77c96576beb7") .url("/v2/security_groups/966e7ac0-1c1a-4ca9-8a5f-77c96576beb7") .build()) .entity(SecurityGroupEntity.builder() .name("my_super_sec_group") .rule(RuleEntity.builder() .protocol(ICMP) .destination("0.0.0.0/0") .type(0) .code(1) .build()) .rule(RuleEntity.builder() .protocol(TCP) .destination("0.0.0.0/0") .ports("2048-3000") .log(true) .build()) .rule(RuleEntity.builder() .protocol(UDP) .destination("0.0.0.0/0") .ports("53, 5353") .build()) .rule(RuleEntity.builder() .protocol(ALL) .destination("0.0.0.0/0") .build()) .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/966e7ac0-1c1a-4ca9-8a5f-77c96576beb7/spaces") .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void delete() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(DELETE).path("/security_groups/test-id") .build()) .response(TestResponse.builder() .status(NO_CONTENT) .build()) .build()); this.securityGroups .delete(DeleteSecurityGroupRequest.builder() .securityGroupId("test-id") .build()) .as(StepVerifier::create) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void deleteAsync() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(DELETE).path("/security_groups/test-id?async=true") .build()) .response(TestResponse.builder() .status(ACCEPTED) .payload("fixtures/client/v2/security_groups/DELETE_{id}_async_response.json") .build()) .build()); this.securityGroups .delete(DeleteSecurityGroupRequest.builder() .async(true) .securityGroupId("test-id") .build()) .as(StepVerifier::create) .expectNext(DeleteSecurityGroupResponse.builder() .metadata(Metadata.builder() .id("260ba675-47b6-4094-be7a-349d58e3d36a") .createdAt("2016-02-02T17:16:31Z") .url("/v2/jobs/260ba675-47b6-4094-be7a-349d58e3d36a") .build()) .entity(JobEntity.builder() .id("260ba675-47b6-4094-be7a-349d58e3d36a") .status("queued") .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void deleteRunning() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(DELETE).path("/config/running_security_groups/test-id") .build()) .response(TestResponse.builder() .status(NO_CONTENT) .build()) .build()); this.securityGroups .removeRunningDefault(RemoveSecurityGroupRunningDefaultRequest.builder() .securityGroupId("test-id") .build()) .as(StepVerifier::create) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void deleteStaging() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(DELETE).path("/config/staging_security_groups/test-id") .build()) .response(TestResponse.builder() .status(NO_CONTENT) .build()) .build()); this.securityGroups .removeStagingDefault(RemoveSecurityGroupStagingDefaultRequest.builder() .securityGroupId("test-id") .build()) .as(StepVerifier::create) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void get() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(GET).path("/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/security_groups/GET_{id}_response.json") .build()) .build()); this.securityGroups .get(GetSecurityGroupRequest.builder() .securityGroupId("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .build()) .as(StepVerifier::create) .expectNext(GetSecurityGroupResponse.builder() .metadata(Metadata.builder() .createdAt("2016-06-08T16:41:21Z") .id("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .updatedAt("2016-06-08T16:41:26Z") .url("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .build()) .entity(SecurityGroupEntity.builder() .name("dummy1") .rules() .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/spaces") .stagingSpacesUrl("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/staging_spaces") .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void list() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(GET).path("/security_groups") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/security_groups/GET_security_groups_response.json") .build()) .build()); this.securityGroups .list(ListSecurityGroupsRequest.builder() .build()) .as(StepVerifier::create) .expectNext(ListSecurityGroupsResponse.builder() .totalResults(5) .totalPages(1) .resource(SecurityGroupResource.builder() .metadata(Metadata.builder() .id("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .url("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .createdAt("2016-06-08T16:41:21Z") .build()) .entity(SecurityGroupEntity.builder() .name("dummy1") .rules() .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/spaces") .build()) .build()) .resource(SecurityGroupResource.builder() .metadata(Metadata.builder() .id("61a3df25-f372-4554-9b77-811aaa5374c1") .url("/v2/security_groups/61a3df25-f372-4554-9b77-811aaa5374c1") .createdAt("2016-06-08T16:41:21Z") .build()) .entity(SecurityGroupEntity.builder() .name("dummy2") .rules() .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/61a3df25-f372-4554-9b77-811aaa5374c1/spaces") .build()) .build()) .resource(SecurityGroupResource.builder() .metadata(Metadata.builder() .id("26bdad19-b077-4542-aac0-f7e4c53c344d") .url("/v2/security_groups/26bdad19-b077-4542-aac0-f7e4c53c344d") .createdAt("2016-06-08T16:41:22Z") .build()) .entity(SecurityGroupEntity.builder() .name("name-67") .rule(RuleEntity.builder() .protocol(UDP) .ports("8080") .destination("198.41.191.47/1") .build()) .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/26bdad19-b077-4542-aac0-f7e4c53c344d/spaces") .build()) .build()) .resource(SecurityGroupResource.builder() .metadata(Metadata.builder() .id("0a2b8908-66f5-4bef-80f3-ca21ed86fbb3") .url("/v2/security_groups/0a2b8908-66f5-4bef-80f3-ca21ed86fbb3") .createdAt("2016-06-08T16:41:22Z") .build()) .entity(SecurityGroupEntity.builder() .name("name-68") .rule(RuleEntity.builder() .protocol(UDP) .ports("8080") .destination("198.41.191.47/1") .build()) .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/0a2b8908-66f5-4bef-80f3-ca21ed86fbb3/spaces") .build()) .build()) .resource(SecurityGroupResource.builder() .metadata(Metadata.builder() .id("f5b93b76-cd25-4fed-bed6-0d9d0acff542") .url("/v2/security_groups/f5b93b76-cd25-4fed-bed6-0d9d0acff542") .createdAt("2016-06-08T16:41:22Z") .build()) .entity(SecurityGroupEntity.builder() .name("name-69") .rule(RuleEntity.builder() .protocol(UDP) .ports("8080") .destination("198.41.191.47/1") .build()) .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/f5b93b76-cd25-4fed-bed6-0d9d0acff542/spaces") .build()) .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void listRunning() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(GET).path("/config/running_security_groups") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/config/GET_running_security_groups_response.json") .build()) .build()); this.securityGroups .listRunningDefaults(ListSecurityGroupRunningDefaultsRequest.builder() .build()) .as(StepVerifier::create) .expectNext(ListSecurityGroupRunningDefaultsResponse.builder() .totalPages(1) .totalResults(1) .resource(SecurityGroupResource.builder() .metadata(Metadata.builder() .createdAt("2016-04-06T00:17:17Z") .id("1f2f24f8-f68c-4a3b-b51a-8134fe2626d8") .url("/v2/config/running_security_groups/1f2f24f8-f68c-4a3b-b51a-8134fe2626d8") .build()) .entity(SecurityGroupEntity.builder() .name("name-114") .rule(RuleEntity.builder() .destination("198.41.191.47/1") .ports("8080") .protocol(UDP) .build()) .runningDefault(true) .stagingDefault(false) .build()) .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void listSpaces() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(GET).path("/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/spaces?space_guid=09a060b2-f97a-4a57-b7d2-35e06ad71050") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/config/GET_{id}_spaces_response.json") .build()) .build()); this.securityGroups .listSpaces(ListSecurityGroupSpacesRequest.builder() .securityGroupId("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .spaceId("09a060b2-f97a-4a57-b7d2-35e06ad71050") .build()) .as(StepVerifier::create) .expectNext(ListSecurityGroupSpacesResponse.builder() .totalPages(1) .totalResults(1) .resource(SpaceResource.builder() .metadata(Metadata.builder() .createdAt("2016-06-08T16:41:21Z") .id("3435dd59-f289-4191-83e6-6201d6fb6a22") .updatedAt("2016-06-08T16:41:26Z") .url("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22") .build()) .entity(SpaceEntity.builder() .allowSsh(true) .applicationEventsUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/app_events") .applicationsUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/apps") .auditorsUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/auditors") .developersUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/developers") .domainsUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/domains") .eventsUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/events") .managersUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/managers") .name("name-40") .organizationId("1d1dd3f4-36bd-4380-8d01-3c7a934a9281") .organizationUrl("/v2/organizations/1d1dd3f4-36bd-4380-8d01-3c7a934a9281") .routesUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/routes") .securityGroupsUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/security_groups") .serviceInstancesUrl("/v2/spaces/3435dd59-f289-4191-83e6-6201d6fb6a22/service_instances") .spaceQuotaDefinitionId(null) .build()) .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void listStaging() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(GET).path("/config/staging_security_groups") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/config/GET_staging_security_groups_response.json") .build()) .build()); this.securityGroups .listStagingDefaults(ListSecurityGroupStagingDefaultsRequest.builder() .build()) .as(StepVerifier::create) .expectNext(ListSecurityGroupStagingDefaultsResponse.builder() .totalPages(1) .totalResults(1) .resource(SecurityGroupResource.builder() .metadata(Metadata.builder() .createdAt("2016-04-16T01:23:52Z") .id("c0bb3afb-ae01-4af0-96cf-a5b0d2dca894") .url("/v2/config/staging_security_groups/c0bb3afb-ae01-4af0-96cf-a5b0d2dca894") .build()) .entity(SecurityGroupEntity.builder() .name("name-570") .rule(RuleEntity.builder() .destination("198.41.191.47/1") .ports("8080") .protocol(UDP) .build()) .runningDefault(false) .stagingDefault(true) .build()) .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void removeSpace() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(DELETE).path("/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/spaces/ca8f04d1-bc2b-40ef-975e-fda2cc785c2a") .build()) .response(TestResponse.builder() .status(NO_CONTENT) .build()) .build()); this.securityGroups .removeSpace(RemoveSecurityGroupSpaceRequest.builder() .securityGroupId("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .spaceId("ca8f04d1-bc2b-40ef-975e-fda2cc785c2a") .build()) .as(StepVerifier::create) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void setRunning() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(PUT).path("/config/running_security_groups/test-security-group-default-id") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/config/PUT_{id}_running_security_groups_response.json") .build()) .build()); this.securityGroups .setRunningDefault(SetSecurityGroupRunningDefaultRequest.builder() .securityGroupId("test-security-group-default-id") .build()) .as(StepVerifier::create) .expectNext(SetSecurityGroupRunningDefaultResponse.builder() .metadata(Metadata.builder() .createdAt("2016-04-06T00:17:17Z") .id("9aa7ab9c-997f-4f87-be50-87105521881a") .url("/v2/config/running_security_groups/9aa7ab9c-997f-4f87-be50-87105521881a") .updatedAt("2016-04-06T00:17:17Z") .build()) .entity(SecurityGroupEntity.builder() .name("name-109") .rule(RuleEntity.builder() .destination("198.41.191.47/1") .ports("8080") .protocol(UDP) .build()) .runningDefault(true) .stagingDefault(false) .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void setStaging() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(PUT).path("/config/staging_security_groups/test-security-group-default-id") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/config/PUT_{id}_staging_security_groups_response.json") .build()) .build()); this.securityGroups .setStagingDefault(SetSecurityGroupStagingDefaultRequest.builder() .securityGroupId("test-security-group-default-id") .build()) .as(StepVerifier::create) .expectNext(SetSecurityGroupStagingDefaultResponse.builder() .metadata(Metadata.builder() .createdAt("2016-04-16T01:23:52Z") .id("50165fce-6c41-4c35-a4d8-3858ee217d36") .url("/v2/config/staging_security_groups/50165fce-6c41-4c35-a4d8-3858ee217d36") .updatedAt("2016-04-16T01:23:52Z") .build()) .entity(SecurityGroupEntity.builder() .name("name-567") .rule(RuleEntity.builder() .destination("198.41.191.47/1") .ports("8080") .protocol(UDP) .build()) .runningDefault(false) .stagingDefault(true) .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void update() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(PUT).path("/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .payload("fixtures/client/v2/security_groups/PUT_{id}_request.json") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/client/v2/security_groups/PUT_{id}_response.json") .build()) .build()); this.securityGroups .update(UpdateSecurityGroupRequest.builder() .name("new_name") .rules() .securityGroupId("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .build()) .as(StepVerifier::create) .expectNext(UpdateSecurityGroupResponse.builder() .metadata(Metadata.builder() .createdAt("2016-06-08T16:41:21Z") .id("1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .updatedAt("2016-06-08T16:41:21Z") .url("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159") .build()) .entity(SecurityGroupEntity.builder() .name("new_name") .rules() .runningDefault(false) .stagingDefault(false) .spacesUrl("/v2/security_groups/1452e164-0c3e-4a6c-b3c3-c40ad9fd0159/spaces") .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } }
44.95422
154
0.543805
29d5b34da6a09652b5985301b44f0c3bfe46d1c9
748
package com.rros.logmeinbasicdeck.dto; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.rros.logmeinbasicdeck.model.CardValue; import com.rros.logmeinbasicdeck.model.Suit; @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public record SuitCardValue<U extends Suit<U>, V extends CardValue<V>>(U suit, V cardValue) implements Comparable<SuitCardValue<U, V>> { @Override public int compareTo(SuitCardValue<U, V> o) { int i = suit.compareTo(o.suit); if (i == 0) { // XXX 2020-12-15 rosr descending card value order return -1 * cardValue.compareTo(o.cardValue); } return i; } }
37.4
128
0.63369
3b7c6c6e4911df77df626499d8b9d61bb14cd087
9,904
package com.spring.learn.common.utils; import java.io.Serializable; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; /** * 布隆过滤器的实现类 * 定义:http://en.wikipedia.org/wiki/Bloom_filter * https://my.oschina.net/LucasZhu/blog/1813110 * * @param <E> E指定了要插入过滤器中的元素的类型,eg,String Integer * @author Magnus Skjegstad <magnus@skjegstad.com> * @translator xiaoye */ public class BloomFilter<E> implements Serializable { private static final long serialVersionUID = -2326638072608273135L; private BitSet bitset; private int bitSetSize; private double bitsPerElement; /** * 能够添加的元素的最大个数 */ private int expectedNumberOfFilterElements; /** * 过滤器容器中元素的实际数量 */ private int numberOfAddedElements; /** * 哈希函数的个数 */ private int k; /** * 存储哈希值的字符串的编码方式 */ static final Charset charset = Charset.forName("UTF-8"); /** * 在大多数情况下,MD5提供了较好的散列精确度。如有必要,可以换成 SHA1算法 */ static final String hashName = "MD5"; /** * MessageDigest类用于为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法 */ static final MessageDigest digestFunction; // 初始化 MessageDigest 的摘要算法对象 static { MessageDigest tmp; try { tmp = java.security.MessageDigest.getInstance(hashName); } catch (NoSuchAlgorithmException e) { tmp = null; } digestFunction = tmp; } /** * 构造一个空的布隆过滤器. 过滤器的长度为c*n * * @param c 表示每个元素占有多少位 * @param n 表示过滤器能添加的最大元素数量 * @param k 表示需要使用的哈希函数的个数 */ public BloomFilter(double c, int n, int k) { this.expectedNumberOfFilterElements = n; this.k = k; this.bitsPerElement = c; this.bitSetSize = (int) Math.ceil(c * n); numberOfAddedElements = 0; this.bitset = new BitSet(bitSetSize); } /** * 构造一个空的布隆过滤器。最优哈希函数的个数将由过滤器的总大小和期望元素个数来确定。 * * @param bitSetSize 指定了过滤器的总大小 * @param expectedNumberOElements 指定了过滤器能添加的最大的元素数量 */ public BloomFilter(int bitSetSize, int expectedNumberOElements) { this(bitSetSize / (double) expectedNumberOElements, expectedNumberOElements, (int) Math.round((bitSetSize / (double) expectedNumberOElements) * Math.log(2.0))); } /** * 通过指定误报率来构造一个过滤器。 * 每个元素所占的位数和哈希函数的数量会根据误报率来得出。 * * @param falsePositiveProbability 所期望误报率. * @param expectedNumberOfElements 要添加的元素的数量 */ public BloomFilter(double falsePositiveProbability, int expectedNumberOfElements) { // c = k/ln(2) this(Math.ceil(-(Math.log(falsePositiveProbability) / Math.log(2))) / Math.log(2), expectedNumberOfElements, // k = ln(2)m/n (int) Math.ceil(-(Math.log(falsePositiveProbability) / Math.log(2)))); } /** * 根据旧过滤器的数据,重新构造一个新的过滤器 * * @param bitSetSize 指定了过滤器所需位的大小 * @param expectedNumberOfFilterElements 指定了过滤器所能添加的元素的最大数量 * to contain. * @param actualNumberOfFilterElements 指定了原来过滤器的数据的数量 * <code>filterData</code> BitSet. * @param filterData 原有过滤器中的BitSet对象 */ public BloomFilter(int bitSetSize, int expectedNumberOfFilterElements, int actualNumberOfFilterElements, BitSet filterData) { this(bitSetSize, expectedNumberOfFilterElements); this.bitset = filterData; this.numberOfAddedElements = actualNumberOfFilterElements; } /** * 根据字符串的内容生成摘要 * * @param val 字符串的内容 * @param charset 输入数据的编码方式 * @return 输出为一个long类型 */ public static long createHash(String val, Charset charset) { return createHash(val.getBytes(charset)); } /** * 根据字符串内容生成摘要 * * @param val 指定了输入的字符串。默认的编码为 UTF-8 * @return 输出为一个long类型 */ public static long createHash(String val) { return createHash(val, charset); } /** * 根据字节数组生成摘要 * * @param data 输入数据 * @return 输出为long类型的摘要 */ public static long createHash(byte[] data) { long h = 0; byte[] res; synchronized (digestFunction) { res = digestFunction.digest(data); } for (int i = 0; i < 4; i++) { h <<= 8; h |= ((int) res[i]) & 0xFF; } return h; } /** * 重写equals方法 */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BloomFilter<E> other = (BloomFilter<E>) obj; if (this.expectedNumberOfFilterElements != other.expectedNumberOfFilterElements) { return false; } if (this.k != other.k) { return false; } if (this.bitSetSize != other.bitSetSize) { return false; } if (this.bitset != other.bitset) { return this.bitset != null && this.bitset.equals(other.bitset); } return true; } /** * 重写了hashCode方法 */ @Override public int hashCode() { int hash = 7; hash = 61 * hash + (this.bitset != null ? this.bitset.hashCode() : 0); hash = 61 * hash + this.expectedNumberOfFilterElements; hash = 61 * hash + this.bitSetSize; hash = 61 * hash + this.k; return hash; } /** * 根据最大元素数量和过滤器的大小来计算误报率。 * 方法的返回值为误报率。如果插入的元素个数小于最大值,则误报率会比返回值要小。 * * @return 期望的误报率. */ public double expectedFalsePositiveProbability() { return getFalsePositiveProbability(expectedNumberOfFilterElements); } /** * 通过插入的元素数量和过滤器容器大小来计算实际的误报率。 * * @param numberOfElements 插入的元素的个数. * @return 误报率. */ public double getFalsePositiveProbability(double numberOfElements) { // (1 - e^(-k * n / m)) ^ k return Math.pow((1 - Math.exp(-k * numberOfElements / (double) bitSetSize)), k); } /** * 通过实际插入的元素数量和过滤器容器大小来计算实际的误报率。 * * @return 误报率. */ public double getFalsePositiveProbability() { return getFalsePositiveProbability(numberOfAddedElements); } /** * 返回哈希函数的个数 k * * @return k. */ public int getK() { return k; } /** * 清空过滤器元素 */ public void clear() { bitset.clear(); numberOfAddedElements = 0; } /** * 向过滤器中添加元素。 * 添加的元素的toString()方法将会被调用,返回的字符串作为哈希函数的输出。 * * @param element 要添加的元素 */ public void add(E element) { long hash; String valString = element.toString(); for (int x = 0; x < k; x++) { hash = createHash(valString + Integer.toString(x)); hash = hash % (long) bitSetSize; bitset.set(Math.abs((int) hash), true); } numberOfAddedElements++; } /** * 添加一个元素集合到过滤器中 * * @param c 元素集合. */ public void addAll(Collection<? extends E> c) { for (E element : c) { add(element); } } /** * 用来判断元素是否在过滤器中。如果已存在,返回 true。 * * @param element 要检查的元素. * @return 如果估计该元素已存在,则返回true */ public boolean contains(E element) { long hash; String valString = element.toString(); for (int x = 0; x < k; x++) { hash = createHash(valString + Integer.toString(x)); hash = hash % (long) bitSetSize; if (!bitset.get(Math.abs((int) hash))) { return false; } } return true; } /** * 判断一个集合中的元素是否都在过滤器中。 * * @param c 要检查的元素集合 * @return 如果集合所有的元素都在过滤器中,则返回true。 */ public boolean containsAll(Collection<? extends E> c) { for (E element : c) { if (!contains(element)) { return false; } } return true; } /** * 得到某一位的值 * * @param bit bit的位置. * @return 如果该位被设置,则返回true。 */ public boolean getBit(int bit) { return bitset.get(bit); } /** * 设置过滤器某一位的值 * * @param bit 要设置的位置. * @param value true表示已经成功设置。false表示改为被清除。 */ public void setBit(int bit, boolean value) { bitset.set(bit, value); } /** * 返回存放信息的位数组. * * @return 位数组. */ public BitSet getBitSet() { return bitset; } /** * 得到过滤器中位数组个大小。 * * @return 数组大小. */ public int size() { return this.bitSetSize; } /** * 返回已添加的元素的个数 * * @return 元素个数. */ public int count() { return this.numberOfAddedElements; } /** * 得到能添加的元素的最大数量 * * @return 最大数量. */ public int getExpectedNumberOfElements() { return expectedNumberOfFilterElements; } /** * 得到每个元素占用的位的个数的期望值 * * @return 每个元素占用的位数 */ public double getExpectedBitsPerElement() { return this.bitsPerElement; } /** * 得到每个元素占用位数的实际值 * * @return 每个元素占用的位数. */ public double getBitsPerElement() { return this.bitSetSize / (double) numberOfAddedElements; } public static void main(String[] args) { BloomFilter bloomFilter = new BloomFilter<String>(8, 10000000, 5); bloomFilter.add("123123"); //1561702408643 //1561702422561 System.out.println(bloomFilter.contains("12312")); //取得指定时区的时间 System.out.println(System.currentTimeMillis()); TimeZone zone = TimeZone.getTimeZone("GMT - 4:00"); Calendar cal = Calendar.getInstance(zone); System.out.println(cal.getTimeInMillis()); } }
24.575682
168
0.560683
ac77869958be1f71e1d9bad9bf7c61edc12a76e1
4,152
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.quarkus.component.debezium.common.it.sqlserver; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; import org.apache.camel.quarkus.component.debezium.common.it.AbstractDebeziumTest; import org.apache.camel.quarkus.component.debezium.common.it.Record; import org.apache.camel.quarkus.component.debezium.common.it.Type; import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; @QuarkusTest @QuarkusTestResource(DebeziumSqlserverTestResource.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class DebeziumSqlserverTest extends AbstractDebeziumTest { private static final Logger LOG = Logger.getLogger(DebeziumSqlserverTest.class); //has to be constant and has to be equal to Type.mysql.getJdbcProperty public static final String PROPERTY_JDBC = "sqlserver_jdbc"; private static Connection connection; public DebeziumSqlserverTest() { super(Type.sqlserver); } @BeforeAll public static void setUp() throws SQLException { final String jdbcUrl = System.getProperty(Type.sqlserver.getPropertyJdbc()); if (jdbcUrl != null) { connection = DriverManager.getConnection(jdbcUrl); } else { LOG.warn("Container is not running. Connection is not created."); } } @Before public void before() { org.junit.Assume.assumeTrue(connection != null); } @AfterAll public static void cleanUp() throws SQLException { if (connection != null) { connection.close(); } } @Override protected Connection getConnection() { return connection; } @Override protected String getCompanyTableName() { return "Test." + super.getCompanyTableName(); } @Test @Order(0) @EnabledIfSystemProperty(named = PROPERTY_JDBC, matches = ".*") public void testReceiveInitCompany() { //receive first record (operation r) for the init company - using larger timeout Response response = receiveResponse("/receiveAsRecord"); response.then() .statusCode(200); Record record = response.getBody().as(Record.class); Assert.assertEquals("r", record.getOperation()); Assert.assertEquals("Struct{NAME=init,CITY=init}", record.getValue()); } @Test @Order(1) @EnabledIfSystemProperty(named = PROPERTY_JDBC, matches = ".*") public void testInsert() throws SQLException { super.testInsert(); } @Test @Order(2) @EnabledIfSystemProperty(named = PROPERTY_JDBC, matches = ".*") public void testUpdate() throws SQLException { super.testUpdate(); } @Test @Order(3) @EnabledIfSystemProperty(named = PROPERTY_JDBC, matches = ".*") public void testDelete() throws SQLException { super.testDelete(); } }
33.216
88
0.713391
2a223e9afb2cf10c586611fe7e6cb246265a6ad8
2,264
/* * Copyright (C) 2018 Intel Corporation * SPDX-License-Identifier: Apache-2.0 */ package oms.sample.p2p; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TextView; public class ChatFragment extends Fragment implements View.OnClickListener { private ScrollView chatSV; private TextView chatTV; private EditText chatET; private Button sendBtn; private ChatFragmentListener mListener; private StringBuilder chatHistory = new StringBuilder(); public ChatFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mView = inflater.inflate(R.layout.fragment_chat, container, false); chatSV = mView.findViewById(R.id.chat_history); chatTV = mView.findViewById(R.id.chat_history_content); chatET = mView.findViewById(R.id.chat_content); sendBtn = mView.findViewById(R.id.send_btn); sendBtn.setOnClickListener(this); updateMessageView(); return mView; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof ChatFragmentListener) { mListener = (ChatFragmentListener) context; } else { throw new RuntimeException(context.toString() + " must implement LoginFragmentListener"); } } @Override public void onClick(View v) { mListener.onSendMessage(chatET.getText().toString()); chatET.setText(""); } void onMessage(String peerId, String message) { String chat = "\n" + peerId + ": " + message; chatHistory.append(chat); updateMessageView(); } private void updateMessageView() { if (getActivity() != null) { getActivity().runOnUiThread(() -> chatTV.setText(chatHistory.toString())); } } public interface ChatFragmentListener { void onSendMessage(String message); } }
29.025641
86
0.674912
b9707aadfc35393bf436f4aa130b49dbd70b0105
9,167
package softuni.jsonexer.service.impl; import org.modelmapper.ModelMapper; import org.modelmapper.TypeMap; import org.springframework.stereotype.Service; import softuni.jsonexer.domain.dto.binding.json.ProductSeedDto; import softuni.jsonexer.domain.dto.binding.xml.ProductImportDto; import softuni.jsonexer.domain.dto.binding.xml.ProductImportRootDto; import softuni.jsonexer.domain.dto.views.json_views.ProductInRangeDto; import softuni.jsonexer.domain.dto.views.json_views.UserBuyerDto; import softuni.jsonexer.domain.dto.views.json_views.UserSellerDto; import softuni.jsonexer.domain.dto.views.xml_views.ProductInRangeRootDto; import softuni.jsonexer.domain.dto.views.xml_views.ProductsInRangeXmlViewDto; import softuni.jsonexer.domain.models.Category; import softuni.jsonexer.domain.models.Product; import softuni.jsonexer.domain.models.User; import softuni.jsonexer.repository.CategoryRepository; import softuni.jsonexer.repository.ProductRepository; import softuni.jsonexer.repository.UserRepository; import softuni.jsonexer.service.ProductService; import softuni.jsonexer.util.ValidatorUtil; import javax.transaction.Transactional; import java.math.BigDecimal; import java.util.*; @Service @Transactional public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; private final UserRepository userRepository; private final CategoryRepository categoryRepository; private final ValidatorUtil validatorUtil; private final ModelMapper modelMapper; public ProductServiceImpl(ProductRepository productRepository, UserRepository userRepository, CategoryRepository categoryRepository, ValidatorUtil validatorUtil, ModelMapper modelMapper) { this.productRepository = productRepository; this.userRepository = userRepository; this.categoryRepository = categoryRepository; this.validatorUtil = validatorUtil; this.modelMapper = modelMapper; } @Override public void seedProductsFromJson(ProductSeedDto[] productSeedDtos) { for (ProductSeedDto productSeedDto : productSeedDtos) { productSeedDto.setSeller(this.getRandomSeller()); productSeedDto.setBuyer(this.getRandomBuyer()); productSeedDto.setCategories(this.getRandomCategories()); if (!this.validatorUtil.isValid(productSeedDto)) { this.validatorUtil.violations(productSeedDto) .forEach(v -> System.out.println(v.getMessage())); continue; } Product product = this.productRepository .findByName(productSeedDto.getName()) .orElse(null); if (product == null) { product = this.modelMapper.map(productSeedDto, Product.class); this.productRepository.saveAndFlush(product); } } } @Override public void seedProductsFromXml(ProductImportRootDto productImportRootDto) { for (ProductImportDto productDto : productImportRootDto.getProductImportDtos()) { productDto.setSeller(this.getRandomSeller()); productDto.setBuyer(this.getRandomBuyer()); productDto.setCategories(this.getRandomCategories()); if (!this.validatorUtil.isValid(productDto)) { this.validatorUtil.violations(productDto) .forEach(v -> System.out.println(v.getMessage())); continue; } Product product = this.productRepository .findByName(productDto.getName()) .orElse(null); if (product == null) { product = this.modelMapper.map(productDto, Product.class); this.productRepository.saveAndFlush(product); } } } private User getRandomSeller() { Random random = new Random(); int id = 0; while (this.userRepository.findById(id).orElse(null) == null) { id = random.nextInt((int) this.userRepository.count() - 1) + 1; } return this.userRepository.findById(id).get(); } private User getRandomBuyer() { Random random = new Random(); int id = random.nextInt((int) this.userRepository.count() - 1) + 1; if (id % 4 == 0) { return null; } return this.userRepository.findById(id).orElse(null); } private Category getRandomCategory() { Random random = new Random(); int id = random.nextInt((int) this.categoryRepository.count() - 1) + 1; return this.categoryRepository.findById(id).orElse(null); } private Set<Category> getRandomCategories() { Set<Category> categories = new HashSet<>(); Random random = new Random(); int size = random.nextInt((int) this.categoryRepository.count() - 1) + 1; for (int i = 0; i < size; i++) { categories.add(getRandomCategory()); } return categories; } @Override public Object[] productsInRange(BigDecimal more, BigDecimal less) { List<Product> products = this.productRepository .findAllByPriceBetweenAndBuyerIsNullOrderByPrice(more, less); List<ProductInRangeDto> productInRangeDtos = new ArrayList<>(); List<ProductsInRangeXmlViewDto> productInRangeXmlDtos = new ArrayList<>(); for (Product product : products) { ProductInRangeDto productInRangeDto = this.modelMapper.map(product, ProductInRangeDto.class); productInRangeDto.setSeller(String.format("%s %s", product.getSeller().getFirstName(), product.getSeller().getLastName())); ProductsInRangeXmlViewDto productsInRangeXmlViewDto = this.modelMapper.map(product, ProductsInRangeXmlViewDto.class); productsInRangeXmlViewDto.setSeller(String.format("%s %s", product.getSeller().getFirstName(), product.getSeller().getLastName())); if (!validatorUtil.isValid(productInRangeDto) || !validatorUtil.isValid(productsInRangeXmlViewDto)) { System.out.println("Error! Invalid Data input."); continue; } productInRangeXmlDtos.add(productsInRangeXmlViewDto); productInRangeDtos.add(productInRangeDto); } ProductInRangeRootDto productInRangeRootDto = new ProductInRangeRootDto(); productInRangeRootDto.setProducts(productInRangeXmlDtos); Object[] results = new Object[2]; results[0] = productInRangeDtos; results[1] = productInRangeRootDto; return results; } @Override public Object[] successfullySoldProducts() { List<Product> products = this.productRepository.findAllBySellerIsNotNullAndBuyerIsNotNull(); TypeMap<Product, UserBuyerDto> buyerJsonViewMap = this.modelMapper.createTypeMap(Product.class, UserBuyerDto.class); buyerJsonViewMap.addMappings(m -> m.map(Product::getName, UserBuyerDto::setName)); buyerJsonViewMap.addMappings(m -> m.map(Product::getPrice, UserBuyerDto::setPrice)); buyerJsonViewMap.addMappings(m -> m.map(product -> product.getBuyer().getFirstName(), UserBuyerDto::setFirstName)); buyerJsonViewMap.addMappings(m -> m.map(product -> product.getBuyer().getLastName(), UserBuyerDto::setLastName));; TypeMap<Product, UserSellerDto> sellerJsonViewMap = this.modelMapper.createTypeMap(Product.class, UserSellerDto.class); sellerJsonViewMap.addMappings(m -> m.map(product -> product.getSeller().getFirstName(), (dest, value) -> dest.setFirstName((String) value))); sellerJsonViewMap.addMappings(m -> m.map(product -> product.getSeller().getLastName(), (dest, value) -> dest.setLastName((String) value))); sellerJsonViewMap.addMappings(m -> m.skip(UserSellerDto::setBuyers)); List<UserSellerDto> sellers = new ArrayList<>(); for (Product product : products) { UserSellerDto userSellerDto = sellers .stream() .filter( user -> user .getLastName() .equals(product.getSeller().getLastName())) .findFirst() .orElse(null); if (userSellerDto == null) { userSellerDto = sellerJsonViewMap.map(product); } UserBuyerDto buyerDto = buyerJsonViewMap.map(product); userSellerDto.getBuyers().add(buyerDto); sellers.add(userSellerDto); } Object[] viewsResult = new Object[1]; viewsResult[0] = sellers; return viewsResult; } }
40.030568
106
0.636413
542ef214bb646e6b7d52e12f216e6f0000843c4f
2,923
package com.o3dr.services.android.lib.gcs.returnToMe; import android.os.Parcel; import android.support.annotation.IntDef; import com.o3dr.services.android.lib.coordinate.LatLongAlt; import com.o3dr.services.android.lib.drone.property.DroneAttribute; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by Fredia Huya-Kouadio on 9/22/15. */ public class ReturnToMeState implements DroneAttribute { @IntDef({STATE_IDLE, STATE_USER_LOCATION_UNAVAILABLE, STATE_USER_LOCATION_INACCURATE, STATE_WAITING_FOR_VEHICLE_GPS, STATE_UPDATING_HOME, STATE_ERROR_UPDATING_HOME}) @Retention(RetentionPolicy.SOURCE) public @interface ReturnToMeStates{} public static final int STATE_IDLE = 0; public static final int STATE_USER_LOCATION_UNAVAILABLE = 1; public static final int STATE_USER_LOCATION_INACCURATE = 2; public static final int STATE_WAITING_FOR_VEHICLE_GPS = 3; public static final int STATE_UPDATING_HOME = 4; public static final int STATE_ERROR_UPDATING_HOME = 5; private LatLongAlt originalHomeLocation; private LatLongAlt currentHomeLocation; @ReturnToMeStates private int state = STATE_IDLE; public ReturnToMeState(){} public ReturnToMeState(@ReturnToMeStates int state){ this.state = state; } @ReturnToMeStates public int getState() { return state; } public void setState(@ReturnToMeStates int state) { this.state = state; } public LatLongAlt getCurrentHomeLocation() { return currentHomeLocation; } public void setCurrentHomeLocation(LatLongAlt currentHomeLocation) { this.currentHomeLocation = currentHomeLocation; } public LatLongAlt getOriginalHomeLocation() { return originalHomeLocation; } public void setOriginalHomeLocation(LatLongAlt originalHomeLocation) { this.originalHomeLocation = originalHomeLocation; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.state); dest.writeParcelable(this.originalHomeLocation, 0); dest.writeParcelable(this.currentHomeLocation, 0); } protected ReturnToMeState(Parcel in) { @ReturnToMeStates final int temp = in.readInt(); this.state = temp; this.originalHomeLocation = in.readParcelable(LatLongAlt.class.getClassLoader()); this.currentHomeLocation = in.readParcelable(LatLongAlt.class.getClassLoader()); } public static final Creator<ReturnToMeState> CREATOR = new Creator<ReturnToMeState>() { public ReturnToMeState createFromParcel(Parcel source) { return new ReturnToMeState(source); } public ReturnToMeState[] newArray(int size) { return new ReturnToMeState[size]; } }; }
30.134021
91
0.721519
7154aa16957fd6bbd8d0785b6a12ed1870aed18b
2,055
package net.qb9.hades; import android.app.IntentService; import android.content.Intent; import android.util.Log; import android.app.NotificationManager; import android.os.Bundle; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.PendingIntent; import android.content.Context; import android.support.v4.app.NotificationCompat; import net.qb9.hades.push.R; public class GCMIntentService extends IntentService { public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GCMIntentService() { super("GCMIntentService"); } @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String messageType = gcm.getMessageType(intent); if ( ! extras.isEmpty() ) { if ( GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType) ) { String title = extras.getString("title", ""); String msg = extras.getString("msg", ""); sendNotification(title, msg, extras); } } GCMBroadcastReceiver.completeWakefulIntent(intent); } private void sendNotification(String title, String msg, Bundle extras) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); /* Intent notifIntent = new Intent(this, AppActivity.class); notifIntent.putExtras(extras); notifIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); */ } }
30.671642
122
0.775182
98e0aa0129a7a97f351600d10d2d5e163107fbc7
3,419
package crab.handler.impl; import crab.Crab; import crab.constant.CrabConst; import crab.handler.HttpHandler; import crab.http.HttpRequest; import crab.http.HttpResponse; import crab.http.HttpStatus; import crab.kit.IOKit; import crab.kit.PathKit; import java.io.*; import java.net.URLDecoder; import java.util.List; import java.util.stream.Stream; /** * 基于磁盘静态文件实现的Handler */ public class AssetHandler implements HttpHandler { private File rootFile; private String rootPath; public AssetHandler(File rootFile) { this.rootFile = rootFile; this.rootPath = rootFile.getPath(); } public AssetHandler(String rootPath) { this(new File(rootPath)); } @Override public HttpResponse handle(HttpRequest request) { String uri = request.getUri(); try { uri = URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { uri = uri.replace("%20", " "); } System.out.println("Request URL > " + uri); uri = PathKit.fixPath(uri); if (uri.equals("/")) { uri = "/" + CrabConst.DEFAULT_ROOTFILE; } //处理rootPath if (rootPath == null) { rootPath = rootFile.getAbsolutePath(); if (rootPath.endsWith("/") || rootPath.endsWith(".")) { rootPath = rootPath.substring(0, rootPath.length() - 1); } } //初始化web服务器工作空间 initWorkSpace(rootPath); File file = new File(rootFile, uri); if (file.exists() && !file.isDirectory()) { try { //返回此抽象路径名的规范路径名字符串 String requestPath = file.getCanonicalPath(); if (requestPath.endsWith("/")) { requestPath = requestPath.substring(0, requestPath.length() - 1); } if (!requestPath.startsWith(rootPath)) { return new HttpResponse().reason(HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST.toString()); } HttpResponse res = new HttpResponse(HttpStatus.OK, new FileInputStream(file)); res.setLength(file.length()); return res; } catch (IOException e) { return new HttpResponse().reason(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR.toString()); } } if (!file.exists()) { return new HttpResponse().reason(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.toString()); } return null; } private static void initWorkSpace(String rootPath) { System.out.println("Crab's WorkSpace is at :: " + rootPath); String resourcePath = ""; if (Crab.isTest() == true) { resourcePath = Crab.class.getResource("/workspace").getPath(); IOKit.copyFile(resourcePath, rootPath); } else { File rootfile = new File(rootPath); rootfile.mkdirs(); List<InputStream> streamList = IOKit.getInputStreamList("/workspace/crab.gif", "/workspace/favicon.ico", "/workspace/index.html"); IOKit.copyJarFile(streamList.get(0), new File(rootPath + "/crab.gif")); IOKit.copyJarFile(streamList.get(1), new File(rootPath + "/favicon.ico")); IOKit.copyJarFile(streamList.get(2), new File(rootPath + "/index.html")); } } }
31.081818
142
0.589646
9c33e0a409995fbe394de53fbab826d906d8ff03
1,375
/* * Copyright (C) 2010-2021 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.report.impl.activity; import com.evolveum.midpoint.repo.common.ObjectResolver; import com.evolveum.midpoint.repo.common.activity.run.AbstractActivityRun; import com.evolveum.midpoint.report.impl.ReportServiceImpl; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.CommonException; /** * Contains common functionality for executions of collection export report-related activities. * This is an experiment - using object composition instead of inheritance. */ class ExportCollectionActivitySupport extends ExportActivitySupport { ExportCollectionActivitySupport(AbstractActivityRun<?, ?, ?> activityRun, ReportServiceImpl reportService, ObjectResolver resolver, AbstractReportWorkDefinition workDefinition) { super(activityRun, reportService, resolver, workDefinition); } @Override public void stateCheck(OperationResult result) throws CommonException { MiscUtil.stateCheck(report.getObjectCollection() != null, "Only collection-based reports are supported here"); super.stateCheck(result); } }
40.441176
118
0.786909
b8489072481fa200dd7c1405a6c2f4b94a7f0f3d
5,101
/* BAD_OPERATION.java -- Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.omg.CORBA; import java.io.Serializable; /** * Means that the object exists but does not support the operation that was * invoked on it. * * In GNU Classpath, this exception may have the following Minor codes: * * <table border="1"> * <tr> * <th>Hex</th> * <th>Dec</th> * <th>Minor</th> * <th>Name</th> * <th>Case</th> * </tr> * <tr> * <td>47430000</td> * <td>1195573248 </td> * <td>0</td> * <td>Method</td> * <td> The remote side requested to invoke the method that is not available on * that target (client and server probably disagree in the object definition). * This code is set when the problem arises in the Classpath core; the idlj and * rmic may generate the user code that sets 0x0 or other value.</td> * </tr> * <tr> * <td>47430009</td> * <td>1195573257</td> * <td>9</td> * <td>Any</td> * <td> Attempt to extract from the Any value of the different type that was * stored into that Any. </td> * </tr> * <tr> * <td>4743000a</td> * <td>1195573258</td> * <td>10</td> * <td>Activation</td> * <td>Failed to activate the inactive object due any reason.</td> * </tr> * <tr> * <td>4743000b</td> * <td>1195573259</td> * <td>11</td> * <td>Policy</td> * <td> The policies, applying to ORB or POA prevent the requested operation. * </td> * </tr> * <tr> * <td>4743000c</td> * <td>1195573260</td> * <td>12</td> * <td>Socket</td> * <td> Socket related errors like failure to open socket on the expected port.</td> * </tr> * <tr> * <td>4743000e</td> * <td>1195573262</td> * <td>14</td> * <td>Enumeration</td> * <td> The passed value for enumeration is outside the valid range for that * enumeration. </td> * </tr> * <tr> * <td>4743000f</td> * <td>1195573263</td> * <td>15</td> * <td>PolicyType</td> * <td> The passed policy code is outside the valid range of the possible * policies for the given policy type. </td> * </tr> * </table> * * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) */ public final class BAD_OPERATION extends SystemException implements Serializable { /** * Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 1654621651720499682L; /** * Creates a BAD_OPERATION with the default minor code of 0, completion state * COMPLETED_NO and the given explaining message. * * @param message the explaining message. */ public BAD_OPERATION(String message) { super(message, 0, CompletionStatus.COMPLETED_NO); } /** * Creates BAD_OPERATION with the default minor code of 0 and a completion * state COMPLETED_NO. */ public BAD_OPERATION() { super("", 0, CompletionStatus.COMPLETED_NO); } /** * Creates a BAD_OPERATION exception with the specified minor code and * completion status. * * @param minor additional error code. * @param completed the method completion status. */ public BAD_OPERATION(int minor, CompletionStatus completed) { super("", minor, completed); } /** * Created BAD_OPERATION exception, providing full information. * * @param reason explaining message. * @param minor additional error code (the "minor"). * @param completed the method completion status. */ public BAD_OPERATION(String reason, int minor, CompletionStatus completed) { super(reason, minor, completed); } }
30.005882
84
0.706332
21d1155f1df371f2af3bd9e604698fb0ee2b733d
1,558
package com.idunnolol.moviesdemo.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import com.idunnolol.moviesdemo.R; import java.util.ArrayList; import java.util.List; /** * Allows SlidingPairViews to operate without having to layout constantly */ public class SlidingListView extends ListView { public SlidingListView(Context context) { super(context); } public SlidingListView(Context context, AttributeSet attrs) { super(context, attrs); } public SlidingListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } // For performance reasons, we want to set the slide directly on the views instead of // setting the slide in the adapter and notifying that the dataset changed. public void setSlide(float slide) { if (getWidth() == 0) { return; } for (SlidingPairView child : getAllSlidingPairViewChildren()) { child.setSlide(slide); } } public void setUseHardwareLayers(boolean useHardwareLayers) { for (SlidingPairView child : getAllSlidingPairViewChildren()) { child.setUseHardwareLayers(useHardwareLayers); } } private List<SlidingPairView> getAllSlidingPairViewChildren() { List<SlidingPairView> children = new ArrayList<SlidingPairView>(); int childCount = getChildCount(); for (int a = 0; a < childCount; a++) { View view = getChildAt(a).findViewById(R.id.sliding_pair); if (view != null) { children.add((SlidingPairView) view); } } return children; } }
25.540984
86
0.743902
1079b5069f4f026978f41cf3e908fef97cf63741
445
package com.walkhub.walkhub.domain.exercise.presentation.dto.response; import lombok.Builder; import lombok.Getter; import java.util.List; @Getter @Builder public class QueryExerciseAnalysisResponse { private final List<Integer> walkCountList; private final Integer dailyWalkCountGoal; private final Integer walkCount; private final Double calorie; private final Integer distance; private final Double exerciseTime; }
24.722222
70
0.791011
c1d50df824d3932765aeebf5c1004453158d0673
2,475
package com.gotruck.interview.test.models.domains; import com.gotruck.interview.test.models.enums.PurchaseOrderStatus; import java.util.Date; public class PurchaseOrderImpl implements PurchaseOrder { private String orderID; private Date orderDate; private PurchaseOrderStatus orderStatus; private User buyer; public PurchaseOrderImpl() { } public PurchaseOrderImpl(String orderID, Date orderDate, PurchaseOrderStatus orderStatus, User buyer) { this.orderID = orderID; this.orderDate = orderDate; this.orderStatus = orderStatus; this.buyer = buyer; } public static PurchaseOrderImplBuilder builder() { return new PurchaseOrderImplBuilder(); } @Override public String getOrderID() { return this.orderID; } @Override public Date getOrderDate() { return this.orderDate; } @Override public PurchaseOrderStatus getOrderStatus() { return this.orderStatus; } @Override public User getBuyer() { return this.buyer; } public void setOrderID(String orderID) { this.orderID = orderID; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public void setOrderStatus(PurchaseOrderStatus orderStatus) { this.orderStatus = orderStatus; } public void setBuyer(User buyer) { this.buyer = buyer; } public static class PurchaseOrderImplBuilder { private String orderID; private Date orderDate; private PurchaseOrderStatus orderStatus; private User buyer; PurchaseOrderImplBuilder() { } public PurchaseOrderImpl build() { return new PurchaseOrderImpl(); } public String toString() { return "PurchaseOrderImpl.PurchaseOrderImplBuilder()"; } public PurchaseOrderImplBuilder orderID(String orderID) { this.orderID = orderID; return this; } public PurchaseOrderImplBuilder orderDate(Date orderDate) { this.orderDate = orderDate; return this; } public PurchaseOrderImplBuilder orderStatus(PurchaseOrderStatus orderStatus) { this.orderStatus = orderStatus; return this; } public PurchaseOrderImplBuilder buyer(User buyer) { this.buyer = buyer; return this; } } }
24.50495
107
0.638788
a77e4a88bdfa550d77443d7ce77cdd22daa7e7fa
1,010
package hard.other; public class LargestRectangleArea { int[] heights; int max=-1; public int largestRectangleArea(int[] heights) { if(heights.length==0)return 0; this.heights=heights; split(0, heights.length-1); return max; } void split(int left,int right){ if(left<0||left>=heights.length||right<0||right>=heights.length)return; if(left>right)return; int lowIdx=0; long low=Long.MAX_VALUE; for(int i=left;i<=right;i++){ if(heights[i]<low){ lowIdx=i; low=heights[i]; } } long area=((long)low)*(right-left+1); max=Math.max(max,(int)area); split(left, lowIdx-1); split(lowIdx+1,right); } public static void main(String[] args) { LargestRectangleArea solution=new LargestRectangleArea(); int[] heights={0,2147483647}; System.out.println(solution.largestRectangleArea(heights)); } }
25.897436
79
0.572277