repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
logic-ng/LogicNG
src/main/java/org/logicng/io/writers/FormulaDotFileWriter.java
8963
/////////////////////////////////////////////////////////////////////////// // __ _ _ ________ // // / / ____ ____ _(_)____/ | / / ____/ // // / / / __ \/ __ `/ / ___/ |/ / / __ // // / /___/ /_/ / /_/ / / /__/ /| / /_/ / // // /_____/\____/\__, /_/\___/_/ |_/\____/ // // /____/ // // // // The Next Generation Logic Library // // // /////////////////////////////////////////////////////////////////////////// // // // Copyright 2015-20xx Christoph Zengler // // // // 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.logicng.io.writers; import org.logicng.formulas.BinaryOperator; import org.logicng.formulas.Formula; import org.logicng.formulas.Literal; import org.logicng.formulas.NAryOperator; import org.logicng.formulas.Not; import org.logicng.formulas.PBConstraint; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; /** * A dot file writer for a formula. Writes the internal data structure of the formula to a dot file. * @version 1.1 * @since 1.0 */ public final class FormulaDotFileWriter { /** * Private constructor. */ private FormulaDotFileWriter() { // Intentionally left empty. } /** * Writes a given formula's internal data structure as a dot file. * @param fileName the file name of the dot file to write * @param formula the formula * @param alignLiterals indicates whether all literals should be aligned at the same vertical level * @throws IOException if there was a problem writing the file */ public static void write(final String fileName, final Formula formula, boolean alignLiterals) throws IOException { write(new File(fileName.endsWith(".dot") ? fileName : fileName + ".dot"), formula, alignLiterals); } /** * Writes a given formula's internal data structure as a dot file. * @param file the file of the dot file to write * @param formula the formula * @param alignLiterals indicates whether all literals should be aligned at the same vertical level * @throws IOException if there was a problem writing the file */ public static void write(final File file, final Formula formula, boolean alignLiterals) throws IOException { final StringBuilder sb = new StringBuilder(String.format("digraph G {%n")); final Map<Formula, Integer> ids = new HashMap<>(); if (alignLiterals && !formula.literals().isEmpty()) { sb.append(String.format("{ rank = same;%n")); } int id = 0; for (final Literal lit : formula.literals()) { ids.put(lit, id); sb.append(" id").append(id).append(" [shape=box, label=\""). append(lit.phase() ? lit.name() : "¬" + lit.name()).append(String.format("\"];%n")); id++; } if (alignLiterals && !formula.literals().isEmpty()) { sb.append(String.format("}%n")); } generateDotString(formula, sb, ids); sb.append(String.format("}%n")); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { writer.append(sb); writer.flush(); } } /** * Generates the dot string for a formula * @param formula the formula * @param sb the current string builder * @param ids the current ID mapping */ private static void generateDotString(final Formula formula, final StringBuilder sb, final Map<Formula, Integer> ids) { switch (formula.type()) { case FALSE: sb.append(String.format(" false;%n")); break; case TRUE: sb.append(String.format(" true;%n")); break; case LITERAL: break; case PBC: final int id = ids.size(); ids.put(formula, id); sb.append(" id").append(id).append(" [label=\"").append(formula).append(String.format("\"];%n")); for (final Formula operand : ((PBConstraint) formula).operands()) { sb.append(" id").append(id).append(" -> id").append(ids.get(operand)).append(String.format(";%n")); } break; case NOT: generateNotDotString((Not) formula, sb, ids); break; case IMPL: generateBinaryDotString((BinaryOperator) formula, sb, ids, "⇒", true); break; case EQUIV: generateBinaryDotString((BinaryOperator) formula, sb, ids, "⇔", true); break; case AND: generateNaryDotString((NAryOperator) formula, sb, ids, "∧"); break; case OR: generateNaryDotString((NAryOperator) formula, sb, ids, "∨"); break; default: throw new IllegalArgumentException("Cannot write the formula type " + formula.type()); } } private static void generateNotDotString(final Not not, final StringBuilder sb, final Map<Formula, Integer> ids) { int id; if (!ids.containsKey(not.operand())) { generateDotString(not.operand(), sb, ids); } id = ids.size(); ids.put(not, id); sb.append(" id").append(id).append(String.format(" [label=\"¬\"];%n")); sb.append(" id").append(id).append(" -> id").append(ids.get(not.operand())).append(String.format(";%n")); } private static void generateBinaryDotString(final BinaryOperator formula, final StringBuilder sb, final Map<Formula, Integer> ids, String op, boolean directions) { if (!ids.containsKey(formula.left())) { generateDotString(formula.left(), sb, ids); } if (!ids.containsKey(formula.right())) { generateDotString(formula.right(), sb, ids); } final int id = ids.size(); ids.put(formula, id); sb.append(" id").append(id).append(" [label=\"").append(op).append(String.format("\"];%n")); sb.append(" id").append(id).append(" -> id").append(ids.get(formula.left())); sb.append(directions ? String.format(" [label=\"l\"];%n") : String.format(";%n")); sb.append(" id").append(id).append(" -> id").append(ids.get(formula.right())); sb.append(directions ? String.format(" [label=\"r\"];%n") : String.format(";%n")); } private static void generateNaryDotString(final NAryOperator formula, final StringBuilder sb, final Map<Formula, Integer> ids, final String op) { for (final Formula operand : formula) { if (!ids.containsKey(operand)) { generateDotString(operand, sb, ids); } } final int id = ids.size(); ids.put(formula, id); sb.append(" id").append(id).append(" [label=\"").append(op).append(String.format("\"];%n")); for (final Formula operand : formula) { sb.append(" id").append(id).append(" -> id").append(ids.get(operand)).append(String.format(";%n")); } } }
apache-2.0
k21/buck
src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java
26621
/** * Autogenerated by Thrift Compiler (0.10.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.facebook.buck.distributed.thrift; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-08-18") public class FetchRuleKeyLogsRequest implements org.apache.thrift.TBase<FetchRuleKeyLogsRequest, FetchRuleKeyLogsRequest._Fields>, java.io.Serializable, Cloneable, Comparable<FetchRuleKeyLogsRequest> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("FetchRuleKeyLogsRequest"); private static final org.apache.thrift.protocol.TField RULE_KEYS_FIELD_DESC = new org.apache.thrift.protocol.TField("ruleKeys", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.protocol.TField REPOSITORY_FIELD_DESC = new org.apache.thrift.protocol.TField("repository", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField SCHEDULE_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("scheduleType", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField DISTRIBUTED_BUILD_MODE_ENABLED_FIELD_DESC = new org.apache.thrift.protocol.TField("distributedBuildModeEnabled", org.apache.thrift.protocol.TType.BOOL, (short)4); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new FetchRuleKeyLogsRequestStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new FetchRuleKeyLogsRequestTupleSchemeFactory(); public java.util.List<java.lang.String> ruleKeys; // optional public java.lang.String repository; // optional public java.lang.String scheduleType; // optional public boolean distributedBuildModeEnabled; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { RULE_KEYS((short)1, "ruleKeys"), REPOSITORY((short)2, "repository"), SCHEDULE_TYPE((short)3, "scheduleType"), DISTRIBUTED_BUILD_MODE_ENABLED((short)4, "distributedBuildModeEnabled"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // RULE_KEYS return RULE_KEYS; case 2: // REPOSITORY return REPOSITORY; case 3: // SCHEDULE_TYPE return SCHEDULE_TYPE; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED return DISTRIBUTED_BUILD_MODE_ENABLED; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments private static final int __DISTRIBUTEDBUILDMODEENABLED_ISSET_ID = 0; private byte __isset_bitfield = 0; private static final _Fields optionals[] = {_Fields.RULE_KEYS,_Fields.REPOSITORY,_Fields.SCHEDULE_TYPE,_Fields.DISTRIBUTED_BUILD_MODE_ENABLED}; public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.RULE_KEYS, new org.apache.thrift.meta_data.FieldMetaData("ruleKeys", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); tmpMap.put(_Fields.REPOSITORY, new org.apache.thrift.meta_data.FieldMetaData("repository", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.SCHEDULE_TYPE, new org.apache.thrift.meta_data.FieldMetaData("scheduleType", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.DISTRIBUTED_BUILD_MODE_ENABLED, new org.apache.thrift.meta_data.FieldMetaData("distributedBuildModeEnabled", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(FetchRuleKeyLogsRequest.class, metaDataMap); } public FetchRuleKeyLogsRequest() { } /** * Performs a deep copy on <i>other</i>. */ public FetchRuleKeyLogsRequest(FetchRuleKeyLogsRequest other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetRuleKeys()) { java.util.List<java.lang.String> __this__ruleKeys = new java.util.ArrayList<java.lang.String>(other.ruleKeys); this.ruleKeys = __this__ruleKeys; } if (other.isSetRepository()) { this.repository = other.repository; } if (other.isSetScheduleType()) { this.scheduleType = other.scheduleType; } this.distributedBuildModeEnabled = other.distributedBuildModeEnabled; } public FetchRuleKeyLogsRequest deepCopy() { return new FetchRuleKeyLogsRequest(this); } @Override public void clear() { this.ruleKeys = null; this.repository = null; this.scheduleType = null; setDistributedBuildModeEnabledIsSet(false); this.distributedBuildModeEnabled = false; } public int getRuleKeysSize() { return (this.ruleKeys == null) ? 0 : this.ruleKeys.size(); } public java.util.Iterator<java.lang.String> getRuleKeysIterator() { return (this.ruleKeys == null) ? null : this.ruleKeys.iterator(); } public void addToRuleKeys(java.lang.String elem) { if (this.ruleKeys == null) { this.ruleKeys = new java.util.ArrayList<java.lang.String>(); } this.ruleKeys.add(elem); } public java.util.List<java.lang.String> getRuleKeys() { return this.ruleKeys; } public FetchRuleKeyLogsRequest setRuleKeys(java.util.List<java.lang.String> ruleKeys) { this.ruleKeys = ruleKeys; return this; } public void unsetRuleKeys() { this.ruleKeys = null; } /** Returns true if field ruleKeys is set (has been assigned a value) and false otherwise */ public boolean isSetRuleKeys() { return this.ruleKeys != null; } public void setRuleKeysIsSet(boolean value) { if (!value) { this.ruleKeys = null; } } public java.lang.String getRepository() { return this.repository; } public FetchRuleKeyLogsRequest setRepository(java.lang.String repository) { this.repository = repository; return this; } public void unsetRepository() { this.repository = null; } /** Returns true if field repository is set (has been assigned a value) and false otherwise */ public boolean isSetRepository() { return this.repository != null; } public void setRepositoryIsSet(boolean value) { if (!value) { this.repository = null; } } public java.lang.String getScheduleType() { return this.scheduleType; } public FetchRuleKeyLogsRequest setScheduleType(java.lang.String scheduleType) { this.scheduleType = scheduleType; return this; } public void unsetScheduleType() { this.scheduleType = null; } /** Returns true if field scheduleType is set (has been assigned a value) and false otherwise */ public boolean isSetScheduleType() { return this.scheduleType != null; } public void setScheduleTypeIsSet(boolean value) { if (!value) { this.scheduleType = null; } } public boolean isDistributedBuildModeEnabled() { return this.distributedBuildModeEnabled; } public FetchRuleKeyLogsRequest setDistributedBuildModeEnabled(boolean distributedBuildModeEnabled) { this.distributedBuildModeEnabled = distributedBuildModeEnabled; setDistributedBuildModeEnabledIsSet(true); return this; } public void unsetDistributedBuildModeEnabled() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __DISTRIBUTEDBUILDMODEENABLED_ISSET_ID); } /** Returns true if field distributedBuildModeEnabled is set (has been assigned a value) and false otherwise */ public boolean isSetDistributedBuildModeEnabled() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __DISTRIBUTEDBUILDMODEENABLED_ISSET_ID); } public void setDistributedBuildModeEnabledIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __DISTRIBUTEDBUILDMODEENABLED_ISSET_ID, value); } public void setFieldValue(_Fields field, java.lang.Object value) { switch (field) { case RULE_KEYS: if (value == null) { unsetRuleKeys(); } else { setRuleKeys((java.util.List<java.lang.String>)value); } break; case REPOSITORY: if (value == null) { unsetRepository(); } else { setRepository((java.lang.String)value); } break; case SCHEDULE_TYPE: if (value == null) { unsetScheduleType(); } else { setScheduleType((java.lang.String)value); } break; case DISTRIBUTED_BUILD_MODE_ENABLED: if (value == null) { unsetDistributedBuildModeEnabled(); } else { setDistributedBuildModeEnabled((java.lang.Boolean)value); } break; } } public java.lang.Object getFieldValue(_Fields field) { switch (field) { case RULE_KEYS: return getRuleKeys(); case REPOSITORY: return getRepository(); case SCHEDULE_TYPE: return getScheduleType(); case DISTRIBUTED_BUILD_MODE_ENABLED: return isDistributedBuildModeEnabled(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case RULE_KEYS: return isSetRuleKeys(); case REPOSITORY: return isSetRepository(); case SCHEDULE_TYPE: return isSetScheduleType(); case DISTRIBUTED_BUILD_MODE_ENABLED: return isSetDistributedBuildModeEnabled(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that == null) return false; if (that instanceof FetchRuleKeyLogsRequest) return this.equals((FetchRuleKeyLogsRequest)that); return false; } public boolean equals(FetchRuleKeyLogsRequest that) { if (that == null) return false; if (this == that) return true; boolean this_present_ruleKeys = true && this.isSetRuleKeys(); boolean that_present_ruleKeys = true && that.isSetRuleKeys(); if (this_present_ruleKeys || that_present_ruleKeys) { if (!(this_present_ruleKeys && that_present_ruleKeys)) return false; if (!this.ruleKeys.equals(that.ruleKeys)) return false; } boolean this_present_repository = true && this.isSetRepository(); boolean that_present_repository = true && that.isSetRepository(); if (this_present_repository || that_present_repository) { if (!(this_present_repository && that_present_repository)) return false; if (!this.repository.equals(that.repository)) return false; } boolean this_present_scheduleType = true && this.isSetScheduleType(); boolean that_present_scheduleType = true && that.isSetScheduleType(); if (this_present_scheduleType || that_present_scheduleType) { if (!(this_present_scheduleType && that_present_scheduleType)) return false; if (!this.scheduleType.equals(that.scheduleType)) return false; } boolean this_present_distributedBuildModeEnabled = true && this.isSetDistributedBuildModeEnabled(); boolean that_present_distributedBuildModeEnabled = true && that.isSetDistributedBuildModeEnabled(); if (this_present_distributedBuildModeEnabled || that_present_distributedBuildModeEnabled) { if (!(this_present_distributedBuildModeEnabled && that_present_distributedBuildModeEnabled)) return false; if (this.distributedBuildModeEnabled != that.distributedBuildModeEnabled) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetRuleKeys()) ? 131071 : 524287); if (isSetRuleKeys()) hashCode = hashCode * 8191 + ruleKeys.hashCode(); hashCode = hashCode * 8191 + ((isSetRepository()) ? 131071 : 524287); if (isSetRepository()) hashCode = hashCode * 8191 + repository.hashCode(); hashCode = hashCode * 8191 + ((isSetScheduleType()) ? 131071 : 524287); if (isSetScheduleType()) hashCode = hashCode * 8191 + scheduleType.hashCode(); hashCode = hashCode * 8191 + ((isSetDistributedBuildModeEnabled()) ? 131071 : 524287); if (isSetDistributedBuildModeEnabled()) hashCode = hashCode * 8191 + ((distributedBuildModeEnabled) ? 131071 : 524287); return hashCode; } @Override public int compareTo(FetchRuleKeyLogsRequest other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.valueOf(isSetRuleKeys()).compareTo(other.isSetRuleKeys()); if (lastComparison != 0) { return lastComparison; } if (isSetRuleKeys()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ruleKeys, other.ruleKeys); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(isSetRepository()).compareTo(other.isSetRepository()); if (lastComparison != 0) { return lastComparison; } if (isSetRepository()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.repository, other.repository); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(isSetScheduleType()).compareTo(other.isSetScheduleType()); if (lastComparison != 0) { return lastComparison; } if (isSetScheduleType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.scheduleType, other.scheduleType); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(isSetDistributedBuildModeEnabled()).compareTo(other.isSetDistributedBuildModeEnabled()); if (lastComparison != 0) { return lastComparison; } if (isSetDistributedBuildModeEnabled()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.distributedBuildModeEnabled, other.distributedBuildModeEnabled); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("FetchRuleKeyLogsRequest("); boolean first = true; if (isSetRuleKeys()) { sb.append("ruleKeys:"); if (this.ruleKeys == null) { sb.append("null"); } else { sb.append(this.ruleKeys); } first = false; } if (isSetRepository()) { if (!first) sb.append(", "); sb.append("repository:"); if (this.repository == null) { sb.append("null"); } else { sb.append(this.repository); } first = false; } if (isSetScheduleType()) { if (!first) sb.append(", "); sb.append("scheduleType:"); if (this.scheduleType == null) { sb.append("null"); } else { sb.append(this.scheduleType); } first = false; } if (isSetDistributedBuildModeEnabled()) { if (!first) sb.append(", "); sb.append("distributedBuildModeEnabled:"); sb.append(this.distributedBuildModeEnabled); first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class FetchRuleKeyLogsRequestStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public FetchRuleKeyLogsRequestStandardScheme getScheme() { return new FetchRuleKeyLogsRequestStandardScheme(); } } private static class FetchRuleKeyLogsRequestStandardScheme extends org.apache.thrift.scheme.StandardScheme<FetchRuleKeyLogsRequest> { public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list178 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList<java.lang.String>(_list178.size); java.lang.String _elem179; for (int _i180 = 0; _i180 < _list178.size; ++_i180) { _elem179 = iprot.readString(); struct.ruleKeys.add(_elem179); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.ruleKeys != null) { if (struct.isSetRuleKeys()) { oprot.writeFieldBegin(RULE_KEYS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.ruleKeys.size())); for (java.lang.String _iter181 : struct.ruleKeys) { oprot.writeString(_iter181); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } if (struct.repository != null) { if (struct.isSetRepository()) { oprot.writeFieldBegin(REPOSITORY_FIELD_DESC); oprot.writeString(struct.repository); oprot.writeFieldEnd(); } } if (struct.scheduleType != null) { if (struct.isSetScheduleType()) { oprot.writeFieldBegin(SCHEDULE_TYPE_FIELD_DESC); oprot.writeString(struct.scheduleType); oprot.writeFieldEnd(); } } if (struct.isSetDistributedBuildModeEnabled()) { oprot.writeFieldBegin(DISTRIBUTED_BUILD_MODE_ENABLED_FIELD_DESC); oprot.writeBool(struct.distributedBuildModeEnabled); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class FetchRuleKeyLogsRequestTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public FetchRuleKeyLogsRequestTupleScheme getScheme() { return new FetchRuleKeyLogsRequestTupleScheme(); } } private static class FetchRuleKeyLogsRequestTupleScheme extends org.apache.thrift.scheme.TupleScheme<FetchRuleKeyLogsRequest> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetRuleKeys()) { optionals.set(0); } if (struct.isSetRepository()) { optionals.set(1); } if (struct.isSetScheduleType()) { optionals.set(2); } if (struct.isSetDistributedBuildModeEnabled()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetRuleKeys()) { { oprot.writeI32(struct.ruleKeys.size()); for (java.lang.String _iter182 : struct.ruleKeys) { oprot.writeString(_iter182); } } } if (struct.isSetRepository()) { oprot.writeString(struct.repository); } if (struct.isSetScheduleType()) { oprot.writeString(struct.scheduleType); } if (struct.isSetDistributedBuildModeEnabled()) { oprot.writeBool(struct.distributedBuildModeEnabled); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list183 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32()); struct.ruleKeys = new java.util.ArrayList<java.lang.String>(_list183.size); java.lang.String _elem184; for (int _i185 = 0; _i185 < _list183.size; ++_i185) { _elem184 = iprot.readString(); struct.ruleKeys.add(_elem184); } } struct.setRuleKeysIsSet(true); } if (incoming.get(1)) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } if (incoming.get(2)) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } if (incoming.get(3)) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
apache-2.0
shakamunyi/drill
exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatchLoader.java
10172
/* * 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.drill.exec.record; import io.netty.buffer.DrillBuf; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.drill.common.StackTrace; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.common.map.CaseInsensitiveMap; import org.apache.drill.common.types.TypeProtos.MinorType; import org.apache.drill.exec.exception.SchemaChangeException; import org.apache.drill.exec.expr.TypeHelper; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.proto.UserBitShared.RecordBatchDef; import org.apache.drill.exec.proto.UserBitShared.SerializedField; import org.apache.drill.exec.record.selection.SelectionVector2; import org.apache.drill.exec.record.selection.SelectionVector4; import org.apache.drill.exec.vector.AllocationHelper; import org.apache.drill.exec.vector.ValueVector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; /** * Holds record batch loaded from record batch message. */ public class RecordBatchLoader implements VectorAccessible, Iterable<VectorWrapper<?>>{ private final static Logger logger = LoggerFactory.getLogger(RecordBatchLoader.class); private final BufferAllocator allocator; private VectorContainer container = new VectorContainer(); private int valueCount; private BatchSchema schema; /** * Constructs a loader using the given allocator for vector buffer allocation. */ public RecordBatchLoader(BufferAllocator allocator) { this.allocator = Preconditions.checkNotNull(allocator); } /** * Load a record batch from a single buffer. * * @param def * The definition for the record batch. * @param buf * The buffer that holds the data associated with the record batch. * @return Whether the schema changed since the previous load. * @throws SchemaChangeException * TODO: Clean: DRILL-2933 load(...) never actually throws SchemaChangeException. */ @SuppressWarnings("resource") public boolean load(RecordBatchDef def, DrillBuf buf) throws SchemaChangeException { if (logger.isTraceEnabled()) { logger.trace("Loading record batch with def {} and data {}", def, buf); logger.trace("Load, ThreadID: {}\n{}", Thread.currentThread().getId(), new StackTrace()); } container.zeroVectors(); valueCount = def.getRecordCount(); boolean schemaChanged = schema == null; // Load vectors from the batch buffer, while tracking added and/or removed // vectors (relative to the previous call) in order to determine whether the // the schema has changed since the previous call. // Set up to recognize previous fields that no longer exist. final Map<String, ValueVector> oldFields = CaseInsensitiveMap.newHashMap(); for(final VectorWrapper<?> wrapper : container) { final ValueVector vector = wrapper.getValueVector(); oldFields.put(vector.getField().getName(), vector); } final VectorContainer newVectors = new VectorContainer(); try { final List<SerializedField> fields = def.getFieldList(); int bufOffset = 0; for(final SerializedField field : fields) { final MaterializedField fieldDef = MaterializedField.create(field); ValueVector vector = oldFields.remove(fieldDef.getName()); if (vector == null) { // Field did not exist previously--is schema change. schemaChanged = true; vector = TypeHelper.getNewVector(fieldDef, allocator); } else if (!vector.getField().getType().equals(fieldDef.getType())) { // Field had different type before--is schema change. // clear previous vector vector.clear(); schemaChanged = true; vector = TypeHelper.getNewVector(fieldDef, allocator); // If the field is a map, check if the map schema changed. } else if (vector.getField().getType().getMinorType() == MinorType.MAP && ! isSameSchema(vector.getField().getChildren(), field.getChildList())) { // The map schema changed. Discard the old map and create a new one. schemaChanged = true; vector.clear(); vector = TypeHelper.getNewVector(fieldDef, allocator); } // Load the vector. if (field.getValueCount() == 0) { AllocationHelper.allocate(vector, 0, 0, 0); } else { vector.load(field, buf.slice(bufOffset, field.getBufferLength())); } bufOffset += field.getBufferLength(); newVectors.add(vector); } // rebuild the schema. final SchemaBuilder builder = BatchSchema.newBuilder(); for (final VectorWrapper<?> v : newVectors) { builder.addField(v.getField()); } builder.setSelectionVectorMode(BatchSchema.SelectionVectorMode.NONE); schema = builder.build(); newVectors.buildSchema(BatchSchema.SelectionVectorMode.NONE); container = newVectors; } catch (final Throwable cause) { // We have to clean up new vectors created here and pass over the actual cause. It is upper layer who should // adjudicate to call upper layer specific clean up logic. for (final VectorWrapper<?> wrapper:newVectors) { wrapper.getValueVector().clear(); } throw cause; } finally { if (!oldFields.isEmpty()) { schemaChanged = true; for (final ValueVector vector:oldFields.values()) { vector.clear(); } } } return schemaChanged; } /** * Check if two schemas are the same. The schemas, given as lists, represent the * children of the original and new maps (AKA structures.) * * @param currentChildren current children of a Drill map * @param newChildren new children, in an incoming batch, of the same * Drill map * @return true if the schemas are identical, false if a child is missing * or has changed type or cardinality (AKA "mode"). */ private boolean isSameSchema(Collection<MaterializedField> currentChildren, List<SerializedField> newChildren) { if (currentChildren.size() != newChildren.size()) { return false; } // Column order can permute (see DRILL-5828). So, use a map // for matching. Map<String, MaterializedField> childMap = CaseInsensitiveMap.newHashMap(); for (MaterializedField currentChild : currentChildren) { childMap.put(currentChild.getName(), currentChild); } for (SerializedField newChild : newChildren) { MaterializedField currentChild = childMap.get(newChild.getNamePart().getName()); // New map member? if (currentChild == null) { return false; } // Changed data type? if (! currentChild.getType().equals(newChild.getMajorType())) { return false; } } // Everything matches. return true; } @Override public TypedFieldId getValueVectorId(SchemaPath path) { return container.getValueVectorId(path); } // // @SuppressWarnings("unchecked") // public <T extends ValueVector> T getValueVectorId(int fieldId, Class<?> clazz) { // ValueVector v = container.get(fieldId); // assert v != null; // if (v.getClass() != clazz){ // logger.warn(String.format( // "Failure while reading vector. Expected vector class of %s but was holding vector class %s.", // clazz.getCanonicalName(), v.getClass().getCanonicalName())); // return null; // } // return (T) v; // } @Override public int getRecordCount() { return valueCount; } public VectorContainer getContainer() { return container; } @Override public VectorWrapper<?> getValueAccessorById(Class<?> clazz, int... ids){ return container.getValueAccessorById(clazz, ids); } public WritableBatch getWritableBatch(){ boolean isSV2 = (schema.getSelectionVectorMode() == BatchSchema.SelectionVectorMode.TWO_BYTE); return WritableBatch.getBatchNoHVWrap(valueCount, container, isSV2); } @Override public Iterator<VectorWrapper<?>> iterator() { return this.container.iterator(); } @Override public SelectionVector2 getSelectionVector2() { throw new UnsupportedOperationException(); } @Override public SelectionVector4 getSelectionVector4() { throw new UnsupportedOperationException(); } @Override public BatchSchema getSchema() { return schema; } public void resetRecordCount() { valueCount = 0; } /** * Clears this loader, which clears the internal vector container (see * {@link VectorContainer#clear}) and resets the record count to zero. */ public void clear() { container.clear(); resetRecordCount(); } /** * Sorts vectors into canonical order (by field name). Updates schema and * internal vector container. */ public void canonicalize() { //logger.debug( "RecordBatchLoader : before schema " + schema); container = VectorContainer.canonicalize(container); // rebuild the schema. SchemaBuilder b = BatchSchema.newBuilder(); for(final VectorWrapper<?> v : container){ b.addField(v.getField()); } b.setSelectionVectorMode(BatchSchema.SelectionVectorMode.NONE); this.schema = b.build(); //logger.debug( "RecordBatchLoader : after schema " + schema); } }
apache-2.0
dushmis/closure-compiler
test/com/google/javascript/jscomp/GenerateExportsTest.java
8598
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; /** * Generate exports unit test. * */ public final class GenerateExportsTest extends CompilerTestCase { private static final String EXTERNS = "function google_exportSymbol(a, b) {}; " + "goog.exportProperty = function(a, b, c) {}; "; private boolean allowNonGlobalExports = true; public GenerateExportsTest() { super(EXTERNS); compareJsDoc = false; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new GenerateExports(compiler, allowNonGlobalExports, "google_exportSymbol", "goog.exportProperty"); } @Override protected int getNumRepetitions() { // This pass only runs once. return 1; } @Override public void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(false); this.allowNonGlobalExports = true; } @Override protected void testExternChanges(String input, String expectedExtern) { this.enableCompareAsTree(false); super.testExternChanges(input, expectedExtern); } public void testExportSymbol() { test("/** @export */function foo() {}", "function foo(){}google_exportSymbol(\"foo\",foo)"); } public void testExportSymbolAndProperties() { test("/** @export */function foo() {}" + "/** @export */foo.prototype.bar = function() {}", "function foo(){}" + "google_exportSymbol(\"foo\",foo);" + "foo.prototype.bar=function(){};" + "goog.exportProperty(foo.prototype,\"bar\",foo.prototype.bar)"); } public void testExportPrototypeProperty() { test("function Foo() {}\n" + "/** @export */ Foo.prototype.bar = function() {};", "function Foo() {}\n" + "Foo.prototype.bar = function(){};\n" + "goog.exportProperty(Foo.prototype, 'bar', Foo.prototype.bar);"); } public void testExportSymbolAndConstantProperties() { test("/** @export */function foo() {}" + "/** @export */foo.BAR = 5;", "function foo(){}" + "google_exportSymbol(\"foo\",foo);" + "foo.BAR=5;" + "goog.exportProperty(foo,\"BAR\",foo.BAR)"); } public void testExportVars() { test("/** @export */var FOO = 5", "var FOO=5;" + "google_exportSymbol(\"FOO\",FOO)"); } public void testNoExport() { test("var FOO = 5", "var FOO=5"); } /** * Nested assignments are ambiguous and therefore not supported. * @see FindExportableNodes */ public void testNestedVarAssign() { this.allowNonGlobalExports = false; testError("var BAR;\n/** @export */var FOO = BAR = 5", FindExportableNodes.NON_GLOBAL_ERROR); this.allowNonGlobalExports = true; testError("var BAR;\n/** @export */var FOO = BAR = 5", FindExportableNodes.EXPORT_ANNOTATION_NOT_ALLOWED); } /** * Nested assignments are ambiguous and therefore not supported. * @see FindExportableNodes */ public void testNestedAssign() { this.allowNonGlobalExports = false; testError("var BAR;var FOO = {};\n/** @export */FOO.test = BAR = 5", FindExportableNodes.NON_GLOBAL_ERROR); this.allowNonGlobalExports = true; testError("var BAR;var FOO = {};\n/** @export */FOO.test = BAR = 5", FindExportableNodes.EXPORT_ANNOTATION_NOT_ALLOWED); } public void testNonGlobalScopeExport1() { this.allowNonGlobalExports = false; testError("(function() { /** @export */var FOO = 5 })()", FindExportableNodes.NON_GLOBAL_ERROR); this.allowNonGlobalExports = true; testError("(function() { /** @export */var FOO = 5 })()", FindExportableNodes.EXPORT_ANNOTATION_NOT_ALLOWED); } public void testNonGlobalScopeExport2() { this.allowNonGlobalExports = false; testError("var x = {/** @export */ A:function() {}}", FindExportableNodes.NON_GLOBAL_ERROR); } public void testExportClass() { test("/** @export */ function G() {} foo();", "function G() {} google_exportSymbol('G', G); foo();"); } public void testExportClassMember() { test(LINE_JOINER.join( "/** @export */ function F() {}", "/** @export */ F.prototype.method = function() {};"), LINE_JOINER.join( "function F() {}", "google_exportSymbol('F', F);", "F.prototype.method = function() {};", "goog.exportProperty(F.prototype, 'method', F.prototype.method);")); } public void testExportEs6ClassSymbol() { setAcceptedLanguage(LanguageMode.ECMASCRIPT6); test("/** @export */ class G {} foo();", "class G {} google_exportSymbol('G', G); foo();"); test("/** @export */ G = class {}; foo();", "G = class {}; google_exportSymbol('G', G); foo();"); } public void testExportEs6ClassProperty() { setAcceptedLanguage(LanguageMode.ECMASCRIPT6); test(LINE_JOINER.join( "/** @export */ G = class {};", "/** @export */ G.foo = class {};"), LINE_JOINER.join( "G = class {}; google_exportSymbol('G', G);", "G.foo = class {};", "goog.exportProperty(G, 'foo', G.foo)")); test(LINE_JOINER.join( "G = class {};", "/** @export */ G.prototype.foo = class {};"), LINE_JOINER.join( "G = class {}; G.prototype.foo = class {};", "goog.exportProperty(G.prototype, 'foo', G.prototype.foo)")); } public void testExportEs6ClassMembers() { setAcceptedLanguage(LanguageMode.ECMASCRIPT6); test(LINE_JOINER.join( "/** @export */ class G {", " /** @export */ method() {} }"), LINE_JOINER.join( "class G { method() {} }", "google_exportSymbol('G', G);", "goog.exportProperty(G.prototype, 'method', G.prototype.method);")); test(LINE_JOINER.join( "/** @export */ class G {", "/** @export */ static method() {} }"), LINE_JOINER.join( "class G { static method() {} }", "google_exportSymbol('G', G);", "goog.exportProperty(G, 'method', G.method);")); } public void testExportSubclass() { test("var goog = {}; function F() {}" + "/** @export */ function G() {} goog.inherits(G, F);", "var goog = {}; function F() {}" + "function G() {} goog.inherits(G, F); google_exportSymbol('G', G);"); } public void testExportEnum() { // TODO(johnlenz): Issue 310, should the values also be externed? test("/** @enum {string}\n @export */ var E = {A:1, B:2};", "/** @enum {string}\n @export */ var E = {A:1, B:2};" + "google_exportSymbol('E', E);"); } public void testExportObjectLit1() { allowExternsChanges(true); String code = "var E = {/** @export */ A:1, B:2};"; testSame(code); testExternChanges(code, "Object.prototype.A;"); } public void testExportObjectLit2() { allowExternsChanges(true); String code = "var E = {/** @export */ get A() { return 1 }, B:2};"; testSame(code); testExternChanges(code, "Object.prototype.A;"); } public void testExportObjectLit3() { allowExternsChanges(true); String code = "var E = {/** @export */ set A(v) {}, B:2};"; testSame(code); testExternChanges(code, "Object.prototype.A;"); } public void testExportObjectLit4() { allowExternsChanges(true); String code = "var E = {/** @export */ A:function() {}, B:2};"; testSame(code); testExternChanges(code, "Object.prototype.A;"); } public void testExportClassMember1() { allowExternsChanges(true); String code = "var E = function() { /** @export */ this.foo = 1; };"; testSame(code); testExternChanges(code, "Object.prototype.foo;"); } public void testExportClassMemberStub() { allowExternsChanges(true); String code = "var E = function() { /** @export */ this.foo; };"; testSame(code); testExternChanges(code, "Object.prototype.foo;"); } }
apache-2.0
don-philipe/graphhopper
reader-gtfs/src/main/java/com/graphhopper/gtfs/TripFromLabel.java
24787
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.gtfs; import com.conveyal.gtfs.GTFSFeed; import com.conveyal.gtfs.model.Stop; import com.conveyal.gtfs.model.StopTime; import com.google.protobuf.InvalidProtocolBufferException; import com.google.transit.realtime.GtfsRealtime; import com.graphhopper.ResponsePath; import com.graphhopper.Trip; import com.graphhopper.gtfs.fare.Fares; import com.graphhopper.routing.InstructionsFromEdges; import com.graphhopper.routing.Path; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.util.*; import com.graphhopper.util.details.PathDetail; import com.graphhopper.util.details.PathDetailsBuilderFactory; import com.graphhopper.util.details.PathDetailsFromEdges; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.time.temporal.ChronoUnit.SECONDS; class TripFromLabel { private static final Logger logger = LoggerFactory.getLogger(TripFromLabel.class); private final GraphHopperStorage graphHopperStorage; private final GtfsStorage gtfsStorage; private final RealtimeFeed realtimeFeed; private final GeometryFactory geometryFactory = new GeometryFactory(); private final PathDetailsBuilderFactory pathDetailsBuilderFactory; TripFromLabel(GraphHopperStorage graphHopperStorage, GtfsStorage gtfsStorage, RealtimeFeed realtimeFeed, PathDetailsBuilderFactory pathDetailsBuilderFactory) { this.graphHopperStorage = graphHopperStorage; this.gtfsStorage = gtfsStorage; this.realtimeFeed = realtimeFeed; this.pathDetailsBuilderFactory = pathDetailsBuilderFactory; } ResponsePath createResponsePath(Translation tr, PointList waypoints, Graph queryGraph, Weighting accessEgressWeighting, List<Label.Transition> solution, List<String> requestedPathDetails) { final List<Trip.Leg> legs = buildLegs(tr, queryGraph, accessEgressWeighting, solution, requestedPathDetails); if (legs.size() > 1 && legs.get(0) instanceof Trip.WalkLeg) { final Trip.WalkLeg accessLeg = (Trip.WalkLeg) legs.get(0); legs.set(0, new Trip.WalkLeg(accessLeg.departureLocation, new Date(legs.get(1).getDepartureTime().getTime() - (accessLeg.getArrivalTime().getTime() - accessLeg.getDepartureTime().getTime())), accessLeg.geometry, accessLeg.distance, accessLeg.instructions, accessLeg.details, legs.get(1).getDepartureTime())); } if (legs.size() > 1 && legs.get(legs.size() - 1) instanceof Trip.WalkLeg) { final Trip.WalkLeg egressLeg = (Trip.WalkLeg) legs.get(legs.size() - 1); legs.set(legs.size() - 1, new Trip.WalkLeg(egressLeg.departureLocation, legs.get(legs.size() - 2).getArrivalTime(), egressLeg.geometry, egressLeg.distance, egressLeg.instructions, egressLeg.details, new Date(legs.get(legs.size() - 2).getArrivalTime().getTime() + (egressLeg.getArrivalTime().getTime() - egressLeg.getDepartureTime().getTime())))); } ResponsePath path = new ResponsePath(); path.setWaypoints(waypoints); path.getLegs().addAll(legs); final InstructionList instructions = new InstructionList(tr); final PointList pointsList = new PointList(); for (int i = 0; i < path.getLegs().size(); ++i) { Trip.Leg leg = path.getLegs().get(i); if (leg instanceof Trip.WalkLeg) { final Trip.WalkLeg walkLeg = ((Trip.WalkLeg) leg); List<Instruction> theseInstructions = walkLeg.instructions.subList(0, i < path.getLegs().size() - 1 ? walkLeg.instructions.size() - 1 : walkLeg.instructions.size()); int previousPointsCount = pointsList.size(); for (Instruction instruction : theseInstructions) { pointsList.add(instruction.getPoints()); } instructions.addAll(theseInstructions); path.addPathDetails(shift(((Trip.WalkLeg) leg).details, previousPointsCount)); } else if (leg instanceof Trip.PtLeg) { final Trip.PtLeg ptLeg = ((Trip.PtLeg) leg); final PointList pl; if (!ptLeg.isInSameVehicleAsPrevious) { pl = new PointList(); final Instruction departureInstruction = new Instruction(Instruction.PT_START_TRIP, ptLeg.trip_headsign, pl); departureInstruction.setDistance(leg.getDistance()); departureInstruction.setTime(ptLeg.travelTime); instructions.add(departureInstruction); } else { pl = instructions.get(instructions.size() - 2).getPoints(); } pl.add(ptLeg.stops.get(0).geometry.getY(), ptLeg.stops.get(0).geometry.getX()); pointsList.add(ptLeg.stops.get(0).geometry.getY(), ptLeg.stops.get(0).geometry.getX()); for (Trip.Stop stop : ptLeg.stops.subList(0, ptLeg.stops.size() - 1)) { pl.add(stop.geometry.getY(), stop.geometry.getX()); pointsList.add(stop.geometry.getY(), stop.geometry.getX()); } final PointList arrivalPointList = new PointList(); final Trip.Stop arrivalStop = ptLeg.stops.get(ptLeg.stops.size() - 1); arrivalPointList.add(arrivalStop.geometry.getY(), arrivalStop.geometry.getX()); pointsList.add(arrivalStop.geometry.getY(), arrivalStop.geometry.getX()); Instruction arrivalInstruction = new Instruction(Instruction.PT_END_TRIP, arrivalStop.stop_name, arrivalPointList); if (ptLeg.isInSameVehicleAsPrevious) { instructions.set(instructions.size() - 1, arrivalInstruction); } else { instructions.add(arrivalInstruction); } } } path.setInstructions(instructions); path.setPoints(pointsList); path.setDistance(path.getLegs().stream().mapToDouble(Trip.Leg::getDistance).sum()); path.setTime((legs.get(legs.size() - 1).getArrivalTime().toInstant().toEpochMilli() - legs.get(0).getDepartureTime().toInstant().toEpochMilli())); path.setNumChanges((int) path.getLegs().stream() .filter(l -> l instanceof Trip.PtLeg) .filter(l -> !((Trip.PtLeg) l).isInSameVehicleAsPrevious) .count() - 1); com.graphhopper.gtfs.fare.Trip faresTrip = new com.graphhopper.gtfs.fare.Trip(); path.getLegs().stream() .filter(leg -> leg instanceof Trip.PtLeg) .map(leg -> (Trip.PtLeg) leg) .findFirst() .ifPresent(firstPtLeg -> { LocalDateTime firstPtDepartureTime = GtfsHelper.localDateTimeFromDate(firstPtLeg.getDepartureTime()); path.getLegs().stream() .filter(leg -> leg instanceof Trip.PtLeg) .map(leg -> (Trip.PtLeg) leg) .map(ptLeg -> { final GTFSFeed gtfsFeed = gtfsStorage.getGtfsFeeds().get(ptLeg.feed_id); return new com.graphhopper.gtfs.fare.Trip.Segment(ptLeg.feed_id, ptLeg.route_id, Duration.between(firstPtDepartureTime, GtfsHelper.localDateTimeFromDate(ptLeg.getDepartureTime())).getSeconds(), gtfsFeed.stops.get(ptLeg.stops.get(0).stop_id).zone_id, gtfsFeed.stops.get(ptLeg.stops.get(ptLeg.stops.size() - 1).stop_id).zone_id, ptLeg.stops.stream().map(s -> gtfsFeed.stops.get(s.stop_id).zone_id).collect(Collectors.toSet())); }) .forEach(faresTrip.segments::add); Fares.cheapestFare(gtfsStorage.getFares(), faresTrip) .ifPresent(amount -> path.setFare(amount.getAmount())); }); return path; } private Map<String, List<PathDetail>> shift(Map<String, List<PathDetail>> pathDetailss, int previousPointsCount) { for (List<PathDetail> pathDetails : pathDetailss.values()) { for (PathDetail pathDetail : pathDetails) { pathDetail.setFirst(pathDetail.getFirst() + previousPointsCount); pathDetail.setLast(pathDetail.getLast() + previousPointsCount); } } return pathDetailss; } private List<Trip.Leg> buildLegs(Translation tr, Graph queryGraph, Weighting weighting, List<Label.Transition> path, List<String> requestedPathDetails) { final List<List<Label.Transition>> partitions = parsePathToPartitions(path); return partitions.stream().flatMap(partition -> parsePartitionToLegs(partition, queryGraph, weighting, tr, requestedPathDetails).stream()).collect(Collectors.toList()); } private List<List<Label.Transition>> parsePathToPartitions(List<Label.Transition> path) { List<List<Label.Transition>> partitions = new ArrayList<>(); partitions.add(new ArrayList<>()); final Iterator<Label.Transition> iterator = path.iterator(); partitions.get(partitions.size() - 1).add(iterator.next()); iterator.forEachRemaining(transition -> { final List<Label.Transition> previous = partitions.get(partitions.size() - 1); final Label.EdgeLabel previousEdge = previous.get(previous.size() - 1).edge; if (previousEdge != null && (transition.edge.edgeType == GtfsStorage.EdgeType.ENTER_PT || previousEdge.edgeType == GtfsStorage.EdgeType.EXIT_PT)) { final ArrayList<Label.Transition> p = new ArrayList<>(); p.add(new Label.Transition(previous.get(previous.size() - 1).label, null)); partitions.add(p); } partitions.get(partitions.size() - 1).add(transition); }); return partitions; } private class StopsFromBoardHopDwellEdges { private final GtfsRealtime.TripDescriptor tripDescriptor; private final List<Trip.Stop> stops = new ArrayList<>(); private final GTFSFeed gtfsFeed; private Instant boardTime; private Instant arrivalTimeFromHopEdge; private Optional<Instant> updatedArrival; private StopTime stopTime = null; private GtfsReader.TripWithStopTimes tripUpdate = null; private int stopSequence = 0; StopsFromBoardHopDwellEdges(String feedId, GtfsRealtime.TripDescriptor tripDescriptor) { this.tripDescriptor = tripDescriptor; this.gtfsFeed = gtfsStorage.getGtfsFeeds().get(feedId); if (this.tripUpdate != null) { validateTripUpdate(this.tripUpdate); } } void next(Label.Transition t) { switch (t.edge.edgeType) { case BOARD: { boardTime = Instant.ofEpochMilli(t.label.currentTime); stopSequence = realtimeFeed.getStopSequence(t.edge.edgeIteratorState.getEdge()); stopTime = realtimeFeed.getStopTime(gtfsFeed, tripDescriptor, t, boardTime, stopSequence); tripUpdate = realtimeFeed.getTripUpdate(gtfsFeed, tripDescriptor, t, boardTime).orElse(null); Instant plannedDeparture = Instant.ofEpochMilli(t.label.currentTime); Optional<Instant> updatedDeparture = getDepartureDelay(stopSequence).map(delay -> plannedDeparture.plus(delay, SECONDS)); Stop stop = gtfsFeed.stops.get(stopTime.stop_id); stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), null, null, null, isArrivalCancelled(stopSequence), updatedDeparture.map(Date::from).orElse(Date.from(plannedDeparture)), Date.from(plannedDeparture), updatedDeparture.map(Date::from).orElse(null), isDepartureCancelled(stopSequence))); break; } case HOP: { stopSequence = realtimeFeed.getStopSequence(t.edge.edgeIteratorState.getEdge()); stopTime = realtimeFeed.getStopTime(gtfsFeed, tripDescriptor, t, boardTime, stopSequence); arrivalTimeFromHopEdge = Instant.ofEpochMilli(t.label.currentTime); updatedArrival = getArrivalDelay(stopSequence).map(delay -> arrivalTimeFromHopEdge.plus(delay, SECONDS)); break; } case DWELL: { Instant plannedDeparture = Instant.ofEpochMilli(t.label.currentTime); Optional<Instant> updatedDeparture = getDepartureDelay(stopTime.stop_sequence).map(delay -> plannedDeparture.plus(delay, SECONDS)); Stop stop = gtfsFeed.stops.get(stopTime.stop_id); stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), updatedArrival.map(Date::from).orElse(Date.from(arrivalTimeFromHopEdge)), Date.from(arrivalTimeFromHopEdge), updatedArrival.map(Date::from).orElse(null), isArrivalCancelled(stopSequence), updatedDeparture.map(Date::from).orElse(Date.from(plannedDeparture)), Date.from(plannedDeparture), updatedDeparture.map(Date::from).orElse(null), isDepartureCancelled(stopSequence))); break; } default: { throw new RuntimeException(); } } } private Optional<Integer> getArrivalDelay(int stopSequence) { if (tripUpdate != null) { int arrival_time = tripUpdate.stopTimes.stream().filter(st -> st.stop_sequence == stopSequence).findFirst().orElseThrow(() -> new RuntimeException("Stop time not found.")).arrival_time; logger.trace("stop_sequence {} scheduled arrival {} updated arrival {}", stopSequence, stopTime.arrival_time, arrival_time); return Optional.of(arrival_time - stopTime.arrival_time); } else { return Optional.empty(); } } private boolean isArrivalCancelled(int stopSequence) { if (tripUpdate != null) { return tripUpdate.cancelledArrivals.contains(stopSequence); } else { return false; } } private Optional<Integer> getDepartureDelay(int stopSequence) { if (tripUpdate != null) { int departure_time = tripUpdate.stopTimes.stream().filter(st -> st.stop_sequence == stopSequence).findFirst().orElseThrow(() -> new RuntimeException("Stop time not found.")).departure_time; logger.trace("stop_sequence {} scheduled departure {} updated departure {}", stopSequence, stopTime.departure_time, departure_time); return Optional.of(departure_time - stopTime.departure_time); } else { return Optional.empty(); } } private boolean isDepartureCancelled(int stopSequence) { if (tripUpdate != null) { return tripUpdate.cancelledDeparture.contains(stopSequence); } else { return false; } } void finish() { Stop stop = gtfsFeed.stops.get(stopTime.stop_id); stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), updatedArrival.map(Date::from).orElse(Date.from(arrivalTimeFromHopEdge)), Date.from(arrivalTimeFromHopEdge), updatedArrival.map(Date::from).orElse(null), isArrivalCancelled(stopSequence), null, null, null, isDepartureCancelled(stopSequence))); for (Trip.Stop tripStop : stops) { logger.trace("{}", tripStop); } } private void validateTripUpdate(GtfsReader.TripWithStopTimes tripUpdate) { try { Iterable<StopTime> interpolatedStopTimesForTrip = gtfsFeed.getInterpolatedStopTimesForTrip(tripUpdate.trip.trip_id); long nStopTimes = StreamSupport.stream(interpolatedStopTimesForTrip.spliterator(), false).count(); logger.trace("Original stop times: {} Updated stop times: {}", nStopTimes, tripUpdate.stopTimes.size()); if (nStopTimes != tripUpdate.stopTimes.size()) { logger.error("Original stop times: {} Updated stop times: {}", nStopTimes, tripUpdate.stopTimes.size()); } } catch (GTFSFeed.FirstAndLastStopsDoNotHaveTimes firstAndLastStopsDoNotHaveTimes) { throw new RuntimeException(firstAndLastStopsDoNotHaveTimes); } } } // We are parsing a string of edges into a hierarchical trip. // One could argue that one should never write a parser // by hand, because it is always ugly, but use a parser library. // The code would then read like a specification of what paths through the graph mean. private List<Trip.Leg> parsePartitionToLegs(List<Label.Transition> path, Graph graph, Weighting weighting, Translation tr, List<String> requestedPathDetails) { if (path.size() <= 1) { return Collections.emptyList(); } if (GtfsStorage.EdgeType.ENTER_PT == path.get(1).edge.edgeType) { String feedId = path.get(1).edge.feedId; List<Trip.Leg> result = new ArrayList<>(); long boardTime = -1; List<Label.Transition> partition = null; for (int i = 1; i < path.size(); i++) { Label.Transition transition = path.get(i); Label.EdgeLabel edge = path.get(i).edge; if (edge.edgeType == GtfsStorage.EdgeType.BOARD) { boardTime = transition.label.currentTime; partition = new ArrayList<>(); } if (partition != null) { partition.add(path.get(i)); } if (EnumSet.of(GtfsStorage.EdgeType.TRANSFER, GtfsStorage.EdgeType.LEAVE_TIME_EXPANDED_NETWORK).contains(edge.edgeType)) { Geometry lineString = lineStringFromEdges(partition); GtfsRealtime.TripDescriptor tripDescriptor; try { tripDescriptor = GtfsRealtime.TripDescriptor.parseFrom(realtimeFeed.getTripDescriptor(partition.get(0).edge.edgeIteratorState.getEdge())); } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } final StopsFromBoardHopDwellEdges stopsFromBoardHopDwellEdges = new StopsFromBoardHopDwellEdges(feedId, tripDescriptor); partition.stream() .filter(e -> EnumSet.of(GtfsStorage.EdgeType.HOP, GtfsStorage.EdgeType.BOARD, GtfsStorage.EdgeType.DWELL).contains(e.edge.edgeType)) .forEach(stopsFromBoardHopDwellEdges::next); stopsFromBoardHopDwellEdges.finish(); List<Trip.Stop> stops = stopsFromBoardHopDwellEdges.stops; result.add(new Trip.PtLeg( feedId, partition.get(0).edge.nTransfers == 0, tripDescriptor.getTripId(), tripDescriptor.getRouteId(), edges(partition).map(edgeLabel -> edgeLabel.edgeIteratorState).collect(Collectors.toList()).get(0).getName(), stops, partition.stream().mapToDouble(t -> t.edge.distance).sum(), path.get(i - 1).label.currentTime - boardTime, lineString)); partition = null; feedId = edge.feedId; } } return result; } else { InstructionList instructions = new InstructionList(tr); InstructionsFromEdges instructionsFromEdges = new InstructionsFromEdges(graph, weighting, weighting.getFlagEncoder(), instructions); int prevEdgeId = -1; for (int i = 1; i < path.size(); i++) { if (path.get(i).edge.edgeType != GtfsStorage.EdgeType.HIGHWAY) { throw new IllegalStateException("Got a transit edge where I think I must be on a road."); } EdgeIteratorState edge = path.get(i).edge.edgeIteratorState; instructionsFromEdges.next(edge, i, prevEdgeId); prevEdgeId = edge.getEdge(); } instructionsFromEdges.finish(); Path pathh = new Path(graph); for (Label.Transition transition : path) { if (transition.edge != null) pathh.addEdge(transition.edge.edgeIteratorState.getEdge()); } pathh.setFromNode(path.get(0).label.adjNode); pathh.setEndNode(path.get(path.size()-1).label.adjNode); pathh.setFound(true); Map<String, List<PathDetail>> pathDetails = PathDetailsFromEdges.calcDetails(pathh, graphHopperStorage.getEncodingManager(), weighting, requestedPathDetails, pathDetailsBuilderFactory, 0); final Instant departureTime = Instant.ofEpochMilli(path.get(0).label.currentTime); final Instant arrivalTime = Instant.ofEpochMilli(path.get(path.size() - 1).label.currentTime); return Collections.singletonList(new Trip.WalkLeg( "Walk", Date.from(departureTime), lineStringFromEdges(path), edges(path).mapToDouble(edgeLabel -> edgeLabel.distance).sum(), instructions, pathDetails, Date.from(arrivalTime))); } } private Stream<Label.EdgeLabel> edges(List<Label.Transition> path) { return path.stream().filter(t -> t.edge != null).map(t -> t.edge); } private Geometry lineStringFromEdges(List<Label.Transition> transitions) { List<Coordinate> coordinates = new ArrayList<>(); final Iterator<Label.Transition> iterator = transitions.iterator(); iterator.next(); coordinates.addAll(toCoordinateArray(iterator.next().edge.edgeIteratorState.fetchWayGeometry(FetchMode.ALL))); iterator.forEachRemaining(transition -> coordinates.addAll(toCoordinateArray(transition.edge.edgeIteratorState.fetchWayGeometry(FetchMode.PILLAR_AND_ADJ)))); return geometryFactory.createLineString(coordinates.toArray(new Coordinate[coordinates.size()])); } private static List<Coordinate> toCoordinateArray(PointList pointList) { List<Coordinate> coordinates = new ArrayList<>(pointList.size()); for (int i = 0; i < pointList.size(); i++) { coordinates.add(pointList.getDimension() == 3 ? new Coordinate(pointList.getLon(i), pointList.getLat(i)) : new Coordinate(pointList.getLon(i), pointList.getLat(i), pointList.getEle(i))); } return coordinates; } }
apache-2.0
ferstl/spring-jdbc-oracle
src/test/java/com/github/ferstl/spring/jdbc/oracle/UcpUpdateBatchingIntegrationTest.java
953
/* * Copyright (c) 2021 by Philippe Marschall <philippe.marschall@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ferstl.spring.jdbc.oracle; import org.springframework.test.context.ActiveProfiles; import com.github.ferstl.spring.jdbc.oracle.dsconfig.DataSourceProfile; @ActiveProfiles(DataSourceProfile.UCP) public class UcpUpdateBatchingIntegrationTest extends AbstractUpdateBatchingIntegrationTest { }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/DeleteStageResult.java
2165
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.apigatewayv2.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteStageResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteStageResult == false) return false; DeleteStageResult other = (DeleteStageResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeleteStageResult clone() { try { return (DeleteStageResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
gureronder/midpoint
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/modal/LimitationsEditorDialog.java
16533
/* * Copyright (c) 2010-2013 Evolveum * * 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.evolveum.midpoint.web.component.wizard.resource.component.schemahandling.modal; import com.evolveum.midpoint.web.component.form.CheckFormGroup; import com.evolveum.midpoint.web.component.form.TextFormGroup; import com.evolveum.midpoint.web.component.input.ThreeStateBooleanPanel; import com.evolveum.midpoint.web.component.util.LoadableModel; import com.evolveum.midpoint.web.component.wizard.resource.dto.PropertyLimitationsTypeDto; import com.evolveum.midpoint.web.util.InfoTooltipBehavior; import com.evolveum.midpoint.xml.ns._public.common.common_3.LayerType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PropertyAccessType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PropertyLimitationsType; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.StringResourceModel; import java.util.ArrayList; import java.util.List; /** * @author shood * */ public class LimitationsEditorDialog extends ModalWindow{ private static enum ChangeState{ SKIP, FIRST, LAST } private static final String ID_REPEATER = "repeater"; private static final String ID_LIMITATIONS_LINK = "limitationsLink"; private static final String ID_LIMITATIONS_LABEL = "limitationsLinkName"; private static final String ID_LIMITATION_DELETE = "deleteLimitation"; private static final String ID_BODY = "accountBodyContainer"; private static final String ID_LAYER_SCHEMA = "layerSchema"; private static final String ID_LAYER_MODEL = "layerModel"; private static final String ID_LAYER_PRESENTATION = "layerPresentation"; private static final String ID_ACCESS_ADD = "addAccess"; private static final String ID_ACCESS_READ = "readAccess"; private static final String ID_ACCESS_MODIFY = "modifyAccess"; private static final String ID_MIN_OCCURS = "minOccurs"; private static final String ID_MAX_OCCURS = "maxOccurs"; private static final String ID_IGNORE = "ignore"; private static final String ID_BUTTON_ADD = "addButton"; private static final String ID_BUTTON_SAVE = "saveButton"; private static final String ID_BUTTON_CANCEL = "cancelButton"; private static final String ID_MAIN_FORM = "mainForm"; private static final String ID_T_LAYERS = "layersTooltip"; private static final String ID_T_PROPERTY = "propertyAccessTooltip"; private static final String ID_LABEL_SIZE = "col-md-4"; private static final String ID_INPUT_SIZE = "col-md-8"; private ChangeState changeState = ChangeState.FIRST; private boolean initialized; private IModel<List<PropertyLimitationsTypeDto>> model; private IModel<List<PropertyLimitationsType>> inputModel; public LimitationsEditorDialog(String id, final IModel<List<PropertyLimitationsType>> limitation){ super(id); inputModel = limitation; model = new LoadableModel<List<PropertyLimitationsTypeDto>>(false) { @Override protected List<PropertyLimitationsTypeDto> load() { return loadLimitationsModel(limitation); } }; setOutputMarkupId(true); setTitle(createStringResource("LimitationsEditorDialog.label")); showUnloadConfirmation(false); setCssClassName(ModalWindow.CSS_CLASS_GRAY); setCookieName(LimitationsEditorDialog.class.getSimpleName() + ((int) (Math.random() * 100))); setInitialWidth(600); setInitialHeight(700); setWidthUnit("px"); WebMarkupContainer content = new WebMarkupContainer(getContentId()); content.setOutputMarkupId(true); setContent(content); } private List<PropertyLimitationsTypeDto> loadLimitationsModel(IModel<List<PropertyLimitationsType>> limList){ List<PropertyLimitationsTypeDto> limitations = new ArrayList<>(); List<PropertyLimitationsType> limitationTypeList = limList.getObject(); for(PropertyLimitationsType limitation: limitationTypeList){ limitations.add(new PropertyLimitationsTypeDto(limitation)); } return limitations; } @Override protected void onBeforeRender(){ super.onBeforeRender(); if(initialized){ return; } initLayout((WebMarkupContainer) get(getContentId())); initialized = true; } public void initLayout(WebMarkupContainer content){ Form form = new Form(ID_MAIN_FORM); form.setOutputMarkupId(true); content.add(form); ListView repeater = new ListView<PropertyLimitationsTypeDto>(ID_REPEATER, model){ @Override protected void populateItem(final ListItem<PropertyLimitationsTypeDto> item){ WebMarkupContainer linkContainer = new WebMarkupContainer(ID_LIMITATIONS_LINK); linkContainer.setOutputMarkupId(true); linkContainer.add(new AttributeModifier("href", createCollapseItemId(item, true))); item.add(linkContainer); Label linkLabel = new Label(ID_LIMITATIONS_LABEL, createLimitationsLabelModel(item)); linkContainer.add(linkLabel); AjaxLink delete = new AjaxLink(ID_LIMITATION_DELETE) { @Override public void onClick(AjaxRequestTarget target) { deleteLimitationPerformed(target, item); } }; linkContainer.add(delete); WebMarkupContainer limitationBody = new WebMarkupContainer(ID_BODY); limitationBody.setOutputMarkupId(true); limitationBody.setMarkupId(createCollapseItemId(item, false).getObject()); if(changeState != ChangeState.SKIP){ limitationBody.add(new AttributeModifier("class", new AbstractReadOnlyModel<String>() { @Override public String getObject() { if(changeState == ChangeState.FIRST && item.getIndex() == 0){ return "panel-collapse collapse in"; } else if(changeState == ChangeState.LAST && item.getIndex() == (getModelObject().size()-1)){ return "panel-collapse collapse in"; } else { return "panel-collapse collapse"; } } })); } item.add(limitationBody); initLimitationBody(limitationBody, item); } }; repeater.setOutputMarkupId(true); form.add(repeater); initButtons(form); } private void initButtons(Form form){ AjaxLink add = new AjaxLink(ID_BUTTON_ADD) { @Override public void onClick(AjaxRequestTarget target) { addLimitationsPerformed(target); } }; form.add(add); AjaxLink cancel = new AjaxLink(ID_BUTTON_CANCEL) { @Override public void onClick(AjaxRequestTarget target) { cancelPerformed(target); } }; form.add(cancel); AjaxLink save = new AjaxLink(ID_BUTTON_SAVE) { @Override public void onClick(AjaxRequestTarget target) { savePerformed(target); } }; form.add(save); } private void initLimitationBody(final WebMarkupContainer body, ListItem<PropertyLimitationsTypeDto> item){ CheckFormGroup schema = new CheckFormGroup(ID_LAYER_SCHEMA, new PropertyModel<Boolean>(item.getModelObject(), PropertyLimitationsTypeDto.F_SCHEMA), createStringResource("LimitationsEditorDialog.label.schema"), ID_LABEL_SIZE, ID_INPUT_SIZE); schema.getCheck().add(prepareAjaxOnComponentTagUpdateBehavior()); body.add(schema); CheckFormGroup model = new CheckFormGroup(ID_LAYER_MODEL, new PropertyModel<Boolean>(item.getModelObject(), PropertyLimitationsTypeDto.F_MODEL), createStringResource("LimitationsEditorDialog.label.model"), ID_LABEL_SIZE, ID_INPUT_SIZE); model.getCheck().add(prepareAjaxOnComponentTagUpdateBehavior()); body.add(model); CheckFormGroup presentation = new CheckFormGroup(ID_LAYER_PRESENTATION, new PropertyModel<Boolean>(item.getModelObject(), PropertyLimitationsTypeDto.F_PRESENTATION), createStringResource("LimitationsEditorDialog.label.presentation"), ID_LABEL_SIZE, ID_INPUT_SIZE); presentation.getCheck().add(prepareAjaxOnComponentTagUpdateBehavior()); body.add(presentation); ThreeStateBooleanPanel add = new ThreeStateBooleanPanel(ID_ACCESS_ADD, new PropertyModel<Boolean>(item.getModelObject(), PropertyLimitationsTypeDto.F_LIMITATION + ".access.add"), "LimitationsEditorDialog.allow", "LimitationsEditorDialog.inherit", "LimitationsEditorDialog.deny", null); body.add(add); ThreeStateBooleanPanel read = new ThreeStateBooleanPanel(ID_ACCESS_READ, new PropertyModel<Boolean>(item.getModelObject(), PropertyLimitationsTypeDto.F_LIMITATION + ".access.read"), "LimitationsEditorDialog.allow", "LimitationsEditorDialog.inherit", "LimitationsEditorDialog.deny", null); body.add(read); ThreeStateBooleanPanel modify = new ThreeStateBooleanPanel(ID_ACCESS_MODIFY, new PropertyModel<Boolean>(item.getModelObject(), PropertyLimitationsTypeDto.F_LIMITATION + ".access.modify"), "LimitationsEditorDialog.allow", "LimitationsEditorDialog.inherit", "LimitationsEditorDialog.deny", null); body.add(modify); TextFormGroup minOccurs = new TextFormGroup(ID_MIN_OCCURS, new PropertyModel<String>(item.getModelObject(), PropertyLimitationsTypeDto.F_LIMITATION + ".minOccurs"), createStringResource("LimitationsEditorDialog.label.minOccurs"), "SchemaHandlingStep.limitations.tooltip.minOccurs", true, ID_LABEL_SIZE, ID_INPUT_SIZE, false); minOccurs.getField().add(prepareAjaxOnComponentTagUpdateBehavior()); body.add(minOccurs); TextFormGroup maxOccurs = new TextFormGroup(ID_MAX_OCCURS, new PropertyModel<String>(item.getModelObject(), PropertyLimitationsTypeDto.F_LIMITATION + ".maxOccurs"), createStringResource("LimitationsEditorDialog.label.maxOccurs"), "SchemaHandlingStep.limitations.tooltip.maxOccurs", true, ID_LABEL_SIZE, ID_INPUT_SIZE, false); maxOccurs.getField().add(prepareAjaxOnComponentTagUpdateBehavior()); body.add(maxOccurs); CheckFormGroup ignore = new CheckFormGroup(ID_IGNORE, new PropertyModel<Boolean>(item.getModelObject(), PropertyLimitationsTypeDto.F_LIMITATION + ".ignore"), createStringResource("LimitationsEditorDialog.label.ignore"), "SchemaHandlingStep.limitations.tooltip.ignore", true, ID_LABEL_SIZE, ID_INPUT_SIZE); ignore.getCheck().add(prepareAjaxOnComponentTagUpdateBehavior()); body.add(ignore); Label layersTooltip = new Label(ID_T_LAYERS); layersTooltip.add(new InfoTooltipBehavior(true){ @Override public String getModalContainer(Component component) { return body.getMarkupId(); } }); body.add(layersTooltip); Label propertyTooltip = new Label(ID_T_PROPERTY); propertyTooltip.add(new InfoTooltipBehavior(true){ @Override public String getModalContainer(Component component) { return body.getMarkupId(); } }); body.add(propertyTooltip); } private AjaxFormComponentUpdatingBehavior prepareAjaxOnComponentTagUpdateBehavior(){ return new AjaxFormComponentUpdatingBehavior("onBlur") { @Override protected void onUpdate(AjaxRequestTarget target) {} }; } private IModel<String> createLimitationsLabelModel(final ListItem<PropertyLimitationsTypeDto> item){ return new AbstractReadOnlyModel<String>() { @Override public String getObject() { StringBuilder sb = new StringBuilder(); PropertyLimitationsTypeDto dto = item.getModelObject(); sb.append("#").append(item.getIndex()+1).append(" - "); if(dto.isModel()){ sb.append(LayerType.MODEL).append(", "); } if(dto.isPresentation()){ sb.append(LayerType.PRESENTATION).append(", "); } if(dto.isSchema()){ sb.append(LayerType.SCHEMA).append(", "); } sb.append(":"); if(dto.getLimitationObject().getAccess() != null){ PropertyAccessType access = dto.getLimitationObject().getAccess(); if(access.isRead() != null && access.isRead()){ sb.append(getString("LimitationsEditorDialog.label.read")).append(", "); } if(access.isAdd() != null && access.isAdd()){ sb.append(getString("LimitationsEditorDialog.label.add")).append(", "); } if(access.isModify() != null && access.isModify()){ sb.append(getString("LimitationsEditorDialog.label.modify")).append(", "); } } return sb.toString(); } }; } private IModel<String> createCollapseItemId(final ListItem<PropertyLimitationsTypeDto> item, final boolean appendSelector){ return new AbstractReadOnlyModel<String>() { @Override public String getObject() { StringBuilder sb = new StringBuilder(); if(appendSelector){ sb.append("#"); } sb.append("collapse").append(item.getId()); return sb.toString(); } }; } public StringResourceModel createStringResource(String resourceKey, Object... objects) { return new StringResourceModel(resourceKey, this, null, resourceKey, objects); } private void addLimitationsPerformed(AjaxRequestTarget target){ changeState = ChangeState.LAST; model.getObject().add(new PropertyLimitationsTypeDto(new PropertyLimitationsType())); target.add(getContent()); } private void deleteLimitationPerformed(AjaxRequestTarget target, ListItem<PropertyLimitationsTypeDto> item){ changeState = ChangeState.SKIP; model.getObject().remove(item.getModelObject()); target.add(getContent()); } private void cancelPerformed(AjaxRequestTarget target){ close(target); } protected void savePerformed(AjaxRequestTarget target){ List<PropertyLimitationsTypeDto> list = model.getObject(); List<PropertyLimitationsType> outputList = new ArrayList<>(); for(PropertyLimitationsTypeDto dto: list){ outputList.add(dto.prepareDtoForSave()); } inputModel.setObject(outputList); close(target); } }
apache-2.0
lyg123/sharding-jdbc
sharding-jdbc-config-parent/sharding-jdbc-config-common/src/test/java/com/dangdang/ddframe/rdb/sharding/config/common/fixture/IncrementIdGenerator.java
860
/* * Copyright 1999-2015 dangdang.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * </p> */ package com.dangdang.ddframe.rdb.sharding.config.common.fixture; public class IncrementIdGenerator extends AbstractNumberIdGenerator { @Override public Number generateId() { return getSequence().incrementAndGet(); } }
apache-2.0
CaoYouXin/serveV2
server/server/src/util/StringUtil.java
1729
package util; import java.math.BigInteger; import java.security.MessageDigest; public class StringUtil { /** * 对字符串md5加密 * * @param str * @return */ public static String getMD5(String str) { try { // 生成一个MD5加密计算摘要 MessageDigest md = MessageDigest.getInstance("MD5"); // 计算md5函数 md.update(str.getBytes()); // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 return new BigInteger(1, md.digest()).toString(16); } catch (Exception e) { throw new RuntimeException("MD5加密出现错误"); } } public static int indexOf(String str, int index, String... search) { int indexOf = -1; for (String c : search) { indexOf = str.indexOf(c, index); if (-1 != indexOf) { return indexOf; } } return indexOf; } public static int indexOf(String str, int index, char... search) { int indexOf = -1; for (char c : search) { indexOf = str.indexOf(c, index); if (-1 != indexOf) { return indexOf; } } return indexOf; } public static String cutPrefix(String str, String... prefix) { for (String s : prefix) { if (str.startsWith(s)) { return str.substring(s.length()); } } return str; } }
apache-2.0
fabric8io/kubernetes-client
kubernetes-model-generator/kubernetes-model-common/src/main/java/io/fabric8/kubernetes/model/Scope.java
1077
/** * Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.model; /** * Represents the scope of a resource in the cluster. Resources can either be cluster-scoped or only * are visible within the confines of a given namespace. */ public enum Scope { NAMESPACED("Namespaced"), CLUSTER("Cluster"); private final String value; Scope(String value) { this.value = value; } public String value() { return value; } @Override public String toString() { return value; } }
apache-2.0
eriksuta/fidm
fidm/src/main/java/com/esuta/fidm/model/federation/client/GenericListRestResponse.java
1415
package com.esuta.fidm.model.federation.client; import com.esuta.fidm.repository.schema.core.ObjectType; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author shood * */ public class GenericListRestResponse<T extends Serializable> extends SimpleRestResponse{ private List<T> values; public GenericListRestResponse(){} public GenericListRestResponse(List<T> values) { this.values = values; } public GenericListRestResponse(int status, String message, List<T> values) { super(status, message); this.values = values; } public List<T> getValues() { if(values == null){ values = new ArrayList<>(); } return values; } public void setValues(List<T> values) { this.values = values; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof GenericListRestResponse)) return false; if (!super.equals(o)) return false; GenericListRestResponse that = (GenericListRestResponse) o; if (values != null ? !values.equals(that.values) : that.values != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (values != null ? values.hashCode() : 0); return result; } }
apache-2.0
johnny0917/mamu
mamu.repository/src/main/java/com/mamu/repository/schema/property/accessor/GremlinEnumStringFieldPropertyAccessor.java
1405
package com.mamu.repository.schema.property.accessor; import java.lang.reflect.Field; /** * A {@link AbstractGremlinFieldPropertyAccessor} for enum properties that will be mapped with the name (String). * * @author Johnny */ public class GremlinEnumStringFieldPropertyAccessor extends AbstractGremlinFieldPropertyAccessor<String> { protected Class<? extends Enum> numnum; public GremlinEnumStringFieldPropertyAccessor(Field field, Class<?> numnum) { super(field); this.numnum = (Class<? extends Enum>) numnum; } @Override public String get(Object object) { try { Object result = field.get(object); if (result == null) { return null; } return result.toString(); } catch (IllegalAccessException e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public void set(Object object, String name) { try { if (name == null) { field.set(object, name); } for (Enum num : numnum.getEnumConstants()) { if (num.name().equals(name)) { field.set(object, num); break; } } } catch (IllegalAccessException e) { throw new IllegalStateException(e.getMessage(), e); } } }
apache-2.0
binarylife/Ydkd
app/src/main/java/com/bei/yd/utils/SharedPreferenceUtil.java
3133
package com.bei.yd.utils; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.bei.yd.app.YDApp; /** * sharedPreference工具类V1.0(后期改进) * * @author renxiaomin */ public class SharedPreferenceUtil { private static SharedPreferences mSharedPreferences; private static synchronized SharedPreferences getPreferneces() { if (mSharedPreferences == null) { mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(YDApp .mContext); } return mSharedPreferences; } /** * 打印所有 */ public static void print() { System.out.println(getPreferneces().getAll()); } /** * 清空保存在默认SharePreference下的所有数据 */ public static void clear() { getPreferneces().edit().clear().commit(); } /** * 保存字符串 * * @return */ public static void putString(String key, String value) { getPreferneces().edit().putString(key, value).commit(); } /** * 读取字符串 * * @param key * @return */ public static String getString(String key) { return getPreferneces().getString(key, null); } /** * 读取字符串由默认值 * * @param key * @return */ public static String getString(String key, String defaultStr) { return getPreferneces().getString(key, defaultStr); } /** * 保存整型值 * * @return */ public static void putInt(String key, int value) { getPreferneces().edit().putInt(key, value).commit(); } /** * 读取整型值 * * @param key * @return */ public static int getInt(String key) { return getPreferneces().getInt(key, 0); } /** * 读取整型值 * * @param key * @param defaultValue * @return */ public static int getInt(String key, int defaultValue) { return getPreferneces().getInt(key, defaultValue); } /** * 保存布尔值 * * @return */ public static void putBoolean(String key, Boolean value) { getPreferneces().edit().putBoolean(key, value).commit(); } public static void putLong(String key, long value) { getPreferneces().edit().putLong(key, value).commit(); } public static long getLong(String key) { return getPreferneces().getLong(key, 0); } /** * t 读取布尔值 * * @param key * @return */ public static boolean getBoolean(String key, boolean defValue) { return getPreferneces().getBoolean(key, defValue); } /** * 移除字段 * * @return */ public static void removeString(String key) { getPreferneces().edit().remove(key).commit(); } /** * 获取SharedPreferences(要主动commit) * * @return APP的SharedPreferences对象 */ public static SharedPreferences getSharedPreferences() { return getPreferneces(); } }
apache-2.0
NotFound403/WePay
src/main/java/cn/felord/wepay/ali/sdk/api/response/AlipayMarketingCardOpenResponse.java
1046
package cn.felord.wepay.ali.sdk.api.response; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; import cn.felord.wepay.ali.sdk.api.domain.MerchantCard; import cn.felord.wepay.ali.sdk.api.AlipayResponse; /** * ALIPAY API: alipay.marketing.card.open response. * * @author auto create * @version $Id: $Id */ public class AlipayMarketingCardOpenResponse extends AlipayResponse { private static final long serialVersionUID = 6313343285629938676L; /** * 商户卡信息(包括支付宝分配的业务卡号) */ @ApiField("card_info") private MerchantCard cardInfo; /** * <p>Setter for the field <code>cardInfo</code>.</p> * * @param cardInfo a {@link cn.felord.wepay.ali.sdk.api.domain.MerchantCard} object. */ public void setCardInfo(MerchantCard cardInfo) { this.cardInfo = cardInfo; } /** * <p>Getter for the field <code>cardInfo</code>.</p> * * @return a {@link cn.felord.wepay.ali.sdk.api.domain.MerchantCard} object. */ public MerchantCard getCardInfo( ) { return this.cardInfo; } }
apache-2.0
ox-it/cucm-http-api
src/main/java/com/cisco/axl/api/_8/GetAppServerInfoRes.java
3426
package com.cisco.axl.api._8; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for GetAppServerInfoRes complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="GetAppServerInfoRes"> * &lt;complexContent> * &lt;extension base="{http://www.cisco.com/AXL/API/8.0}APIResponse"> * &lt;sequence> * &lt;element name="return"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appServerInfo" type="{http://www.cisco.com/AXL/API/8.0}RAppServerInfo"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GetAppServerInfoRes", propOrder = { "_return" }) public class GetAppServerInfoRes extends APIResponse { @XmlElement(name = "return", required = true) protected GetAppServerInfoRes.Return _return; /** * Gets the value of the return property. * * @return * possible object is * {@link GetAppServerInfoRes.Return } * */ public GetAppServerInfoRes.Return getReturn() { return _return; } /** * Sets the value of the return property. * * @param value * allowed object is * {@link GetAppServerInfoRes.Return } * */ public void setReturn(GetAppServerInfoRes.Return value) { this._return = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appServerInfo" type="{http://www.cisco.com/AXL/API/8.0}RAppServerInfo"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "appServerInfo" }) public static class Return { @XmlElement(required = true) protected RAppServerInfo appServerInfo; /** * Gets the value of the appServerInfo property. * * @return * possible object is * {@link RAppServerInfo } * */ public RAppServerInfo getAppServerInfo() { return appServerInfo; } /** * Sets the value of the appServerInfo property. * * @param value * allowed object is * {@link RAppServerInfo } * */ public void setAppServerInfo(RAppServerInfo value) { this.appServerInfo = value; } } }
apache-2.0
TianYunZi/15springcloud
3.1.4.spring-cloud-high-avaliable-peer02/src/main/java/com/boot/Ch314Application.java
445
package com.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * Created by XJX on 2017/6/18. */ @SpringBootApplication @EnableEurekaServer public class Ch314Application { public static void main(String[] args) { SpringApplication.run(Ch314Application.class, args); } }
apache-2.0
google-business-communications/java-businesscommunications
com/google/api/services/businesscommunications/v1/model/RequestAgentVerificationRequest.java
2528
/* * 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. */ /* * This code was generated by https://github.com/google/apis-client-generator/ * (build: 2021-09-08 15:02:56 EDT) * on 2021-09-08 at 19:02:57 UTC * Modify at your own risk. */ package com.google.api.services.businesscommunications.v1.model; /** * Request to begin business information verification for an agent. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Business Communications. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class RequestAgentVerificationRequest extends com.google.api.client.json.GenericJson { /** * Required. Verification contact details for the agent. * The value may be {@code null}. */ @com.google.api.client.util.Key private AgentVerificationContact agentVerificationContact; /** * Required. Verification contact details for the agent. * @return value or {@code null} for none */ public AgentVerificationContact getAgentVerificationContact() { return agentVerificationContact; } /** * Required. Verification contact details for the agent. * @param agentVerificationContact agentVerificationContact or {@code null} for none */ public RequestAgentVerificationRequest setAgentVerificationContact(AgentVerificationContact agentVerificationContact) { this.agentVerificationContact = agentVerificationContact; return this; } @Override public RequestAgentVerificationRequest set(String fieldName, Object value) { return (RequestAgentVerificationRequest) super.set(fieldName, value); } @Override public RequestAgentVerificationRequest clone() { return (RequestAgentVerificationRequest) super.clone(); } }
apache-2.0
SolaceLabs/solace-integration-guides
src/weblogic/ConsumerMDB.java
1782
@TransactionManagement(value = TransactionManagementType.BEAN) @TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED) // Perform JNDI lookups on the Weblogic's local JNDI store @MessageDriven( activationConfig = { @ActivationConfigProperty( propertyName="connectionFactoryJndiName", propertyValue="JNDI/J2C/CF"), @ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty( propertyName="destinationJndiName", propertyValue="JNDI/J2C/Q/requests") }) //// Alternative activation configuration to perform JNDI lookups //// on the Solace router by specifying the resource adapter’s JNDI name //@MessageDriven( // activationConfig = { // @ActivationConfigProperty( // propertyName="connectionFactoryJndiName", // propertyValue="JNDI/Sol/CF"), // @ActivationConfigProperty( // propertyName="destinationType", // propertyValue="javax.jms.Queue"), // @ActivationConfigProperty( // propertyName="destination", // propertyValue="JNDI/Sol/Q/requests"), // @ActivationConfigProperty( // propertyName="resourceAdapterJndiName", // propertyValue="JNDI/J2C/RA/sol-jms-ra") // }) public class ConsumerMDB implements MessageListener { @EJB(beanName = "ProducerSB", beanInterface=ProducerSBLocal.class) ProducerSBLocal sb; public ConsumerMDB() { } public void onMessage(Message message) { String msg = message.toString(); System.out.println(Thread.currentThread().getName() + " - ConsumerMDB: received message: " + msg); try { // Send reply message sb.sendMessage(); } catch (JMSException e) { throw new EJBException("Error while sending reply message", e); } } }
apache-2.0
HsingPeng/ALLGO
ALLGO_client/src/cn/edu/njupt/allgo/vo/PrivateMessageVo.java
3126
package cn.edu.njupt.allgo.vo; import com.lidroid.xutils.db.annotation.Column; import com.lidroid.xutils.db.annotation.Id; import com.lidroid.xutils.db.annotation.NoAutoIncrement; import com.lidroid.xutils.db.annotation.Table; @Table(name = "privatemessage") public class PrivateMessageVo { @Id(column = "messageid") @NoAutoIncrement private int messageid; @Column(column = "senderuid") private int senderuid; @Column(column = "sendername") private String sendername; @Column(column = "receiveruid") private int receiveruid; @Column(column = "receivename") private String receivename; @Column(column = "contents") private String contents; @Column(column = "sendtime") private String sendtime; public PrivateMessageVo() { super(); } /** * * @param messageid * @param senderuid * @param sendername * @param receiveruid * @param receivename * @param contents * @param sendtime */ public PrivateMessageVo(int messageid, int senderuid, String sendername, int receiveruid, String receivename, String contents, String sendtime) { super(); this.messageid = messageid; this.senderuid = senderuid; this.sendername = sendername; this.receiveruid = receiveruid; this.receivename = receivename; this.contents = contents; this.sendtime = sendtime; } public int getMessageid() { return messageid; } public void setMessageid(int messageid) { this.messageid = messageid; } public int getSenderuid() { return senderuid; } public void setSenderuid(int senderuid) { this.senderuid = senderuid; } public String getSendername() { return sendername; } public void setSendername(String sendername) { this.sendername = sendername; } public int getReceiveruid() { return receiveruid; } public void setReceiveruid(int receiveruid) { this.receiveruid = receiveruid; } public String getReceivename() { return receivename; } public void setReceivename(String receivename) { this.receivename = receivename; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public String getSendtime() { return sendtime; } public void setSendtime(String sendtime) { this.sendtime = sendtime; } @Override public String toString() { return "PrivateMessageVo [messageid=" + messageid + ", senderuid=" + senderuid + ", sendername=" + sendername + ", receiveruid=" + receiveruid + ", receivename=" + receivename + ", contents=" + contents + ", sendtime=" + sendtime + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + messageid; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrivateMessageVo other = (PrivateMessageVo) obj; if (messageid != other.messageid) return false; return true; } }
apache-2.0
ctripcorp/x-pipe
redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/proxy/parser/route/ProxyRouteParser.java
437
package com.ctrip.xpipe.redis.core.proxy.parser.route; import com.ctrip.xpipe.proxy.ProxyEndpoint; import com.ctrip.xpipe.redis.core.proxy.parser.ProxyOptionParser; import java.util.List; /** * @author chen.zhu * <p> * May 04, 2018 */ public interface ProxyRouteParser extends ProxyOptionParser { void removeNextNodes(); String getContent(); List<ProxyEndpoint> getNextEndpoints(); String getFinalStation(); }
apache-2.0
burberius/eve-esi
src/main/java/net/troja/eve/esi/api/ContractsApi.java
215701
/* * EVE Swagger Interface * An OpenAPI for EVE Online * * The version of the OpenAPI document: 1.10.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package net.troja.eve.esi.api; import net.troja.eve.esi.ApiCallback; import net.troja.eve.esi.ApiClient; import net.troja.eve.esi.ApiException; import net.troja.eve.esi.ApiResponse; import net.troja.eve.esi.Configuration; import net.troja.eve.esi.Pair; import net.troja.eve.esi.ProgressRequestBody; import net.troja.eve.esi.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import net.troja.eve.esi.model.CharacterContractsBidsResponse; import net.troja.eve.esi.model.CharacterContractsItemsResponse; import net.troja.eve.esi.model.CharacterContractsResponse; import net.troja.eve.esi.model.CorporationContractsBidsResponse; import net.troja.eve.esi.model.CorporationContractsItemsResponse; import net.troja.eve.esi.model.CorporationContractsResponse; import net.troja.eve.esi.model.PublicContractsBidsResponse; import net.troja.eve.esi.model.PublicContractsItemsResponse; import net.troja.eve.esi.model.PublicContractsResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ContractsApi { private ApiClient localVarApiClient; public ContractsApi() { this(Configuration.getDefaultApiClient()); } public ContractsApi(ApiClient apiClient) { this.localVarApiClient = apiClient; } public ApiClient getApiClient() { return localVarApiClient; } public void setApiClient(ApiClient apiClient) { this.localVarApiClient = apiClient; } /** * Build call for getCharactersCharacterIdContracts * * @param characterId * An EVE character ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCharactersCharacterIdContractsCall(Integer characterId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/characters/{character_id}/contracts/".replaceAll("\\{" + "character_id" + "\\}", localVarApiClient.escapeString(characterId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } if (token != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("token", token)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "evesso" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getCharactersCharacterIdContractsValidateBeforeCall(Integer characterId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback _callback) throws ApiException { // verify the required parameter 'characterId' is set if (characterId == null) { throw new ApiException( "Missing the required parameter 'characterId' when calling getCharactersCharacterIdContracts(Async)"); } okhttp3.Call localVarCall = getCharactersCharacterIdContractsCall(characterId, datasource, ifNoneMatch, page, token, _callback); return localVarCall; } /** * Get contracts Returns contracts available to a character, only if the * character is issuer, acceptor or assignee. Only returns contracts no * older than 30 days, or if the status is \&quot;in_progress\&quot;. --- * This route is cached for up to 300 seconds * * @param characterId * An EVE character ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @return List&lt;CharacterContractsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<CharacterContractsResponse> getCharactersCharacterIdContracts(Integer characterId, String datasource, String ifNoneMatch, Integer page, String token) throws ApiException { ApiResponse<List<CharacterContractsResponse>> localVarResp = getCharactersCharacterIdContractsWithHttpInfo( characterId, datasource, ifNoneMatch, page, token); return localVarResp.getData(); } /** * Get contracts Returns contracts available to a character, only if the * character is issuer, acceptor or assignee. Only returns contracts no * older than 30 days, or if the status is \&quot;in_progress\&quot;. --- * This route is cached for up to 300 seconds * * @param characterId * An EVE character ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @return ApiResponse&lt;List&lt;CharacterContractsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<CharacterContractsResponse>> getCharactersCharacterIdContractsWithHttpInfo( Integer characterId, String datasource, String ifNoneMatch, Integer page, String token) throws ApiException { okhttp3.Call localVarCall = getCharactersCharacterIdContractsValidateBeforeCall(characterId, datasource, ifNoneMatch, page, token, null); Type localVarReturnType = new TypeToken<List<CharacterContractsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get contracts (asynchronously) Returns contracts available to a * character, only if the character is issuer, acceptor or assignee. Only * returns contracts no older than 30 days, or if the status is * \&quot;in_progress\&quot;. --- This route is cached for up to 300 seconds * * @param characterId * An EVE character ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCharactersCharacterIdContractsAsync(Integer characterId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback<List<CharacterContractsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getCharactersCharacterIdContractsValidateBeforeCall(characterId, datasource, ifNoneMatch, page, token, _callback); Type localVarReturnType = new TypeToken<List<CharacterContractsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getCharactersCharacterIdContractsContractIdBids * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCharactersCharacterIdContractsContractIdBidsCall(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/characters/{character_id}/contracts/{contract_id}/bids/".replaceAll( "\\{" + "character_id" + "\\}", localVarApiClient.escapeString(characterId.toString())).replaceAll( "\\{" + "contract_id" + "\\}", localVarApiClient.escapeString(contractId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (token != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("token", token)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "evesso" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getCharactersCharacterIdContractsContractIdBidsValidateBeforeCall(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token, final ApiCallback _callback) throws ApiException { // verify the required parameter 'characterId' is set if (characterId == null) { throw new ApiException( "Missing the required parameter 'characterId' when calling getCharactersCharacterIdContractsContractIdBids(Async)"); } // verify the required parameter 'contractId' is set if (contractId == null) { throw new ApiException( "Missing the required parameter 'contractId' when calling getCharactersCharacterIdContractsContractIdBids(Async)"); } okhttp3.Call localVarCall = getCharactersCharacterIdContractsContractIdBidsCall(characterId, contractId, datasource, ifNoneMatch, token, _callback); return localVarCall; } /** * Get contract bids Lists bids on a particular auction contract --- This * route is cached for up to 300 seconds SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @return List&lt;CharacterContractsBidsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<CharacterContractsBidsResponse> getCharactersCharacterIdContractsContractIdBids(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token) throws ApiException { ApiResponse<List<CharacterContractsBidsResponse>> localVarResp = getCharactersCharacterIdContractsContractIdBidsWithHttpInfo( characterId, contractId, datasource, ifNoneMatch, token); return localVarResp.getData(); } /** * Get contract bids Lists bids on a particular auction contract --- This * route is cached for up to 300 seconds SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @return ApiResponse&lt;List&lt;CharacterContractsBidsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<CharacterContractsBidsResponse>> getCharactersCharacterIdContractsContractIdBidsWithHttpInfo( Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token) throws ApiException { okhttp3.Call localVarCall = getCharactersCharacterIdContractsContractIdBidsValidateBeforeCall(characterId, contractId, datasource, ifNoneMatch, token, null); Type localVarReturnType = new TypeToken<List<CharacterContractsBidsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get contract bids (asynchronously) Lists bids on a particular auction * contract --- This route is cached for up to 300 seconds SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCharactersCharacterIdContractsContractIdBidsAsync(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token, final ApiCallback<List<CharacterContractsBidsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getCharactersCharacterIdContractsContractIdBidsValidateBeforeCall(characterId, contractId, datasource, ifNoneMatch, token, _callback); Type localVarReturnType = new TypeToken<List<CharacterContractsBidsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getCharactersCharacterIdContractsContractIdItems * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCharactersCharacterIdContractsContractIdItemsCall(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/characters/{character_id}/contracts/{contract_id}/items/".replaceAll( "\\{" + "character_id" + "\\}", localVarApiClient.escapeString(characterId.toString())).replaceAll( "\\{" + "contract_id" + "\\}", localVarApiClient.escapeString(contractId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (token != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("token", token)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "evesso" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getCharactersCharacterIdContractsContractIdItemsValidateBeforeCall(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token, final ApiCallback _callback) throws ApiException { // verify the required parameter 'characterId' is set if (characterId == null) { throw new ApiException( "Missing the required parameter 'characterId' when calling getCharactersCharacterIdContractsContractIdItems(Async)"); } // verify the required parameter 'contractId' is set if (contractId == null) { throw new ApiException( "Missing the required parameter 'contractId' when calling getCharactersCharacterIdContractsContractIdItems(Async)"); } okhttp3.Call localVarCall = getCharactersCharacterIdContractsContractIdItemsCall(characterId, contractId, datasource, ifNoneMatch, token, _callback); return localVarCall; } /** * Get contract items Lists items of a particular contract --- This route is * cached for up to 3600 seconds SSO Scope: * esi-contracts.read_corporation_contracts.v1 SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @return List&lt;CharacterContractsItemsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<CharacterContractsItemsResponse> getCharactersCharacterIdContractsContractIdItems(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token) throws ApiException { ApiResponse<List<CharacterContractsItemsResponse>> localVarResp = getCharactersCharacterIdContractsContractIdItemsWithHttpInfo( characterId, contractId, datasource, ifNoneMatch, token); return localVarResp.getData(); } /** * Get contract items Lists items of a particular contract --- This route is * cached for up to 3600 seconds SSO Scope: * esi-contracts.read_corporation_contracts.v1 SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @return ApiResponse&lt;List&lt;CharacterContractsItemsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<CharacterContractsItemsResponse>> getCharactersCharacterIdContractsContractIdItemsWithHttpInfo( Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token) throws ApiException { okhttp3.Call localVarCall = getCharactersCharacterIdContractsContractIdItemsValidateBeforeCall(characterId, contractId, datasource, ifNoneMatch, token, null); Type localVarReturnType = new TypeToken<List<CharacterContractsItemsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get contract items (asynchronously) Lists items of a particular contract * --- This route is cached for up to 3600 seconds SSO Scope: * esi-contracts.read_corporation_contracts.v1 SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param characterId * An EVE character ID (required) * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCharactersCharacterIdContractsContractIdItemsAsync(Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token, final ApiCallback<List<CharacterContractsItemsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getCharactersCharacterIdContractsContractIdItemsValidateBeforeCall(characterId, contractId, datasource, ifNoneMatch, token, _callback); Type localVarReturnType = new TypeToken<List<CharacterContractsItemsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getContractsPublicBidsContractId * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getContractsPublicBidsContractIdCall(Integer contractId, String datasource, String ifNoneMatch, Integer page, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/contracts/public/bids/{contract_id}/".replaceAll("\\{" + "contract_id" + "\\}", localVarApiClient.escapeString(contractId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] {}; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getContractsPublicBidsContractIdValidateBeforeCall(Integer contractId, String datasource, String ifNoneMatch, Integer page, final ApiCallback _callback) throws ApiException { // verify the required parameter 'contractId' is set if (contractId == null) { throw new ApiException( "Missing the required parameter 'contractId' when calling getContractsPublicBidsContractId(Async)"); } okhttp3.Call localVarCall = getContractsPublicBidsContractIdCall(contractId, datasource, ifNoneMatch, page, _callback); return localVarCall; } /** * Get public contract bids Lists bids on a public auction contract --- This * route is cached for up to 300 seconds * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @return List&lt;PublicContractsBidsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<PublicContractsBidsResponse> getContractsPublicBidsContractId(Integer contractId, String datasource, String ifNoneMatch, Integer page) throws ApiException { ApiResponse<List<PublicContractsBidsResponse>> localVarResp = getContractsPublicBidsContractIdWithHttpInfo( contractId, datasource, ifNoneMatch, page); return localVarResp.getData(); } /** * Get public contract bids Lists bids on a public auction contract --- This * route is cached for up to 300 seconds * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @return ApiResponse&lt;List&lt;PublicContractsBidsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<PublicContractsBidsResponse>> getContractsPublicBidsContractIdWithHttpInfo( Integer contractId, String datasource, String ifNoneMatch, Integer page) throws ApiException { okhttp3.Call localVarCall = getContractsPublicBidsContractIdValidateBeforeCall(contractId, datasource, ifNoneMatch, page, null); Type localVarReturnType = new TypeToken<List<PublicContractsBidsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get public contract bids (asynchronously) Lists bids on a public auction * contract --- This route is cached for up to 300 seconds * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getContractsPublicBidsContractIdAsync(Integer contractId, String datasource, String ifNoneMatch, Integer page, final ApiCallback<List<PublicContractsBidsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getContractsPublicBidsContractIdValidateBeforeCall(contractId, datasource, ifNoneMatch, page, _callback); Type localVarReturnType = new TypeToken<List<PublicContractsBidsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getContractsPublicItemsContractId * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getContractsPublicItemsContractIdCall(Integer contractId, String datasource, String ifNoneMatch, Integer page, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/contracts/public/items/{contract_id}/".replaceAll("\\{" + "contract_id" + "\\}", localVarApiClient.escapeString(contractId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] {}; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getContractsPublicItemsContractIdValidateBeforeCall(Integer contractId, String datasource, String ifNoneMatch, Integer page, final ApiCallback _callback) throws ApiException { // verify the required parameter 'contractId' is set if (contractId == null) { throw new ApiException( "Missing the required parameter 'contractId' when calling getContractsPublicItemsContractId(Async)"); } okhttp3.Call localVarCall = getContractsPublicItemsContractIdCall(contractId, datasource, ifNoneMatch, page, _callback); return localVarCall; } /** * Get public contract items Lists items of a public contract --- This route * is cached for up to 3600 seconds * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @return List&lt;PublicContractsItemsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<PublicContractsItemsResponse> getContractsPublicItemsContractId(Integer contractId, String datasource, String ifNoneMatch, Integer page) throws ApiException { ApiResponse<List<PublicContractsItemsResponse>> localVarResp = getContractsPublicItemsContractIdWithHttpInfo( contractId, datasource, ifNoneMatch, page); return localVarResp.getData(); } /** * Get public contract items Lists items of a public contract --- This route * is cached for up to 3600 seconds * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @return ApiResponse&lt;List&lt;PublicContractsItemsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<PublicContractsItemsResponse>> getContractsPublicItemsContractIdWithHttpInfo( Integer contractId, String datasource, String ifNoneMatch, Integer page) throws ApiException { okhttp3.Call localVarCall = getContractsPublicItemsContractIdValidateBeforeCall(contractId, datasource, ifNoneMatch, page, null); Type localVarReturnType = new TypeToken<List<PublicContractsItemsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get public contract items (asynchronously) Lists items of a public * contract --- This route is cached for up to 3600 seconds * * @param contractId * ID of a contract (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>204</td> * <td>Contract expired or recently accepted by * player</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getContractsPublicItemsContractIdAsync(Integer contractId, String datasource, String ifNoneMatch, Integer page, final ApiCallback<List<PublicContractsItemsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getContractsPublicItemsContractIdValidateBeforeCall(contractId, datasource, ifNoneMatch, page, _callback); Type localVarReturnType = new TypeToken<List<PublicContractsItemsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getContractsPublicRegionId * * @param regionId * An EVE region id (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getContractsPublicRegionIdCall(Integer regionId, String datasource, String ifNoneMatch, Integer page, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/contracts/public/{region_id}/".replaceAll("\\{" + "region_id" + "\\}", localVarApiClient.escapeString(regionId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] {}; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getContractsPublicRegionIdValidateBeforeCall(Integer regionId, String datasource, String ifNoneMatch, Integer page, final ApiCallback _callback) throws ApiException { // verify the required parameter 'regionId' is set if (regionId == null) { throw new ApiException( "Missing the required parameter 'regionId' when calling getContractsPublicRegionId(Async)"); } okhttp3.Call localVarCall = getContractsPublicRegionIdCall(regionId, datasource, ifNoneMatch, page, _callback); return localVarCall; } /** * Get public contracts Returns a paginated list of all public contracts in * the given region --- This route is cached for up to 1800 seconds * * @param regionId * An EVE region id (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @return List&lt;PublicContractsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<PublicContractsResponse> getContractsPublicRegionId(Integer regionId, String datasource, String ifNoneMatch, Integer page) throws ApiException { ApiResponse<List<PublicContractsResponse>> localVarResp = getContractsPublicRegionIdWithHttpInfo(regionId, datasource, ifNoneMatch, page); return localVarResp.getData(); } /** * Get public contracts Returns a paginated list of all public contracts in * the given region --- This route is cached for up to 1800 seconds * * @param regionId * An EVE region id (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @return ApiResponse&lt;List&lt;PublicContractsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<PublicContractsResponse>> getContractsPublicRegionIdWithHttpInfo(Integer regionId, String datasource, String ifNoneMatch, Integer page) throws ApiException { okhttp3.Call localVarCall = getContractsPublicRegionIdValidateBeforeCall(regionId, datasource, ifNoneMatch, page, null); Type localVarReturnType = new TypeToken<List<PublicContractsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get public contracts (asynchronously) Returns a paginated list of all * public contracts in the given region --- This route is cached for up to * 1800 seconds * * @param regionId * An EVE region id (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getContractsPublicRegionIdAsync(Integer regionId, String datasource, String ifNoneMatch, Integer page, final ApiCallback<List<PublicContractsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getContractsPublicRegionIdValidateBeforeCall(regionId, datasource, ifNoneMatch, page, _callback); Type localVarReturnType = new TypeToken<List<PublicContractsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getCorporationsCorporationIdContracts * * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCorporationsCorporationIdContractsCall(Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/corporations/{corporation_id}/contracts/".replaceAll("\\{" + "corporation_id" + "\\}", localVarApiClient.escapeString(corporationId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } if (token != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("token", token)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "evesso" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getCorporationsCorporationIdContractsValidateBeforeCall(Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback _callback) throws ApiException { // verify the required parameter 'corporationId' is set if (corporationId == null) { throw new ApiException( "Missing the required parameter 'corporationId' when calling getCorporationsCorporationIdContracts(Async)"); } okhttp3.Call localVarCall = getCorporationsCorporationIdContractsCall(corporationId, datasource, ifNoneMatch, page, token, _callback); return localVarCall; } /** * Get corporation contracts Returns contracts available to a corporation, * only if the corporation is issuer, acceptor or assignee. Only returns * contracts no older than 30 days, or if the status is * \&quot;in_progress\&quot;. --- This route is cached for up to 300 seconds * * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @return List&lt;CorporationContractsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<CorporationContractsResponse> getCorporationsCorporationIdContracts(Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token) throws ApiException { ApiResponse<List<CorporationContractsResponse>> localVarResp = getCorporationsCorporationIdContractsWithHttpInfo( corporationId, datasource, ifNoneMatch, page, token); return localVarResp.getData(); } /** * Get corporation contracts Returns contracts available to a corporation, * only if the corporation is issuer, acceptor or assignee. Only returns * contracts no older than 30 days, or if the status is * \&quot;in_progress\&quot;. --- This route is cached for up to 300 seconds * * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @return ApiResponse&lt;List&lt;CorporationContractsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<CorporationContractsResponse>> getCorporationsCorporationIdContractsWithHttpInfo( Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token) throws ApiException { okhttp3.Call localVarCall = getCorporationsCorporationIdContractsValidateBeforeCall(corporationId, datasource, ifNoneMatch, page, token, null); Type localVarReturnType = new TypeToken<List<CorporationContractsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get corporation contracts (asynchronously) Returns contracts available to * a corporation, only if the corporation is issuer, acceptor or assignee. * Only returns contracts no older than 30 days, or if the status is * \&quot;in_progress\&quot;. --- This route is cached for up to 300 seconds * * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of contracts</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCorporationsCorporationIdContractsAsync(Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback<List<CorporationContractsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getCorporationsCorporationIdContractsValidateBeforeCall(corporationId, datasource, ifNoneMatch, page, token, _callback); Type localVarReturnType = new TypeToken<List<CorporationContractsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getCorporationsCorporationIdContractsContractIdBids * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCorporationsCorporationIdContractsContractIdBidsCall(Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/corporations/{corporation_id}/contracts/{contract_id}/bids/".replaceAll( "\\{" + "contract_id" + "\\}", localVarApiClient.escapeString(contractId.toString())).replaceAll( "\\{" + "corporation_id" + "\\}", localVarApiClient.escapeString(corporationId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } if (token != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("token", token)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "evesso" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getCorporationsCorporationIdContractsContractIdBidsValidateBeforeCall(Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback _callback) throws ApiException { // verify the required parameter 'contractId' is set if (contractId == null) { throw new ApiException( "Missing the required parameter 'contractId' when calling getCorporationsCorporationIdContractsContractIdBids(Async)"); } // verify the required parameter 'corporationId' is set if (corporationId == null) { throw new ApiException( "Missing the required parameter 'corporationId' when calling getCorporationsCorporationIdContractsContractIdBids(Async)"); } okhttp3.Call localVarCall = getCorporationsCorporationIdContractsContractIdBidsCall(contractId, corporationId, datasource, ifNoneMatch, page, token, _callback); return localVarCall; } /** * Get corporation contract bids Lists bids on a particular auction contract * --- This route is cached for up to 3600 seconds SSO Scope: * esi-contracts.read_corporation_contracts.v1 * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @return List&lt;CorporationContractsBidsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<CorporationContractsBidsResponse> getCorporationsCorporationIdContractsContractIdBids( Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token) throws ApiException { ApiResponse<List<CorporationContractsBidsResponse>> localVarResp = getCorporationsCorporationIdContractsContractIdBidsWithHttpInfo( contractId, corporationId, datasource, ifNoneMatch, page, token); return localVarResp.getData(); } /** * Get corporation contract bids Lists bids on a particular auction contract * --- This route is cached for up to 3600 seconds SSO Scope: * esi-contracts.read_corporation_contracts.v1 * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @return ApiResponse&lt;List&lt;CorporationContractsBidsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<CorporationContractsBidsResponse>> getCorporationsCorporationIdContractsContractIdBidsWithHttpInfo( Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token) throws ApiException { okhttp3.Call localVarCall = getCorporationsCorporationIdContractsContractIdBidsValidateBeforeCall(contractId, corporationId, datasource, ifNoneMatch, page, token, null); Type localVarReturnType = new TypeToken<List<CorporationContractsBidsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get corporation contract bids (asynchronously) Lists bids on a particular * auction contract --- This route is cached for up to 3600 seconds SSO * Scope: esi-contracts.read_corporation_contracts.v1 * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param page * Which page of results to return (optional, default to 1) * @param token * Access token to use if unable to set a header (optional) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of bids</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * X-Pages - Maximum page number <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCorporationsCorporationIdContractsContractIdBidsAsync(Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback<List<CorporationContractsBidsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getCorporationsCorporationIdContractsContractIdBidsValidateBeforeCall(contractId, corporationId, datasource, ifNoneMatch, page, token, _callback); Type localVarReturnType = new TypeToken<List<CorporationContractsBidsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for getCorporationsCorporationIdContractsContractIdItems * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @param _callback * Callback for upload/download progress * @return Call to execute * @throws ApiException * If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCorporationsCorporationIdContractsContractIdItemsCall(Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, String token, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/corporations/{corporation_id}/contracts/{contract_id}/items/".replaceAll( "\\{" + "contract_id" + "\\}", localVarApiClient.escapeString(contractId.toString())).replaceAll( "\\{" + "corporation_id" + "\\}", localVarApiClient.escapeString(corporationId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (datasource != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("datasource", datasource)); } if (token != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("token", token)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (ifNoneMatch != null) { localVarHeaderParams.put("If-None-Match", localVarApiClient.parameterToString(ifNoneMatch)); } Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "evesso" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getCorporationsCorporationIdContractsContractIdItemsValidateBeforeCall(Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, String token, final ApiCallback _callback) throws ApiException { // verify the required parameter 'contractId' is set if (contractId == null) { throw new ApiException( "Missing the required parameter 'contractId' when calling getCorporationsCorporationIdContractsContractIdItems(Async)"); } // verify the required parameter 'corporationId' is set if (corporationId == null) { throw new ApiException( "Missing the required parameter 'corporationId' when calling getCorporationsCorporationIdContractsContractIdItems(Async)"); } okhttp3.Call localVarCall = getCorporationsCorporationIdContractsContractIdItemsCall(contractId, corporationId, datasource, ifNoneMatch, token, _callback); return localVarCall; } /** * Get corporation contract items Lists items of a particular contract --- * This route is cached for up to 3600 seconds SSO Scope: * esi-contracts.read_corporation_contracts.v1 SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @return List&lt;CorporationContractsItemsResponse&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public List<CorporationContractsItemsResponse> getCorporationsCorporationIdContractsContractIdItems( Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, String token) throws ApiException { ApiResponse<List<CorporationContractsItemsResponse>> localVarResp = getCorporationsCorporationIdContractsContractIdItemsWithHttpInfo( contractId, corporationId, datasource, ifNoneMatch, token); return localVarResp.getData(); } /** * Get corporation contract items Lists items of a particular contract --- * This route is cached for up to 3600 seconds SSO Scope: * esi-contracts.read_corporation_contracts.v1 SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @return ApiResponse&lt;List&lt;CorporationContractsItemsResponse&gt;&gt; * @throws ApiException * If fail to call the API, e.g. server error or cannot * deserialize the response body * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public ApiResponse<List<CorporationContractsItemsResponse>> getCorporationsCorporationIdContractsContractIdItemsWithHttpInfo( Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, String token) throws ApiException { okhttp3.Call localVarCall = getCorporationsCorporationIdContractsContractIdItemsValidateBeforeCall(contractId, corporationId, datasource, ifNoneMatch, token, null); Type localVarReturnType = new TypeToken<List<CorporationContractsItemsResponse>>() { }.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get corporation contract items (asynchronously) Lists items of a * particular contract --- This route is cached for up to 3600 seconds SSO * Scope: esi-contracts.read_corporation_contracts.v1 SSO Scope: * esi-contracts.read_character_contracts.v1 * * @param contractId * ID of a contract (required) * @param corporationId * An EVE corporation ID (required) * @param datasource * The server name you would like data from (optional, default to * tranquility) * @param ifNoneMatch * ETag from a previous request. A 304 will be returned if this * matches the current ETag (optional) * @param token * Access token to use if unable to set a header (optional) * @param _callback * The callback to be executed when the API call finishes * @return The request call * @throws ApiException * If fail to process the API call, e.g. serializing the request * body object * @http.response.details <table summary="Response Details" border="1"> * <tr> * <td>Status Code</td> * <td>Description</td> * <td>Response Headers</td> * </tr> * <tr> * <td>200</td> * <td>A list of items in this contract</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>304</td> * <td>Not modified</td> * <td>Cache-Control - The caching mechanism used <br> * ETag - RFC7232 compliant entity tag <br> * Expires - RFC7231 formatted datetime string <br> * Last-Modified - RFC7231 formatted datetime string * <br> * </td> * </tr> * <tr> * <td>400</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>401</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>403</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>404</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>420</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>422</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>500</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>502</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>503</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>504</td> * <td></td> * <td>-</td> * </tr> * <tr> * <td>520</td> * <td></td> * <td>-</td> * </tr> * </table> */ public okhttp3.Call getCorporationsCorporationIdContractsContractIdItemsAsync(Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, String token, final ApiCallback<List<CorporationContractsItemsResponse>> _callback) throws ApiException { okhttp3.Call localVarCall = getCorporationsCorporationIdContractsContractIdItemsValidateBeforeCall(contractId, corporationId, datasource, ifNoneMatch, token, _callback); Type localVarReturnType = new TypeToken<List<CorporationContractsItemsResponse>>() { }.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } }
apache-2.0
springfox/springfox
springfox-core/src/main/java/springfox/documentation/service/Documentation.java
3339
/* * * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 springfox.documentation.service; import springfox.documentation.common.ExternalDocumentation; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; public class Documentation { private final String groupName; private final String basePath; private final Map<String, List<ApiListing>> apiListings; private final Set<Tag> tags; private final ResourceListing resourceListing; private final Set<String> produces; private final Set<String> consumes; private final String host; private final Set<String> schemes; private final List<Server> servers = new ArrayList<>(); private final ExternalDocumentation externalDocumentation; private final List<VendorExtension> vendorExtensions; @SuppressWarnings("ParameterNumber") public Documentation( String groupName, String basePath, Set<Tag> tags, Map<String, List<ApiListing>> apiListings, ResourceListing resourceListing, Set<String> produces, Set<String> consumes, String host, Set<String> schemes, Collection<Server> servers, ExternalDocumentation externalDocumentation, Collection<VendorExtension> vendorExtensions) { this.groupName = groupName; this.basePath = basePath; this.tags = tags; this.apiListings = apiListings; this.resourceListing = resourceListing; this.produces = produces; this.consumes = consumes; this.host = host; this.schemes = schemes; this.servers.addAll(servers); this.externalDocumentation = externalDocumentation; this.vendorExtensions = new ArrayList<>(vendorExtensions); } public String getGroupName() { return groupName; } public Map<String, List<ApiListing>> getApiListings() { return apiListings; } public ResourceListing getResourceListing() { return resourceListing; } public Set<Tag> getTags() { return tags; } public String getBasePath() { return basePath; } public List<String> getProduces() { return new ArrayList<>(produces); } public String getHost() { return host; } public List<String> getSchemes() { return new ArrayList<>(schemes); } public List<String> getConsumes() { return new ArrayList<>(consumes); } public List<VendorExtension> getVendorExtensions() { return vendorExtensions; } public List<Server> getServers() { return servers; } public ExternalDocumentation getExternalDocumentation() { return externalDocumentation; } public void addServer(Server inferredServer) { if (!servers.contains(inferredServer)) { servers.add(inferredServer); } } }
apache-2.0
mohitajwani/ZoloStays
Zolostays/app/src/main/java/com/mohitajwani/zolostays/ViewModelHolder.java
964
package com.mohitajwani.zolostays; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; /** * Created by Mohit Ajwani. * Non-UI Fragment used to retain ViewModels. */ public class ViewModelHolder<VM> extends Fragment { private VM mViewModel; public ViewModelHolder() { } public static <M> ViewModelHolder createContainer(@NonNull M viewModel) { ViewModelHolder<M> viewModelContainer = new ViewModelHolder<>(); viewModelContainer.setViewModel(viewModel); return viewModelContainer; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Nullable public VM getViewmodel() { return mViewModel; } public void setViewModel(@NonNull VM viewModel) { mViewModel = viewModel; } }
apache-2.0
Philzen/cordova-android-multitouch-polyfill
test/src/org/apache/cordova/test/CordovaDriverAction.java
2222
/* 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.cordova.test; import org.apache.cordova.api.CordovaInterface; import org.apache.cordova.api.IPlugin; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class CordovaDriverAction extends Activity implements CordovaInterface { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void bindBackButton(boolean arg0) { // TODO Auto-generated method stub } @Override public void cancelLoadUrl() { // TODO Auto-generated method stub } @Override public Activity getActivity() { // TODO Auto-generated method stub return null; } @Override public boolean isBackButtonBound() { // TODO Auto-generated method stub return false; } @Override public Object onMessage(String arg0, Object arg1) { // TODO Auto-generated method stub return null; } @Override public void setActivityResultCallback(IPlugin arg0) { // TODO Auto-generated method stub } @Override public void startActivityForResult(IPlugin arg0, Intent arg1, int arg2) { // TODO Auto-generated method stub } }
apache-2.0
nilsga/trello-java-wrapper
src/test/java/com/julienvey/trello/integration/CardGetITCase.java
3225
package com.julienvey.trello.integration; import com.julienvey.trello.Trello; import com.julienvey.trello.TrelloHttpClient; import com.julienvey.trello.domain.Action; import com.julienvey.trello.domain.Attachment; import com.julienvey.trello.domain.Board; import com.julienvey.trello.domain.Card; import com.julienvey.trello.impl.TrelloImpl; import com.julienvey.trello.impl.http.ApacheHttpClient; import com.julienvey.trello.impl.http.AsyncTrelloHttpClient; import com.julienvey.trello.impl.http.RestTemplateHttpClient; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.fest.assertions.Assertions.assertThat; @RunWith(Parameterized.class) public class CardGetITCase { private static final String TEST_APPLICATION_KEY = "db555c528ce160c33305d2ea51ae1197"; public static final String CARD_ID = "518bab520967804c03002994"; private Trello trello; private TrelloHttpClient httpClient; @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{{new ApacheHttpClient()}, {new AsyncTrelloHttpClient()}, {new RestTemplateHttpClient()}}); } public CardGetITCase(TrelloHttpClient httpClient) { this.httpClient = httpClient; } @Before public void setUp() { trello = new TrelloImpl(TEST_APPLICATION_KEY, "", httpClient); } @Test public void testGetCard() { Card card = trello.getCard(CARD_ID); assertThat(card).isNotNull(); assertThat(card.getId()).isEqualTo(CARD_ID); assertThat(card.getIdBoard()).isEqualTo("518baad5b05dbf4703004852"); } @Test public void testGetCardByShortUrl() { Card card = trello.getCard("C1fXQHre"); assertThat(card).isNotNull(); assertThat(card.getId()).isEqualTo(CARD_ID); assertThat(card.getIdBoard()).isEqualTo("518baad5b05dbf4703004852"); } @Test public void testGetCardActions() { List<Action> cardActions = trello.getCardActions(CARD_ID); assertThat(cardActions).isNotNull(); assertThat(cardActions).hasSize(1); assertThat(cardActions.get(0).getId()).isEqualTo("5199029a7c4f3ca30a00136a"); } @Test public void testGetCardAttachments() { List<Attachment> cardAttachments = trello.getCardAttachments(CARD_ID); assertThat(cardAttachments).isNotNull(); assertThat(cardAttachments).hasSize(1); assertThat(cardAttachments.get(0).getId()).isEqualTo("519902b653ac28d57e00ec3b"); } @Test public void testGetCardAttachment() { Attachment cardAttachment = trello.getCardAttachment(CARD_ID, "519902b653ac28d57e00ec3b"); assertThat(cardAttachment).isNotNull(); assertThat(cardAttachment.getId()).isEqualTo("519902b653ac28d57e00ec3b"); } @Test public void testGetCardBoard() { Board cardBoard = trello.getCardBoard(CARD_ID); assertThat(cardBoard).isNotNull(); assertThat(cardBoard.getId()).isEqualTo("518baad5b05dbf4703004852"); } }
apache-2.0
EvilMcJerkface/atlasdb
atlasdb-impl-shared/src/main/java/com/palantir/atlasdb/transaction/service/WriteBatchingTransactionService.java
16544
/* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.transaction.service; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.Multimaps; import com.google.common.util.concurrent.ListenableFuture; import com.palantir.atlasdb.autobatch.Autobatchers; import com.palantir.atlasdb.autobatch.BatchElement; import com.palantir.atlasdb.autobatch.DisruptorAutobatcher; import com.palantir.atlasdb.futures.AtlasFutures; import com.palantir.atlasdb.keyvalue.api.Cell; import com.palantir.atlasdb.keyvalue.api.KeyAlreadyExistsException; import com.palantir.common.streams.KeyedStream; import com.palantir.lock.v2.TimelockService; import com.palantir.logsafe.Preconditions; import com.palantir.logsafe.SafeArg; import com.palantir.logsafe.UnsafeArg; import com.palantir.logsafe.exceptions.SafeIllegalStateException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import org.immutables.value.Value; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class coalesces write (that is, put-unless-exists) requests to an underlying {@link EncodingTransactionService}, * such that there is at most one request in flight at a given time. Read requests (gets) are not batched. * * Delegates are expected to throw {@link KeyAlreadyExistsException}s that have meaningful values for * {@link KeyAlreadyExistsException#getExistingKeys()}. */ public final class WriteBatchingTransactionService implements TransactionService { private static final Logger log = LoggerFactory.getLogger(WriteBatchingTransactionService.class); private final EncodingTransactionService delegate; private final DisruptorAutobatcher<TimestampPair, Void> autobatcher; private WriteBatchingTransactionService( EncodingTransactionService delegate, DisruptorAutobatcher<TimestampPair, Void> autobatcher) { this.delegate = delegate; this.autobatcher = autobatcher; } public static TransactionService create(EncodingTransactionService delegate) { DisruptorAutobatcher<TimestampPair, Void> autobatcher = Autobatchers.<TimestampPair, Void>independent( elements -> processBatch(delegate, elements)) .safeLoggablePurpose("write-batching-transaction-service") .build(); return new WriteBatchingTransactionService(delegate, autobatcher); } @CheckForNull @Override public Long get(long startTimestamp) { return delegate.get(startTimestamp); } @Override public Map<Long, Long> get(Iterable<Long> startTimestamps) { return delegate.get(startTimestamps); } @Override public ListenableFuture<Long> getAsync(long startTimestamp) { return delegate.getAsync(startTimestamp); } @Override public ListenableFuture<Map<Long, Long>> getAsync(Iterable<Long> startTimestamps) { return delegate.getAsync(startTimestamps); } @Override public void putUnlessExists(long startTimestamp, long commitTimestamp) throws KeyAlreadyExistsException { AtlasFutures.getUnchecked(autobatcher.apply(TimestampPair.of(startTimestamp, commitTimestamp))); } @Override public void close() { autobatcher.close(); delegate.close(); } /** * Semantics for batch processing: * * - If there are multiple requests to {@link TransactionService#putUnlessExists(long, long)} with the same * start timestamp, we will actually call the KVS with only one request from the batch for that start timestamp. * There are no guarantees as to which request we use. If that element was successfully put (if the whole * operation succeeded, or if the {@link KeyAlreadyExistsException} has partial successes), we return * success for that request, and throw {@link KeyAlreadyExistsException} for all other requests associated with * that start timestamp. If it failed and we know the key already exists, all requests associated with that * start timestamp are failed with a {@link KeyAlreadyExistsException}. Otherwise we will try again. * - If a {@link KeyAlreadyExistsException} is thrown, we fail out requests for keys present in the * {@link KeyAlreadyExistsException}, and then retry our request with those keys removed. If the * {@link KeyAlreadyExistsException} does not include any present keys, we throw an exception. * * Retrying does theoretically mean that in the worst case with N transactions in our batch, we may actually * require N calls to the database, though this is extremely unlikely especially because of the semantics of * {@link TimelockService#startIdentifiedAtlasDbTransactionBatch(int)}. * Alternatives considered included failing out all requests (which is likely to be inefficient and lead to * spurious retries on requests that actually committed), and re-submitting requests other than the failed one * for consideration in the next batch (which may achieve higher throughput, but could lead to starvation of old * requests). */ @VisibleForTesting static void processBatch( EncodingTransactionService delegate, List<BatchElement<TimestampPair, Void>> batchElements) { Multimap<Long, BatchElement<TimestampPair, Void>> startTimestampKeyedBatchElements = MultimapBuilder.hashKeys().hashSetValues().build(); batchElements.forEach(batchElement -> startTimestampKeyedBatchElements.put(batchElement.argument().startTimestamp(), batchElement)); while (!startTimestampKeyedBatchElements.isEmpty()) { Map<Long, BatchElement<TimestampPair, Void>> batch = extractSingleBatchForQuerying(startTimestampKeyedBatchElements); try { delegate.putUnlessExistsMultiple(KeyedStream.stream(batch) .map(batchElement -> batchElement.argument().commitTimestamp()) .collectToMap()); markBatchSuccessful(startTimestampKeyedBatchElements, batch); markAllRemainingRequestsAsFailed(delegate, startTimestampKeyedBatchElements.values()); return; } catch (KeyAlreadyExistsException exception) { handleFailedTimestamps(delegate, startTimestampKeyedBatchElements, batch, exception); handleSuccessfulTimestamps(delegate, startTimestampKeyedBatchElements, batch, exception); } } } private static void markAllRemainingRequestsAsFailed( EncodingTransactionService delegate, Collection<BatchElement<TimestampPair, Void>> batchElementsToFail) { batchElementsToFail.forEach(batchElem -> markPreemptivelyAsFailure(delegate, batchElem)); } private static void markPreemptivelyAsFailure( EncodingTransactionService delegate, BatchElement<TimestampPair, Void> batchElem) { Cell cell = delegate.getEncodingStrategy() .encodeStartTimestampAsCell(batchElem.argument().startTimestamp()); KeyAlreadyExistsException exception = new KeyAlreadyExistsException( "Failed because other client-side element succeeded", ImmutableList.of(cell)); batchElem.result().setException(exception); } private static void handleFailedTimestamps( EncodingTransactionService delegate, Multimap<Long, BatchElement<TimestampPair, Void>> startTimestampKeyedBatchElements, Map<Long, BatchElement<TimestampPair, Void>> batch, KeyAlreadyExistsException exception) { Set<Long> failedTimestamps = getAlreadyExistingStartTimestamps(delegate, batch.keySet(), exception); Map<Boolean, List<Long>> wereFailedTimestampsExpected = classifyTimestampsOnKeySetPresence(batch.keySet(), failedTimestamps); handleExpectedFailedTimestamps(batch, exception, failedTimestamps, wereFailedTimestampsExpected); handleUnexpectedFailedTimestamps(batch, wereFailedTimestampsExpected); markAllRemainingRequestsForTimestampsAsFailed(delegate, startTimestampKeyedBatchElements, failedTimestamps); } private static void handleExpectedFailedTimestamps( Map<Long, BatchElement<TimestampPair, Void>> batch, KeyAlreadyExistsException exception, Set<Long> failedTimestamps, Map<Boolean, List<Long>> wereFailedTimestampsExpected) { List<Long> expectedFailedTimestamps = wereFailedTimestampsExpected.get(true); if (expectedFailedTimestamps == null) { // We expected something important to fail, but nothing did. throw new SafeIllegalStateException( "Made a batch request to putUnlessExists and failed." + " The exception returned did not contain anything pertinent, which is unexpected.", SafeArg.of("batchRequest", batch), SafeArg.of("failedTimestamps", failedTimestamps)); } expectedFailedTimestamps.forEach(timestamp -> { BatchElement<TimestampPair, Void> batchElement = batch.get(timestamp); batchElement.result().setException(exception); }); } private static void handleUnexpectedFailedTimestamps( Map<Long, BatchElement<TimestampPair, Void>> batch, Map<Boolean, List<Long>> wereFailedTimestampsExpected) { List<Long> unexpectedFailedTimestamps = wereFailedTimestampsExpected.get(false); if (unexpectedFailedTimestamps != null) { log.warn( "Failed to putUnlessExists some timestamps which it seems we never asked for." + " Skipping, as this is likely to be safe, but flagging for debugging.", SafeArg.of("unexpectedFailedTimestamps", unexpectedFailedTimestamps), SafeArg.of("batchRequest", batch)); } } private static void handleSuccessfulTimestamps( EncodingTransactionService delegate, Multimap<Long, BatchElement<TimestampPair, Void>> startTimestampKeyedBatchElements, Map<Long, BatchElement<TimestampPair, Void>> batch, KeyAlreadyExistsException exception) { Set<Long> successfulTimestamps = getTimestampsSuccessfullyPutUnlessExists(delegate, exception); Map<Boolean, List<Long>> wereSuccessfulTimestampsExpected = classifyTimestampsOnKeySetPresence(batch.keySet(), successfulTimestamps); handleExpectedSuccesses(batch, wereSuccessfulTimestampsExpected); handleUnexpectedSuccesses(batch, wereSuccessfulTimestampsExpected); markAllRemainingRequestsForTimestampsAsFailed(delegate, startTimestampKeyedBatchElements, successfulTimestamps); } private static void markAllRemainingRequestsForTimestampsAsFailed( EncodingTransactionService delegate, Multimap<Long, BatchElement<TimestampPair, Void>> startTimestampKeyedBatchElements, Set<Long> timestampsToFail) { timestampsToFail.stream() .map(startTimestampKeyedBatchElements::get) .forEach(batchElements -> markAllRemainingRequestsAsFailed(delegate, batchElements)); timestampsToFail.forEach(startTimestampKeyedBatchElements::removeAll); } private static void handleExpectedSuccesses( Map<Long, BatchElement<TimestampPair, Void>> batch, Map<Boolean, List<Long>> wereSuccessfulTimestampsExpected) { List<Long> expectedSuccessfulTimestamps = wereSuccessfulTimestampsExpected.get(true); if (expectedSuccessfulTimestamps != null) { expectedSuccessfulTimestamps.forEach(timestamp -> { BatchElement<TimestampPair, Void> batchElement = batch.get(timestamp); markSuccessful(batchElement.result()); }); } } private static void handleUnexpectedSuccesses( Map<Long, BatchElement<TimestampPair, Void>> batch, Map<Boolean, List<Long>> wereSuccessfulTimestampsExpected) { List<Long> unexpectedSuccessfulTimestamps = wereSuccessfulTimestampsExpected.get(false); if (unexpectedSuccessfulTimestamps != null) { log.warn( "Successfully putUnlessExists some timestamps which it seems we never asked for." + " Skipping, as this is likely to be safe, but flagging for debugging.", SafeArg.of("unexpectedSuccessfulPuts", unexpectedSuccessfulTimestamps), SafeArg.of("batchRequest", batch)); } } private static void markBatchSuccessful( Multimap<Long, BatchElement<TimestampPair, Void>> startTimestampKeyedBatchElements, Map<Long, BatchElement<TimestampPair, Void>> batch) { batch.forEach((startTimestamp, batchElement) -> { startTimestampKeyedBatchElements.remove(startTimestamp, batchElement); markSuccessful(batchElement.result()); }); } private static void markSuccessful(DisruptorAutobatcher.DisruptorFuture<Void> result) { result.set(null); } private static Map<Boolean, List<Long>> classifyTimestampsOnKeySetPresence( Set<Long> requestKeySet, Set<Long> timestampSet) { return timestampSet.stream().collect(Collectors.groupingBy(requestKeySet::contains)); } private static Set<Long> getAlreadyExistingStartTimestamps( EncodingTransactionService delegate, Set<Long> startTimestamps, KeyAlreadyExistsException exception) { Set<Long> existingTimestamps = decodeCellsToTimestamps(delegate, exception.getExistingKeys()); Preconditions.checkState( !existingTimestamps.isEmpty(), "The underlying service threw a KeyAlreadyExistsException, but claimed no keys already existed!" + " This is likely to be a product bug - please contact support.", SafeArg.of("startTimestamps", startTimestamps), UnsafeArg.of("exception", exception)); return existingTimestamps; } private static Set<Long> getTimestampsSuccessfullyPutUnlessExists( EncodingTransactionService delegate, KeyAlreadyExistsException exception) { return decodeCellsToTimestamps(delegate, exception.getKnownSuccessfullyCommittedKeys()); } private static Set<Long> decodeCellsToTimestamps(EncodingTransactionService delegate, Collection<Cell> cells) { return cells.stream() .map(key -> delegate.getEncodingStrategy().decodeCellAsStartTimestamp(key)) .collect(Collectors.toSet()); } private static Map<Long, BatchElement<TimestampPair, Void>> extractSingleBatchForQuerying( Multimap<Long, BatchElement<TimestampPair, Void>> requests) { Map<Long, BatchElement<TimestampPair, Void>> result = Maps.newHashMapWithExpectedSize(requests.keySet().size()); for (Map.Entry<Long, Collection<BatchElement<TimestampPair, Void>>> entry : Multimaps.asMap(requests).entrySet()) { result.put(entry.getKey(), entry.getValue().iterator().next()); } return result; } @Value.Immutable interface TimestampPair { @Value.Parameter long startTimestamp(); @Value.Parameter long commitTimestamp(); static TimestampPair of(long startTimestamp, long commitTimestamp) { return ImmutableTimestampPair.of(startTimestamp, commitTimestamp); } } }
apache-2.0
vvakame/JsonPullParser
jsonpullparser-usage/src/main/java/net/vvakame/sample/issue31/ExtendData.java
511
package net.vvakame.sample.issue31; import net.vvakame.util.jsonpullparser.annotation.JsonKey; import net.vvakame.util.jsonpullparser.annotation.JsonModel; /** * Extend class from base class. * @author vvakame */ @JsonModel(builder = true) public class ExtendData extends BaseData { @JsonKey String b; /** * @return the b * @category accessor */ public String getB() { return b; } /** * @param b the b to set * @category accessor */ public void setB(String b) { this.b = b; } }
apache-2.0
spring-projects/spring-framework
spring-context/src/main/java/org/springframework/context/annotation/Condition.java
2118
/* * Copyright 2002-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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.core.type.AnnotatedTypeMetadata; /** * A single {@code condition} that must be {@linkplain #matches matched} in order * for a component to be registered. * * <p>Conditions are checked immediately before the bean-definition is due to be * registered and are free to veto registration based on any criteria that can * be determined at that point. * * <p>Conditions must follow the same restrictions as {@link BeanFactoryPostProcessor} * and take care to never interact with bean instances. For more fine-grained control * of conditions that interact with {@code @Configuration} beans consider implementing * the {@link ConfigurationCondition} interface. * * @author Phillip Webb * @since 4.0 * @see ConfigurationCondition * @see Conditional * @see ConditionContext */ @FunctionalInterface public interface Condition { /** * Determine if the condition matches. * @param context the condition context * @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class} * or {@link org.springframework.core.type.MethodMetadata method} being checked * @return {@code true} if the condition matches and the component can be registered, * or {@code false} to veto the annotated component's registration */ boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata); }
apache-2.0
bahmanm/ojlang-core
src/main/java/org/ojlang/runtime/sysio/StdOut.java
1434
/* * Copyright 2016 Bahman Movaqar * * 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.ojlang.runtime.sysio; /** * Runtime system STDOUT. * A producer (e.g. an Oj word) "puts" chunks of data while a consumer (e.g. * console) "gets" chunks of data. * * NOTE: Oj expects nothing smaller than a word; for example single characters * are not to be "put". * * @author Bahman Movaqar [Bahman AT BahmanM.com] */ public interface StdOut { /** * Returns the next available chunk of data which depending on the impl may * or may not block. * * @return the next available chunk of data which could be a single word, a * line of code or multiple lines of code. */ String get(); /** * Adds a given chunk of data to be later "consumed" (i.e. "get"). Depending * on the impl, it may or may not block. * * @param chunk the given chunk of data */ void put(String chunk); }
apache-2.0
BlueBrain/bluima
modules/bluima_utils/src/test/java/ch/epfl/bbp/uima/uimafit/CoveringCoveredTest.java
1844
package ch.epfl.bbp.uima.uimafit; import static org.junit.Assert.assertEquals; import static org.apache.uima.fit.util.JCasUtil.selectCovered; import static org.apache.uima.fit.util.JCasUtil.selectCovering; import org.apache.uima.jcas.JCas; import org.junit.Test; import ch.epfl.bbp.uima.testutils.UimaTests; import ch.epfl.bbp.uima.types.DictTerm; import ch.epfl.bbp.uima.types.Punctuation; import de.julielab.jules.types.Chemical; import de.julielab.jules.types.Protein; import de.julielab.jules.types.Token; public class CoveringCoveredTest { @Test public void test() throws Exception { JCas jCas = UimaTests.getTestCas("aaaaabbbbbccccc"); Token t = new Token(jCas, 5, 10); t.addToIndexes(); assertEquals("bbbbb", t.getCoveredText()); // perfect cover Protein p = new Protein(jCas, 5, 10); p.addToIndexes(); assertEquals(1, selectCovered(Protein.class, t).size()); assertEquals(1, selectCovering(jCas, Protein.class, 5, 10).size()); // over cover DictTerm d = new DictTerm(jCas, 4, 10); d.addToIndexes(); assertEquals(0, selectCovered(DictTerm.class, t).size()); assertEquals(1, selectCovering(jCas, DictTerm.class, 5, 10).size()); assertEquals(0, selectCovered(org.apache.uima.conceptMapper.DictTerm.class, t) .size()); assertEquals( 1, selectCovering(jCas, org.apache.uima.conceptMapper.DictTerm.class, 5, 10) .size()); // under cover Chemical c = new Chemical(jCas, 6, 9); c.addToIndexes(); assertEquals(1, selectCovered(Chemical.class, t).size()); assertEquals(0, selectCovering(jCas, Chemical.class, 5, 10).size()); // chevauchant Punctuation pt = new Punctuation(jCas, 3, 9); pt.addToIndexes(); assertEquals(0, selectCovered(Punctuation.class, t).size()); assertEquals(0, selectCovering(jCas, Punctuation.class, 5, 10).size()); } }
apache-2.0
tudarmstadt-lt/topicrawler
lt.seg/src/main/java/de/tudarmstadt/lt/seg/token/DiffTokenizer.java
3274
/* * Copyright 2014 * * 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 de.tudarmstadt.lt.seg.token; import static de.tudarmstadt.lt.seg.SegmentType.WORD_WITH_NUMBER; import java.io.IOException; import java.io.Reader; import java.util.Collections; import java.util.HashSet; import java.util.Set; import de.tudarmstadt.lt.seg.Segment; import de.tudarmstadt.lt.seg.SegmentType; import de.tudarmstadt.lt.seg.SegmentationUtils; /** * * * @author Steffen Remus * */ public class DiffTokenizer implements ITokenizer { Reader _reader = null; int _cp = 0; final Segment _segment = new Segment(){{ begin = 0; end = 0; type = SegmentType.UNKNOWN; text.setLength(0); }}; final Set<Integer> _codepoints = Collections.synchronizedSet(new HashSet<>()); final Set<Integer> _chartypes = Collections.synchronizedSet(new HashSet<>()); @Override public boolean hasNext() { return getNext(); } @Override public Segment next() { return _segment; } private boolean getNext(){ _segment.text.setLength(0); _segment.type = SegmentType.UNKNOWN; _segment.begin = _segment.end; _codepoints.clear(); _chartypes.clear(); while(_cp > 0){ int cp_current = _cp; _segment.text.appendCodePoint(cp_current); _codepoints.add(cp_current); int current_type = Character.getType(cp_current); _chartypes.add(current_type); try { _cp = _reader.read(); } catch (IOException e) { System.err.format("%s: %s%n", e.getClass().getName(), e.getMessage()); break; } ++_segment.end; int cp_next = _cp; int next_type = Character.getType(cp_next); if(SegmentationUtils.charTypeIsEmptySpace(current_type) && !SegmentationUtils.charTypeIsEmptySpace(next_type)) break; if(!SegmentationUtils.charTypeIsEmptySpace(current_type) && SegmentationUtils.charTypeIsEmptySpace(next_type)) break; if(WORD_WITH_NUMBER.allowedCharacterTypes().contains(current_type) && !WORD_WITH_NUMBER.allowedCharacterTypes().contains(next_type)) break; if(!WORD_WITH_NUMBER.allowedCharacterTypes().contains(current_type) && WORD_WITH_NUMBER.allowedCharacterTypes().contains(next_type)) break; } _segment.type = SegmentType.infer(_chartypes); return !_segment.hasZeroLength(); } /* (non-Javadoc) * @see de.tudarmstadt.lt.seg.token.ITokenizer#init(java.io.Reader) */ @Override public ITokenizer init(Reader reader) { _reader = reader; _segment.begin = 0; _segment.end = 0; _segment.type = SegmentType.UNKNOWN; _segment.text.setLength(0); _codepoints.clear(); _chartypes.clear(); try { _cp = _reader.read(); } catch (IOException e) { System.err.format("%s: %s%n", e.getClass().getName(), e.getMessage()); return this; } return this; } }
apache-2.0
triodjangopiter/junior
chapter_004/src/main/java/ru/pravvich/tic_tac/game/Play.java
147
package ru.pravvich.tic_tac.game; /** * Aggregator for game's interfaces. */ public interface Play extends ChoiceSide, LoopMove, InitWinner { }
apache-2.0
cptwin/public-key-authority-javaAPI
src/API.java
5090
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.security.Key; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * * @author Dajne Win */ public class API { private static final int timeOutInMillis = 10000; /** * Requests a one time token from the public key authority server. * @return String Token to be sent to the server for registering * @throws IOException */ public static String requestToken() throws IOException { System.setProperty("jsse.enableSNIExtension", "false"); URL url = new URL("https://python-dwin.rhcloud.com/requesttoken"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("GET"); conn.setConnectTimeout(timeOutInMillis); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String output = rd.readLine(); rd.close(); return output; } /** * Registers your client to the public key server. * @param token The token requested earlier. * @param publicKey Your public key. * @param number Your mobile phone number. * @param nonce A random number value that will be returned to verify the server received your request. * @return Your nonce value that you sent in your request if registering is successful * @throws IOException */ public static String register(String token, String publicKey, String number, int nonce) throws IOException { keyValue = token.substring(0, 16).getBytes(); String raw_data = "{\"token\":\"" + token + "\",\"publickey\":\"" + publicKey + "\",\"number\":\"" + number + "\",\"nonce\":\"" + nonce + "\"}"; String data = encrypt(raw_data); System.setProperty("jsse.enableSNIExtension", "false"); URL url = new URL("https://python-dwin.rhcloud.com/register"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setConnectTimeout(timeOutInMillis); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String output = rd.readLine(); rd.close(); return output; } /** * Gets the public key of another registered client. * @param number The mobile number of the person you want the public key for. * @return The public key of the client, otherwise -1 if it doesn't exist on the server. * @throws IOException */ public static String getPublicKey(String number) throws IOException { String data = "{\"number\":\"" + number + "\"}"; System.setProperty("jsse.enableSNIExtension", "false"); URL url = new URL("https://python-dwin.rhcloud.com/getkey"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setConnectTimeout(timeOutInMillis); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String output = rd.readLine(); rd.close(); return output; } private static final String ALGO = "AES"; private static byte[] keyValue; private static String encrypt(String Data) { try { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.ENCRYPT_MODE, key); byte[] encVal = c.doFinal(Data.getBytes()); String encryptedValue = new BASE64Encoder().encode(encVal); return encryptedValue; } catch (Exception ex) { Logger.getLogger(API.class.getName()).log(Level.SEVERE, null, ex); } return null; } private static String decrypt(String encryptedData) { try { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.DECRYPT_MODE, key); byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData); byte[] decValue = c.doFinal(decordedValue); String decryptedValue = new String(decValue); return decryptedValue; } catch (Exception ex) { Logger.getLogger(API.class.getName()).log(Level.SEVERE, null, ex); } return null; } private static Key generateKey() throws Exception { Key key = new SecretKeySpec(keyValue, ALGO); return key; } }
apache-2.0
StevenTea/CSC
app/src/main/java/com/csc/steven/menudrawer/OverlayDrawer.java
27643
package com.csc.steven.menudrawer; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.GradientDrawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; @SuppressWarnings("ALL") public class OverlayDrawer extends DraggableDrawer { private static final String TAG = "OverlayDrawer"; private int mPeekSize; private Runnable mRevealRunnable = new Runnable() { @Override public void run() { cancelContentTouch(); int animateTo = 0; switch (getPosition()) { case RIGHT: case BOTTOM: animateTo = -mPeekSize; break; default: animateTo = mPeekSize; break; } animateOffsetTo(animateTo, 250); } }; OverlayDrawer(Activity activity, int dragMode) { super(activity, dragMode); } public OverlayDrawer(Context context) { super(context); } public OverlayDrawer(Context context, AttributeSet attrs) { super(context, attrs); } public OverlayDrawer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void initDrawer(Context context, AttributeSet attrs, int defStyle) { super.initDrawer(context, attrs, defStyle); super.addView(mContentContainer, -1, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); if (USE_TRANSLATIONS) { mContentContainer.setLayerType(View.LAYER_TYPE_NONE, null); } mContentContainer.setHardwareLayersEnabled(false); super.addView(mMenuContainer, -1, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); mPeekSize = dpToPx(20); } @Override protected void drawOverlay(Canvas canvas) { final int width = getWidth(); final int height = getHeight(); final int offsetPixels = (int) mOffsetPixels; final float openRatio = Math.abs(mOffsetPixels) / mMenuSize; switch (getPosition()) { case LEFT: mMenuOverlay.setBounds(offsetPixels, 0, width, height); break; case RIGHT: mMenuOverlay.setBounds(0, 0, width + offsetPixels, height); break; case TOP: mMenuOverlay.setBounds(0, offsetPixels, width, height); break; case BOTTOM: mMenuOverlay.setBounds(0, 0, width, height + offsetPixels); break; } mMenuOverlay.setAlpha((int) (MAX_MENU_OVERLAY_ALPHA * openRatio)); mMenuOverlay.draw(canvas); } @Override public void openMenu(boolean animate) { int animateTo = 0; switch (getPosition()) { case LEFT: case TOP: animateTo = mMenuSize; break; case RIGHT: case BOTTOM: animateTo = -mMenuSize; break; } animateOffsetTo(animateTo, 0, animate); } @Override public void closeMenu(boolean animate) { animateOffsetTo(0, 0, animate); } @Override protected void onOffsetPixelsChanged(int offsetPixels) { if (USE_TRANSLATIONS) { switch (getPosition()) { case LEFT: mMenuContainer.setTranslationX(offsetPixels - mMenuSize); break; case TOP: mMenuContainer.setTranslationY(offsetPixels - mMenuSize); break; case RIGHT: mMenuContainer.setTranslationX(offsetPixels + mMenuSize); break; case BOTTOM: mMenuContainer.setTranslationY(offsetPixels + mMenuSize); break; } } else { switch (getPosition()) { case TOP: mMenuContainer.offsetTopAndBottom(offsetPixels - mMenuContainer.getBottom()); break; case BOTTOM: mMenuContainer.offsetTopAndBottom(offsetPixels - (mMenuContainer.getTop() - getHeight())); break; case LEFT: mMenuContainer.offsetLeftAndRight(offsetPixels - mMenuContainer.getRight()); break; case RIGHT: mMenuContainer.offsetLeftAndRight(offsetPixels - (mMenuContainer.getLeft() - getWidth())); break; } } invalidate(); } @Override protected void initPeekScroller() { switch (getPosition()) { case RIGHT: case BOTTOM: { final int dx = -mPeekSize; mPeekScroller.startScroll(0, 0, dx, 0, PEEK_DURATION); break; } default: { final int dx = mPeekSize; mPeekScroller.startScroll(0, 0, dx, 0, PEEK_DURATION); break; } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); onOffsetPixelsChanged((int) mOffsetPixels); } @Override protected GradientDrawable.Orientation getDropShadowOrientation() { switch (getPosition()) { case TOP: return GradientDrawable.Orientation.TOP_BOTTOM; case RIGHT: return GradientDrawable.Orientation.RIGHT_LEFT; case BOTTOM: return GradientDrawable.Orientation.BOTTOM_TOP; default: return GradientDrawable.Orientation.LEFT_RIGHT; } } @Override protected void updateDropShadowRect() { final float openRatio = Math.abs(mOffsetPixels) / mMenuSize; final int dropShadowSize = (int) (mDropShadowSize * openRatio); switch (getPosition()) { case LEFT: mDropShadowRect.top = 0; mDropShadowRect.bottom = getHeight(); mDropShadowRect.left = ViewHelper.getRight(mMenuContainer); mDropShadowRect.right = mDropShadowRect.left + dropShadowSize; break; case TOP: mDropShadowRect.left = 0; mDropShadowRect.right = getWidth(); mDropShadowRect.top = ViewHelper.getBottom(mMenuContainer); mDropShadowRect.bottom = mDropShadowRect.top + dropShadowSize; break; case RIGHT: mDropShadowRect.top = 0; mDropShadowRect.bottom = getHeight(); mDropShadowRect.right = ViewHelper.getLeft(mMenuContainer); mDropShadowRect.left = mDropShadowRect.right - dropShadowSize; break; case BOTTOM: mDropShadowRect.left = 0; mDropShadowRect.right = getWidth(); mDropShadowRect.bottom = ViewHelper.getTop(mMenuContainer); mDropShadowRect.top = mDropShadowRect.bottom - dropShadowSize; break; } } @Override protected void startLayerTranslation() { if (USE_TRANSLATIONS && mHardwareLayersEnabled && !mLayerTypeHardware) { mLayerTypeHardware = true; mMenuContainer.setLayerType(View.LAYER_TYPE_HARDWARE, null); } } @Override protected void stopLayerTranslation() { if (mLayerTypeHardware) { mLayerTypeHardware = false; mMenuContainer.setLayerType(View.LAYER_TYPE_NONE, null); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int width = r - l; final int height = b - t; mContentContainer.layout(0, 0, width, height); if (USE_TRANSLATIONS) { switch (getPosition()) { case LEFT: mMenuContainer.layout(0, 0, mMenuSize, height); break; case RIGHT: mMenuContainer.layout(width - mMenuSize, 0, width, height); break; case TOP: mMenuContainer.layout(0, 0, width, mMenuSize); break; case BOTTOM: mMenuContainer.layout(0, height - mMenuSize, width, height); break; } } else { final int offsetPixels = (int) mOffsetPixels; final int menuSize = mMenuSize; switch (getPosition()) { case LEFT: mMenuContainer.layout(-menuSize + offsetPixels, 0, offsetPixels, height); break; case RIGHT: mMenuContainer.layout(width + offsetPixels, 0, width + menuSize + offsetPixels, height); break; case TOP: mMenuContainer.layout(0, -menuSize + offsetPixels, width, offsetPixels); break; case BOTTOM: mMenuContainer.layout(0, height + offsetPixels, width, height + menuSize + offsetPixels); break; } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) { throw new IllegalStateException("Must measure with an exact size"); } final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = MeasureSpec.getSize(heightMeasureSpec); if (mOffsetPixels == -1) openMenu(false); int menuWidthMeasureSpec; int menuHeightMeasureSpec; switch (getPosition()) { case TOP: case BOTTOM: menuWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, width); menuHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, 0, mMenuSize); break; default: // LEFT/RIGHT menuWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, mMenuSize); menuHeightMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, height); } mMenuContainer.measure(menuWidthMeasureSpec, menuHeightMeasureSpec); final int contentWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, width); final int contentHeightMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, height); mContentContainer.measure(contentWidthMeasureSpec, contentHeightMeasureSpec); setMeasuredDimension(width, height); updateTouchAreaSize(); } private boolean isContentTouch(int x, int y) { boolean contentTouch = false; switch (getPosition()) { case LEFT: contentTouch = ViewHelper.getRight(mMenuContainer) < x; break; case RIGHT: contentTouch = ViewHelper.getLeft(mMenuContainer) > x; break; case TOP: contentTouch = ViewHelper.getBottom(mMenuContainer) < y; break; case BOTTOM: contentTouch = ViewHelper.getTop(mMenuContainer) > y; break; } return contentTouch; } protected boolean onDownAllowDrag(int x, int y) { switch (getPosition()) { case LEFT: return (!mMenuVisible && mInitialMotionX <= mTouchSize) || (mMenuVisible && mInitialMotionX <= mOffsetPixels); case RIGHT: final int width = getWidth(); final int initialMotionX = (int) mInitialMotionX; return (!mMenuVisible && initialMotionX >= width - mTouchSize) || (mMenuVisible && initialMotionX >= width + mOffsetPixels); case TOP: return (!mMenuVisible && mInitialMotionY <= mTouchSize) || (mMenuVisible && mInitialMotionY <= mOffsetPixels); case BOTTOM: final int height = getHeight(); return (!mMenuVisible && mInitialMotionY >= height - mTouchSize) || (mMenuVisible && mInitialMotionY >= height + mOffsetPixels); } return false; } protected boolean onMoveAllowDrag(int x, int y, float dx, float dy) { if (mMenuVisible && mTouchMode == TOUCH_MODE_FULLSCREEN) { return true; } switch (getPosition()) { case LEFT: return (!mMenuVisible && mInitialMotionX <= mTouchSize && (dx > 0)) // Drawer closed || (mMenuVisible && x <= mOffsetPixels) // Drawer open || (Math.abs(mOffsetPixels) <= mPeekSize && mMenuVisible); // Drawer revealed case RIGHT: final int width = getWidth(); return (!mMenuVisible && mInitialMotionX >= width - mTouchSize && (dx < 0)) || (mMenuVisible && x >= width - mOffsetPixels) || (Math.abs(mOffsetPixels) <= mPeekSize && mMenuVisible); case TOP: return (!mMenuVisible && mInitialMotionY <= mTouchSize && (dy > 0)) || (mMenuVisible && x <= mOffsetPixels) || (Math.abs(mOffsetPixels) <= mPeekSize && mMenuVisible); case BOTTOM: final int height = getHeight(); return (!mMenuVisible && mInitialMotionY >= height - mTouchSize && (dy < 0)) || (mMenuVisible && x >= height - mOffsetPixels) || (Math.abs(mOffsetPixels) <= mPeekSize && mMenuVisible); } return false; } protected void onMoveEvent(float dx, float dy) { switch (getPosition()) { case LEFT: setOffsetPixels(Math.min(Math.max(mOffsetPixels + dx, 0), mMenuSize)); break; case RIGHT: setOffsetPixels(Math.max(Math.min(mOffsetPixels + dx, 0), -mMenuSize)); break; case TOP: setOffsetPixels(Math.min(Math.max(mOffsetPixels + dy, 0), mMenuSize)); break; case BOTTOM: setOffsetPixels(Math.max(Math.min(mOffsetPixels + dy, 0), -mMenuSize)); break; } } protected void onUpEvent(int x, int y) { final int offsetPixels = (int) mOffsetPixels; switch (getPosition()) { case LEFT: { if (mIsDragging) { mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); final int initialVelocity = (int) getXVelocity(mVelocityTracker); mLastMotionX = x; animateOffsetTo(initialVelocity > 0 ? mMenuSize : 0, initialVelocity, true); // Close the menu when content is clicked while the menu is visible. } else if (mMenuVisible) { closeMenu(); } break; } case TOP: { if (mIsDragging) { mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); final int initialVelocity = (int) getYVelocity(mVelocityTracker); mLastMotionY = y; animateOffsetTo(initialVelocity > 0 ? mMenuSize : 0, initialVelocity, true); // Close the menu when content is clicked while the menu is visible. } else if (mMenuVisible) { closeMenu(); } break; } case RIGHT: { final int width = getWidth(); if (mIsDragging) { mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); final int initialVelocity = (int) getXVelocity(mVelocityTracker); mLastMotionX = x; animateOffsetTo(initialVelocity > 0 ? 0 : -mMenuSize, initialVelocity, true); // Close the menu when content is clicked while the menu is visible. } else if (mMenuVisible) { closeMenu(); } break; } case BOTTOM: { if (mIsDragging) { mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); final int initialVelocity = (int) getYVelocity(mVelocityTracker); mLastMotionY = y; animateOffsetTo(initialVelocity < 0 ? -mMenuSize : 0, initialVelocity, true); // Close the menu when content is clicked while the menu is visible. } else if (mMenuVisible) { closeMenu(); } break; } } } protected boolean checkTouchSlop(float dx, float dy) { switch (getPosition()) { case TOP: case BOTTOM: return Math.abs(dy) > mTouchSlop && Math.abs(dy) > Math.abs(dx); default: return Math.abs(dx) > mTouchSlop && Math.abs(dx) > Math.abs(dy); } } @Override protected void stopAnimation() { super.stopAnimation(); removeCallbacks(mRevealRunnable); } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { super.requestDisallowInterceptTouchEvent(disallowIntercept); removeCallbacks(mRevealRunnable); if (mIsPeeking) { endPeek(); animateOffsetTo(0, PEEK_DURATION); } } public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = ev.getAction() & MotionEvent.ACTION_MASK; if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { removeCallbacks(mRevealRunnable); mActivePointerId = INVALID_POINTER; mIsDragging = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } if (Math.abs(mOffsetPixels) > mMenuSize / 2) { openMenu(); } else { closeMenu(); } return false; } if (action == MotionEvent.ACTION_DOWN && mMenuVisible && isCloseEnough()) { setOffsetPixels(0); stopAnimation(); endPeek(); setDrawerState(STATE_CLOSED); mIsDragging = false; } // Always intercept events over the content while menu is visible. if (mMenuVisible) { int index = 0; if (mActivePointerId != INVALID_POINTER) { index = ev.findPointerIndex(mActivePointerId); index = index == -1 ? 0 : index; } final int x = (int) ev.getX(index); final int y = (int) ev.getY(index); if (isContentTouch(x, y)) { return true; } } if (!mMenuVisible && !mIsDragging && mTouchMode == TOUCH_MODE_NONE) { return false; } if (action != MotionEvent.ACTION_DOWN && mIsDragging) { return true; } switch (action) { case MotionEvent.ACTION_DOWN: { mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = mInitialMotionY = ev.getY(); final boolean allowDrag = onDownAllowDrag((int) mLastMotionX, (int) mLastMotionY); mActivePointerId = ev.getPointerId(0); if (allowDrag) { setDrawerState(mMenuVisible ? STATE_OPEN : STATE_CLOSED); stopAnimation(); endPeek(); if (!mMenuVisible && mInitialMotionX <= mPeekSize) { postDelayed(mRevealRunnable, 160); } mIsDragging = false; } break; } case MotionEvent.ACTION_MOVE: { final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } final int pointerIndex = ev.findPointerIndex(activePointerId); if (pointerIndex == -1) { mIsDragging = false; mActivePointerId = INVALID_POINTER; endDrag(); closeMenu(true); return false; } final float x = ev.getX(pointerIndex); final float dx = x - mLastMotionX; final float y = ev.getY(pointerIndex); final float dy = y - mLastMotionY; if (Math.abs(dx) >= mTouchSlop || Math.abs(dy) >= mTouchSlop) { removeCallbacks(mRevealRunnable); endPeek(); } if (checkTouchSlop(dx, dy)) { if (mOnInterceptMoveEventListener != null && (mTouchMode == TOUCH_MODE_FULLSCREEN || mMenuVisible) && canChildrenScroll((int) dx, (int) dy, (int) x, (int) y)) { endDrag(); // Release the velocity tracker requestDisallowInterceptTouchEvent(true); return false; } final boolean allowDrag = onMoveAllowDrag((int) x, (int) y, dx, dy); if (allowDrag) { endPeek(); stopAnimation(); setDrawerState(STATE_DRAGGING); mIsDragging = true; mLastMotionX = x; mLastMotionY = y; } } break; } case MotionEvent.ACTION_POINTER_UP: onPointerUp(ev); mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId)); mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId)); break; } if (mVelocityTracker == null) mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); return mIsDragging; } @Override public boolean onTouchEvent(MotionEvent ev) { if (!mMenuVisible && !mIsDragging && mTouchMode == TOUCH_MODE_NONE) { return false; } final int action = ev.getAction() & MotionEvent.ACTION_MASK; if (mVelocityTracker == null) mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); switch (action) { case MotionEvent.ACTION_DOWN: { mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = mInitialMotionY = ev.getY(); final boolean allowDrag = onDownAllowDrag((int) mLastMotionX, (int) mLastMotionY); mActivePointerId = ev.getPointerId(0); if (allowDrag) { stopAnimation(); endPeek(); if (!mMenuVisible && mLastMotionX <= mPeekSize) { postDelayed(mRevealRunnable, 160); } startLayerTranslation(); } break; } case MotionEvent.ACTION_MOVE: { final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex == -1) { mIsDragging = false; mActivePointerId = INVALID_POINTER; endDrag(); closeMenu(true); return false; } if (!mIsDragging) { final float x = ev.getX(pointerIndex); final float dx = x - mLastMotionX; final float y = ev.getY(pointerIndex); final float dy = y - mLastMotionY; if (checkTouchSlop(dx, dy)) { final boolean allowDrag = onMoveAllowDrag((int) x, (int) y, dx, dy); if (allowDrag) { endPeek(); stopAnimation(); setDrawerState(STATE_DRAGGING); mIsDragging = true; mLastMotionX = x; mLastMotionY = y; } else { mInitialMotionX = x; mInitialMotionY = y; } } } if (mIsDragging) { startLayerTranslation(); final float x = ev.getX(pointerIndex); final float dx = x - mLastMotionX; final float y = ev.getY(pointerIndex); final float dy = y - mLastMotionY; mLastMotionX = x; mLastMotionY = y; onMoveEvent(dx, dy); } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { removeCallbacks(mRevealRunnable); int index = ev.findPointerIndex(mActivePointerId); index = index == -1 ? 0 : index; final int x = (int) ev.getX(index); final int y = (int) ev.getY(index); onUpEvent(x, y); mActivePointerId = INVALID_POINTER; mIsDragging = false; break; } case MotionEvent.ACTION_POINTER_DOWN: final int index = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; mLastMotionX = ev.getX(index); mLastMotionY = ev.getY(index); mActivePointerId = ev.getPointerId(index); break; case MotionEvent.ACTION_POINTER_UP: onPointerUp(ev); mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId)); mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId)); break; } return true; } private void onPointerUp(MotionEvent ev) { final int pointerIndex = ev.getActionIndex(); final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = ev.getX(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } }
apache-2.0
zegerhoogeboom/hu-demo-appengine
src/test/java/org/hu/zegerhoogeboom/demo/SignGuestbookServletTest.java
3550
/** * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hu.zegerhoogeboom.demo; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserServiceFactory; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SignGuestbookServletTest { private SignGuestbookServlet signGuestbookServlet; private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()) .setEnvIsLoggedIn(true) .setEnvAuthDomain("localhost") .setEnvEmail("test@localhost"); @Before public void setupSignGuestBookServlet() { helper.setUp(); signGuestbookServlet = new SignGuestbookServlet(); } @After public void tearDownHelper() { helper.tearDown(); } @Test public void testDoPost() throws IOException, EntityNotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); String guestbookName = "TestGuestbook"; String testContent = "Test Content"; when(request.getParameter("guestbookName")).thenReturn(guestbookName); when(request.getParameter("content")).thenReturn(testContent); Date priorToRequest = new Date(); signGuestbookServlet.doPost(request, response); Date afterRequest = new Date(); verify(response).sendRedirect("/guestbook.jsp?guestbookName=TestGuestbook"); User currentUser = UserServiceFactory.getUserService().getCurrentUser(); Entity greeting = DatastoreServiceFactory.getDatastoreService().prepare(new Query()).asSingleEntity(); assertEquals(guestbookName, greeting.getKey().getParent().getName()); assertEquals(testContent, greeting.getProperty("content")); assertEquals(currentUser, greeting.getProperty("user")); Date date = (Date) greeting.getProperty("date"); assertTrue("The date in the entity [" + date + "] is prior to the request being performed", priorToRequest.before(date) || priorToRequest.equals(date)); assertTrue("The date in the entity [" + date + "] is after to the request completed", afterRequest.after(date) || afterRequest.equals(date)); } }
apache-2.0
ctripcorp/cornerstone
cornerstone/src/main/java/com/ctrip/framework/cs/analyzer/AnalyzerHandler.java
3797
package com.ctrip.framework.cs.analyzer; import com.ctrip.framework.cs.SimpleLoggerFactory; import com.ctrip.framework.cs.ViFunctionHandler; import com.ctrip.framework.cs.localLog.LocalLogManager; import com.ctrip.framework.cs.IgniteManager; import com.ctrip.framework.cs.Permission; import com.ctrip.framework.cs.instrument.AgentTool; import com.ctrip.framework.cs.util.TextUtils; import org.slf4j.Logger; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Map; /** * Created by jiang.j on 2016/6/13. */ public class AnalyzerHandler implements ViFunctionHandler { private String startPath ="/analyzer/"; @Override public Object execute(String path, String user, int permission, Logger logger, Map<String, Object> params) throws Exception{ Object rtn=null; if(path.equals(startPath+"deps")) { rtn = Analyzer.getAllPomInfo(); }else if(path.equals(startPath+"heaphisto")){ rtn = JVMSampler.getCurrentHeapHisto(); }else if(path.startsWith(startPath+"vmsnapshot")){ VMMonitor.VMSnapShot vmSnapShot = VMMonitor.getCurrent(); int maxWait = 10; while (!vmSnapShot.isInitiated() && maxWait>0){ Thread.sleep(10); maxWait--; } rtn = VMMonitor.getCurrent(); }else if(path.startsWith(startPath+"getgcloglist")){ rtn = LocalLogManager.getGCLogList(); }else if(path.startsWith(startPath+"getjvmoptions")){ RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); rtn = TextUtils.join(" ", runtimeBean.getInputArguments()); }else if(path.startsWith(startPath+"parsegclog")){ if(params.containsKey("name")) { String fileName = (String) params.get("name"); if (fileName.startsWith("gc-")) { rtn = GCLogAnalyzer.parseToJson(LocalLogManager.getFullPathByName(fileName)); } else { rtn = ""; } } }else if(path.equals(startPath+"jars")) { rtn = Analyzer.getAllJarNames(); }else if(path.equals(startPath+"addclassformetrics")) { AgentTool.addMethodMetricsClass((String) params.get("name")); }else if(path.equals(startPath+"listsource")) { rtn = Analyzer.listJarFolder((String)params.get("jarname")); }else if(path.equals(startPath+"getallmoduleinfo")) { rtn = Analyzer.getAllModuleInfo(); }else if(path.equals(startPath+"getneedmetricsclasses")) { rtn = AgentTool.getNeedMetricsClasses(); }else if(path.equals(startPath+"removemetricsclass")) { String className = (String) params.get("name"); AgentTool.removeMetricsClass(className); }else if(path.equals(startPath+"listclasses")) { rtn = Analyzer.listJarClasses((String)params.get("location")); }else if(path.equalsIgnoreCase(startPath+"allIgnitePlugins")){ rtn = IgniteManager.getPluginMap().keySet(); }else if(path.equalsIgnoreCase(startPath+"selfcheck")){ String pluginId = (String) params.get("id"); rtn = Analyzer.selfCheck(pluginId); }else if(path.equalsIgnoreCase(startPath+"getSelfCheckMsgs")){ String uid = (String) params.get("uid"); int startIndex = Integer.parseInt((String) params.get("index")); rtn = SimpleLoggerFactory.getSimpleLogger(uid).getMsgs(startIndex); } return rtn; } @Override public String getStartPath() { return startPath; } @Override public Permission getPermission(String user) { return Permission.ALL; } }
apache-2.0
haku/Morrigan
src/test/java/com/vaguehope/morrigan/model/media/test/TestMixedMediaDb.java
3293
package com.vaguehope.morrigan.model.media.test; import java.io.File; import java.math.BigInteger; import java.util.Date; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.vaguehope.morrigan.model.exceptions.MorriganException; import com.vaguehope.morrigan.model.media.IMixedMediaItem; import com.vaguehope.morrigan.model.media.IMixedMediaItem.MediaType; import com.vaguehope.morrigan.model.media.internal.db.MediaItemDbConfig; import com.vaguehope.morrigan.model.media.internal.db.mmdb.LocalMixedMediaDb; import com.vaguehope.morrigan.model.media.internal.db.mmdb.MixedMediaItemFactory; import com.vaguehope.morrigan.model.media.internal.db.mmdb.MixedMediaSqliteLayerOuter; import com.vaguehope.morrigan.sqlitewrapper.DbException; public class TestMixedMediaDb extends LocalMixedMediaDb { private static final String NAME = "testDb"; private static final Random RND = new Random(System.currentTimeMillis()); private static final AtomicInteger newDbCounter = new AtomicInteger(0); private static final AtomicInteger newTrackCounter = new AtomicInteger(0); public static int getTrackNumber() { return newTrackCounter.getAndIncrement(); } public TestMixedMediaDb () throws DbException, MorriganException { this(NAME + newDbCounter.getAndIncrement()); } public TestMixedMediaDb (final String name) throws DbException, MorriganException { this(name, true); } public TestMixedMediaDb (final String name, boolean autoCommit) throws DbException, MorriganException { super(name, new MediaItemDbConfig(name, null), new MixedMediaSqliteLayerOuter( "file:" + name + "?mode=memory&cache=shared", autoCommit, new MixedMediaItemFactory())); read(); } public IMixedMediaItem addTestTrack() throws MorriganException, DbException { final int n = getTrackNumber(); return addTestTrack(new File(String.format("some_media_file_%s.ext", n)), BigInteger.TEN.add(BigInteger.valueOf(n))); } public IMixedMediaItem addTestTrack (final File file) throws MorriganException, DbException { return addTestTrack(file, new BigInteger(128, RND)); } public IMixedMediaItem addTestTrack (final BigInteger hashCode) throws MorriganException, DbException { return addTestTrack(new File(String.format("some_media_file_%s.ext", getTrackNumber())), hashCode); } public IMixedMediaItem addTestTrack (final File file, final BigInteger hashCode) throws MorriganException, DbException { addFile(file); final IMixedMediaItem track = getByFile(file); // Workaround so dbRowId is filled in. setItemMediaType(track, MediaType.TRACK); setItemHashCode(track, hashCode); final Date lastPlayed = new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(RND.nextInt(144000))); setTrackDateLastPlayed(track, lastPlayed); return track; } public void printContent(final String prefix) { System.out.println(prefix + ": TestDb " + getListName() + " has " + getCount() + " items:"); final List<IMixedMediaItem> items = getMediaItems(); for (final IMixedMediaItem i : items) { System.out.print(i.isMissing() ? "M" : "-"); System.out.print(i.isEnabled() ? "-" : "D"); System.out.print(" "); System.out.println(i.getFilepath()); } } }
apache-2.0
OpenHFT/Chronicle-Bytes
src/main/java/net/openhft/chronicle/bytes/DistributedUniqueTimeDeduplicator.java
666
package net.openhft.chronicle.bytes; public interface DistributedUniqueTimeDeduplicator { /** * Compare this new timestamp to the previously retained timstamp for the hostId * * @param timestampHostId to compare * @return -1 if the timestamp is older, 0 if the same, +1 if newer */ int compareByHostId(long timestampHostId); /** * Compare this new timestamp to the previously retained timestamp for the hostId and retaining the timestamp * * @param timestampHostId to compare * @return -1 if the timestamp is older, 0 if the same, +1 if newer */ int compareAndRetainNewer(long timestampHostId); }
apache-2.0
metova/privvy
privvy/src/main/java/com/metova/privvy/PrivvyHost.java
210
package com.metova.privvy; public interface PrivvyHost { void initialize(RouteData... routes); void replace(RouteData oldComponent, RouteData newComponent); void goTo(RouteData newComponent); }
apache-2.0
wanwei8/pard-isocca
src/main/java/com/pard/common/utils/file/Resources.java
7885
package com.pard.common.utils.file; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.Properties; /** * Created by wawe on 17/5/31. */ public class Resources { private static ClassLoaderWrapper classLoaderWrapper = new ClassLoaderWrapper(); /** * Charset to use when calling getResourceAsReader. * null means use the system default. */ private static Charset charset; Resources() { } /** * Returns the default classloader (may be null). * * @return The default classloader */ public static ClassLoader getDefaultClassLoader() { return classLoaderWrapper.defaultClassLoader; } /** * Sets the default classloader * * @param defaultClassLoader - the new default ClassLoader */ public static void setDefaultClassLoader(ClassLoader defaultClassLoader) { classLoaderWrapper.defaultClassLoader = defaultClassLoader; } /** * Returns the URL of the resource on the classpath * * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static URL getResourceURL(String resource) throws IOException { return classLoaderWrapper.getResourceAsURL(resource); } /** * Returns the URL of the resource on the classpath * * @param loader The classloader used to fetch the resource * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static URL getResourceURL(ClassLoader loader, String resource) throws IOException { URL url = classLoaderWrapper.getResourceAsURL(resource, loader); if (url == null) throw new IOException("Could not find resource " + resource); return url; } /** * Returns a resource on the classpath as a Stream object * * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static InputStream getResourceAsStream(String resource) throws IOException { return getResourceAsStream(null, resource); } /** * Returns a resource on the classpath as a Stream object * * @param loader The classloader used to fetch the resource * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException { InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader); if (in == null) throw new IOException("Could not find resource " + resource); return in; } /** * Returns a resource on the classpath as a Properties object * * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static Properties getResourceAsProperties(String resource) throws IOException { Properties props = new Properties(); InputStream in = getResourceAsStream(resource); props.load(in); in.close(); return props; } /** * Returns a resource on the classpath as a Properties object * * @param loader The classloader used to fetch the resource * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException { Properties props = new Properties(); InputStream in = getResourceAsStream(loader, resource); props.load(in); in.close(); return props; } /** * Returns a resource on the classpath as a Reader object * * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static Reader getResourceAsReader(String resource) throws IOException { Reader reader; if (charset == null) { reader = new InputStreamReader(getResourceAsStream(resource)); } else { reader = new InputStreamReader(getResourceAsStream(resource), charset); } return reader; } /** * Returns a resource on the classpath as a Reader object * * @param loader The classloader used to fetch the resource * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException { Reader reader; if (charset == null) { reader = new InputStreamReader(getResourceAsStream(loader, resource)); } else { reader = new InputStreamReader(getResourceAsStream(loader, resource), charset); } return reader; } /** * Returns a resource on the classpath as a File object * * @param resource The resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static File getResourceAsFile(String resource) throws IOException { return new File(getResourceURL(resource).getFile()); } /** * Returns a resource on the classpath as a File object * * @param loader - the classloader used to fetch the resource * @param resource - the resource to find * @return The resource * @throws IOException If the resource cannot be found or read */ public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException { return new File(getResourceURL(loader, resource).getFile()); } /** * Gets a URL as an input stream * * @param urlString - the URL to get * @return An input stream with the data from the URL * @throws IOException If the resource cannot be found or read */ public static InputStream getUrlAsStream(String urlString) throws IOException { URL url = new URL(urlString); URLConnection conn = url.openConnection(); return conn.getInputStream(); } /** * Gets a URL as a Reader * * @param urlString - the URL to get * @return A Reader with the data from the URL * @throws IOException If the resource cannot be found or read */ public static Reader getUrlAsReader(String urlString) throws IOException { return new InputStreamReader(getUrlAsStream(urlString)); } /** * Gets a URL as a Properties object * * @param urlString - the URL to get * @return A Properties object with the data from the URL * @throws IOException If the resource cannot be found or read */ public static Properties getUrlAsProperties(String urlString) throws IOException { Properties props = new Properties(); InputStream in = getUrlAsStream(urlString); props.load(in); in.close(); return props; } /** * Loads a class * * @param className - the class to fetch * @return The loaded class * @throws ClassNotFoundException If the class cannot be found (duh!) */ public static Class classForName(String className) throws ClassNotFoundException { return classLoaderWrapper.classForName(className); } public static Charset getCharset() { return charset; } public static void setCharset(Charset charset) { Resources.charset = charset; } }
apache-2.0
lettuce-io/lettuce-core
src/test/java/io/lettuce/core/commands/reactive/HashReactiveCommandIntegrationTests.java
2138
/* * Copyright 2011-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.commands.reactive; import static org.assertj.core.api.Assertions.assertThat; import java.util.stream.Collectors; import javax.inject.Inject; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import reactor.test.StepVerifier; import io.lettuce.core.KeyValue; import io.lettuce.core.Value; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.commands.HashCommandIntegrationTests; import io.lettuce.test.ReactiveSyncInvocationHandler; /** * @author Mark Paluch */ class HashReactiveCommandIntegrationTests extends HashCommandIntegrationTests { private final StatefulRedisConnection<String, String> connection; @Inject HashReactiveCommandIntegrationTests(StatefulRedisConnection<String, String> connection) { super(ReactiveSyncInvocationHandler.sync(connection)); this.connection = connection; } @Test public void hgetall() { connection.sync().hset(key, "zero", "0"); connection.sync().hset(key, "one", "1"); connection.sync().hset(key, "two", "2"); connection.reactive().hgetall(key).collect(Collectors.toMap(KeyValue::getKey, Value::getValue)).as(StepVerifier::create) .assertNext(actual -> { assertThat(actual).containsEntry("zero", "0").containsEntry("one", "1").containsEntry("two", "2"); }).verifyComplete(); } @Test @Disabled("API differences") public void hgetallStreaming() { } }
apache-2.0
infusionsoft/yammer-metrics
metrics-servlets/src/main/java/com/codahale/metrics/servlets/AdminServletContextListener.java
1975
package com.codahale.metrics.servlets; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.util.concurrent.ExecutorService; /** * A listener implementation which injects a {@link MetricRegistry} instance, a * {@link HealthCheckRegistry} instance, and an optional {@link ExecutorService} instance into the * servlet context as named attributes. * * @deprecated Use {@link MetricsServlet.ContextListener} and * {@link HealthCheckServlet.ContextListener} instead. */ @Deprecated public abstract class AdminServletContextListener implements ServletContextListener { /** * Returns the {@link MetricRegistry} to inject into the servlet context. */ protected abstract MetricRegistry getMetricRegistry(); /** * Returns the {@link HealthCheckRegistry} to inject into the servlet context. */ protected abstract HealthCheckRegistry getHealthCheckRegistry(); /** * Returns the {@link ExecutorService} to inject into the servlet context, or {@code null} if * the health checks should be run in the servlet worker thread. */ protected ExecutorService getExecutorService() { // don't use a thread pool by default return null; } @Override public void contextInitialized(ServletContextEvent servletContextEvent) { final ServletContext context = servletContextEvent.getServletContext(); context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); context.setAttribute(HealthCheckServlet.HEALTH_CHECK_EXECUTOR, getExecutorService()); context.setAttribute(MetricsServlet.METRICS_REGISTRY, getMetricRegistry()); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { // no-op... } }
apache-2.0
dorzey/assertj-core
src/test/java/org/assertj/core/internal/StandardComparisonStrategy_iterableContains_Test.java
1630
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2016 the original author or authors. */ package org.assertj.core.internal; import static org.assertj.core.util.Lists.newArrayList; import static org.assertj.core.api.Assertions.*; import java.util.List; import org.assertj.core.internal.StandardComparisonStrategy; import org.junit.Test; /** * Tests for {@link StandardComparisonStrategy#iterableContains(java.util.Collection, Object)}. * * @author Joel Costigliola */ public class StandardComparisonStrategy_iterableContains_Test extends AbstractTest_StandardComparisonStrategy { @Test public void should_pass() { List<?> list = newArrayList("Sam", "Merry", null, "Frodo"); assertThat(standardComparisonStrategy.iterableContains(list, "Frodo")).isTrue(); assertThat(standardComparisonStrategy.iterableContains(list, null)).isTrue(); assertThat(standardComparisonStrategy.iterableContains(list, "Sauron")).isFalse(); } @Test public void should_return_false_if_iterable_is_null() { assertThat(standardComparisonStrategy.iterableContains(null, "Sauron")).isFalse(); } }
apache-2.0
oneliang/third-party-lib
jdom/org/jdom/FilterIterator.java
4050
/*-- $Id: FilterIterator.java,v 1.1 2012/03/26 04:33:54 lv Exp $ Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin. 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 disclaimer that follows these conditions in the documentation and/or other materials provided with the distribution. 3. The name "JDOM" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact <request_AT_jdom_DOT_org>. 4. Products derived from this software may not be called "JDOM", nor may "JDOM" appear in their name, without prior written permission from the JDOM Project Management <request_AT_jdom_DOT_org>. In addition, we request (but do not require) that you include in the end-user documentation provided with the redistribution and/or in the software itself an acknowledgement equivalent to the following: "This product includes software developed by the JDOM Project (http://www.jdom.org/)." Alternatively, the acknowledgment may be graphical using the logos available at http://www.jdom.org/images/logos. 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 JDOM AUTHORS OR THE PROJECT 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 JDOM Project and was originally created by Jason Hunter <jhunter_AT_jdom_DOT_org> and Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information on the JDOM Project, please see <http://www.jdom.org/>. */ package org.jdom; import java.util.*; import org.jdom.filter.*; /** * Traverse a parent's children that match the supplied filter. * * @author Bradley S. Huffman * @version $Revision: 1.1 $, $Date: 2012/03/26 04:33:54 $ */ class FilterIterator implements Iterator { private Iterator iterator; private Filter filter; private Object nextObject; private static final String CVS_ID = "@(#) $RCSfile: FilterIterator.java,v $ $Revision: 1.1 $ $Date: 2012/03/26 04:33:54 $ $Name: $"; public FilterIterator(Iterator iterator, Filter filter) { if ((iterator == null) || (filter == null)) { throw new IllegalArgumentException("null parameter"); } this.iterator = iterator; this.filter = filter; } public boolean hasNext() { if (nextObject != null) { return true; } while (iterator.hasNext()) { Object obj = iterator.next(); if (filter.matches(obj)) { nextObject = obj; return true; } } return false; } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } Object obj = nextObject; nextObject = null; return obj; } public void remove() { // XXX Could cause probs for sure if hasNext() is // called before the remove(), although that's unlikely. iterator.remove(); } }
apache-2.0
jjYBdx4IL/misc
ecs/src/main/java/org/apache/ecs/html/Span.java
7909
/* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-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 acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Jakarta Element Construction Set", * "Jakarta ECS" , 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", * "Jakarta Element Construction Set" nor "Jakarta ECS" nor may "Apache" * appear in their names without prior written permission of the Apache Group. * * 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. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ecs.html; import org.apache.ecs.*; /** This class creates a &lt;SPAN&gt; tag. @version $Id: Span.java,v 1.4 2003/04/27 09:03:51 rdonkin Exp $ @author <a href="mailto:snagy@servletapi.com">Stephan Nagy</a> @author <a href="mailto:jon@clearink.com">Jon S. Stevens</a> */ public class Span extends MultiPartElement implements Printable, MouseEvents, KeyEvents { /** Private initialization routine. */ { setElementType("span"); } /** Basic constructor. You need to set the attributes using the set* methods. */ public Span() { } /** Use the set* methods to set the values of the attributes. @param value set the value of &lt;span&gt;value&lt;/span&gt; */ public Span(String value) { addElement(value); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public Span addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public Span addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public Span addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public Span addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public Span removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } /** The onclick event occurs when the pointing device button is clicked over an element. This attribute may be used with most elements. @param The script */ public void setOnClick(String script) { addAttribute ( "onClick", script ); } /** The ondblclick event occurs when the pointing device button is double clicked over an element. This attribute may be used with most elements. @param The script */ public void setOnDblClick(String script) { addAttribute ( "onDblClick", script ); } /** The onmousedown event occurs when the pointing device button is pressed over an element. This attribute may be used with most elements. @param The script */ public void setOnMouseDown(String script) { addAttribute ( "onMouseDown", script ); } /** The onmouseup event occurs when the pointing device button is released over an element. This attribute may be used with most elements. @param The script */ public void setOnMouseUp(String script) { addAttribute ( "onMouseUp", script ); } /** The onmouseover event occurs when the pointing device is moved onto an element. This attribute may be used with most elements. @param The script */ public void setOnMouseOver(String script) { addAttribute ( "onMouseOver", script ); } /** The onmousemove event occurs when the pointing device is moved while it is over an element. This attribute may be used with most elements. @param The script */ public void setOnMouseMove(String script) { addAttribute ( "onMouseMove", script ); } /** The onmouseout event occurs when the pointing device is moved away from an element. This attribute may be used with most elements. @param The script */ public void setOnMouseOut(String script) { addAttribute ( "onMouseOut", script ); } /** The onkeypress event occurs when a key is pressed and released over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyPress(String script) { addAttribute ( "onKeyPress", script ); } /** The onkeydown event occurs when a key is pressed down over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyDown(String script) { addAttribute ( "onKeyDown", script ); } /** The onkeyup event occurs when a key is released over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyUp(String script) { addAttribute ( "onKeyUp", script ); } }
apache-2.0
haikuowuya/android_system_code
src/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java
4262
/* * Copyright (c) 2007-2008, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sun.org.apache.xml.internal.security.signature; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; /** * Handles <code>&lt;ds:Object&gt;</code> elements * <code>Object<code> {@link Element} supply facility which can contain any kind data * * @author Christian Geuer-Pollmann * $todo$ if we remove childen, the boolean values are not updated */ public class ObjectContainer extends SignatureElementProxy { /** * Constructs {@link ObjectContainer} * * @param doc the {@link Document} in which <code>Object</code> element is placed */ public ObjectContainer(Document doc) { super(doc); } /** * Constructs {@link ObjectContainer} from {@link Element} * * @param element is <code>Object</code> element * @param BaseURI the URI of the resource where the XML instance was stored * @throws XMLSecurityException */ public ObjectContainer(Element element, String BaseURI) throws XMLSecurityException { super(element, BaseURI); } /** * Sets the <code>Id</code> attribute * * @param Id <code>Id</code> attribute */ public void setId(String Id) { if ((Id != null)) { this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); IdResolver.registerElementById(this._constructionElement, Id); } } /** * Returns the <code>Id</code> attribute * * @return the <code>Id</code> attribute */ public String getId() { return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); } /** * Sets the <code>MimeType</code> attribute * * @param MimeType the <code>MimeType</code> attribute */ public void setMimeType(String MimeType) { if ( (MimeType != null)) { this._constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType); } } /** * Returns the <code>MimeType</code> attribute * * @return the <code>MimeType</code> attribute */ public String getMimeType() { return this._constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); } /** * Sets the <code>Encoding</code> attribute * * @param Encoding the <code>Encoding</code> attribute */ public void setEncoding(String Encoding) { if ((Encoding != null)) { this._constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding); } } /** * Returns the <code>Encoding</code> attribute * * @return the <code>Encoding</code> attribute */ public String getEncoding() { return this._constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); } /** * Adds child Node * * @param node child Node * @return the new node in the tree. */ public Node appendChild(Node node) { Node result = null; result = this._constructionElement.appendChild(node); return result; } /** @inheritDoc */ public String getBaseLocalName() { return Constants._TAG_OBJECT; } }
apache-2.0
mysisl/blade
src/main/java/com/smallchill/core/toolbox/cache/ICache.java
1208
/** * Copyright (c) 2015-2017, Chill Zhuang 庄骞 (smallchill@163.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.smallchill.core.toolbox.cache; import java.util.List; /** * 通用缓存接口 */ public interface ICache { public void put(String cacheName, Object key, Object value); public <T> T get(String cacheName, Object key); @SuppressWarnings("rawtypes") public List getKeys(String cacheName); public void remove(String cacheName, Object key); public void removeAll(String cacheName); public <T> T get(String cacheName, Object key, ILoader iLoader); public <T> T get(String cacheName, Object key, Class<? extends ILoader> iLoaderClass); }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-elastictranscoder/src/main/java/com/amazonaws/services/elastictranscoder/model/transform/ThumbnailsJsonUnmarshaller.java
4353
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elastictranscoder.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.elastictranscoder.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Thumbnails JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ThumbnailsJsonUnmarshaller implements Unmarshaller<Thumbnails, JsonUnmarshallerContext> { public Thumbnails unmarshall(JsonUnmarshallerContext context) throws Exception { Thumbnails thumbnails = new Thumbnails(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Format", targetDepth)) { context.nextToken(); thumbnails.setFormat(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Interval", targetDepth)) { context.nextToken(); thumbnails.setInterval(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Resolution", targetDepth)) { context.nextToken(); thumbnails.setResolution(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("AspectRatio", targetDepth)) { context.nextToken(); thumbnails.setAspectRatio(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("MaxWidth", targetDepth)) { context.nextToken(); thumbnails.setMaxWidth(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("MaxHeight", targetDepth)) { context.nextToken(); thumbnails.setMaxHeight(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("SizingPolicy", targetDepth)) { context.nextToken(); thumbnails.setSizingPolicy(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("PaddingPolicy", targetDepth)) { context.nextToken(); thumbnails.setPaddingPolicy(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return thumbnails; } private static ThumbnailsJsonUnmarshaller instance; public static ThumbnailsJsonUnmarshaller getInstance() { if (instance == null) instance = new ThumbnailsJsonUnmarshaller(); return instance; } }
apache-2.0
IHTSDO/release-validation-framework
validation-service/src/main/java/org/ihtsdo/rvf/validation/RF2FileStructureTester.java
4965
package org.ihtsdo.rvf.validation; import java.io.BufferedReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.ihtsdo.rvf.validation.impl.StreamTestReport; import org.ihtsdo.rvf.validation.log.ValidationLog; import org.ihtsdo.rvf.validation.resource.ResourceProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To verify that each line (including last line) in RF2 file is terminated by CR followed by LF (i.e "\r\n"). * */ public class RF2FileStructureTester { private static final String EMPTY_FILE_CHECKING = " empty file checking"; private static final String RF2_LINE_SEPARATOR = "\r\n"; private static final String TEST_TYPE = "line terminator check"; private final ValidationLog validationLog; private final ResourceProvider resourceManager; private final TestReportable testReport; private Date startTime; public static final String LINE_ENDING = RF2_LINE_SEPARATOR; private static final String UTF_8 = "UTF-8"; private static final Logger LOGGER = LoggerFactory.getLogger(RF2FileStructureTester.class); /** * @param validationLog * @param resourceManager * @param testReport */ public RF2FileStructureTester(final ValidationLog validationLog, final ResourceProvider resourceManager, StreamTestReport testReport) { this.validationLog = validationLog; this.resourceManager = resourceManager; this.testReport = testReport; } public void runTests(){ startTime = new Date(); List<String> fileNames = resourceManager.getFileNames(); ExecutorService executorService = Executors.newCachedThreadPool(); List<Future<Boolean>> futures = new ArrayList<>(); for (final String fileName : fileNames) { if (!fileName.endsWith(".txt")) { continue; } Future<Boolean> task = executorService.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return runTestForFile(fileName); } }); futures.add(task); } for (Future<Boolean> task : futures) { try { task.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Task failed when structure testing due to:", e); validationLog.executionError("Error", "Failed to check file due to:" + e.fillInStackTrace()); } } } private boolean runTestForFile(String fileName) { //check total line numbers match or not int totalLine = 0; int totalLineScanned = 0; try (BufferedReader reader = resourceManager.getReader(fileName, Charset.forName(UTF_8)); Scanner scanner = new Scanner(resourceManager.getReader(fileName, Charset.forName(UTF_8)))) { scanner.useDelimiter(RF2_LINE_SEPARATOR); while ((reader.readLine()) != null) { totalLine++; } if (totalLine == 0) { testReport.addError("0-0", startTime, fileName, resourceManager.getFilePath(), fileName + EMPTY_FILE_CHECKING, EMPTY_FILE_CHECKING, null,"total line is :" + totalLine, " RF2 file can't be empty and should at least have a header line",null); } while (scanner.hasNext()) { scanner.next(); totalLineScanned++; } if (totalLineScanned < totalLine) { testReport.addError("0-0", startTime, fileName, resourceManager.getFilePath(), fileName + " line terminator", TEST_TYPE, null, "total line is terminated with CR+LF:" + totalLineScanned , "total line is terminated with CR+LF:" + totalLine,null); } } catch (Exception e) { validationLog.executionError("Error", "Failed to read file:" + fileName); } try (BufferedReader lineReader = new BufferedReader(resourceManager.getReader(fileName, Charset.forName(UTF_8)))) { for (int i = 1;i <= totalLine; i++) { lineReader.readLine(); if (i == (totalLine - 1)) { int read = -1; StringBuilder builder = new StringBuilder(); while ((read = lineReader.read()) != -1) { char charRead = (char)read; if ((charRead == '\r') || (charRead == '\n')) { builder.append(charRead); } } if (!RF2_LINE_SEPARATOR.equals(builder.toString())) { StringBuilder actualResult = new StringBuilder(); String actualLineSeparator = builder.toString().replace("\n", "LF").replace("\r", "CR"); actualResult.append("the last line is terminated with["); actualResult.append(actualLineSeparator); actualResult.append("]"); testReport.addError(totalLine + "-0", startTime, fileName, resourceManager.getFilePath(), fileName + " ast line terminator",TEST_TYPE, null, actualResult.toString(), "the last line is terminated with CR+LF",null); } break; } } } catch (Exception e) { validationLog.executionError("Error", "Failed to read file:" + fileName); } return true; } }
apache-2.0
linhtynny/androiddev2017
MyApplication/app/src/main/java/vn/edu/usth/myapplication/DrawerItemCustomAdapter.java
1407
package vn.edu.usth.myapplication; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; /** * Created by linhtynny on 04/12/2016. */ public class DrawerItemCustomAdapter extends ArrayAdapter<ObjectDrawerItem> { Context mContext; int layoutResourceId; ObjectDrawerItem data[] = null; public DrawerItemCustomAdapter(Context mContext, int layoutResourceId, ObjectDrawerItem[] data) { super(mContext, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.mContext = mContext; this.data = data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View listItem = convertView; LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); listItem = inflater.inflate(layoutResourceId, parent, false); ImageView imageViewIcon = (ImageView) listItem.findViewById(R.id.imageViewIcon); TextView textViewName = (TextView) listItem.findViewById(R.id.textViewName); ObjectDrawerItem folder = data[position]; imageViewIcon.setImageResource(folder.icon); textViewName.setText(folder.name); return listItem; } }
apache-2.0
Orange-OpenSource/matos-profiles
matos-android/src/main/java/android/media/CameraProfile.java
1103
package android.media; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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. * #L% */ public class CameraProfile { // Fields public static final int QUALITY_LOW = 0; public static final int QUALITY_MEDIUM = 1; public static final int QUALITY_HIGH = 2; // Constructors public CameraProfile(){ } // Methods public static int getJpegEncodingQualityParameter(int arg1){ return 0; } public static int getJpegEncodingQualityParameter(int arg1, int arg2){ return 0; } }
apache-2.0
vipshop/Saturn
saturn-console-api/src/main/java/com/vip/saturn/job/console/service/impl/statistics/analyzer/DomainStatisticsAnalyzer.java
3582
/** * Copyright 2016 vip.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * 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. * </p> **/ package com.vip.saturn.job.console.service.impl.statistics.analyzer; import com.vip.saturn.job.console.domain.DomainStatistics; import com.vip.saturn.job.console.domain.JobStatistics; import com.vip.saturn.job.console.domain.RegistryCenterConfiguration; import com.vip.saturn.job.console.domain.ZkCluster; import com.vip.saturn.job.console.repository.zookeeper.CuratorRepository; import com.vip.saturn.job.console.utils.ExecutorNodePath; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author timmy.hu */ public class DomainStatisticsAnalyzer { private List<DomainStatistics> domainList = new ArrayList<DomainStatistics>(); public DomainStatistics initDomain(ZkCluster zkCluster, RegistryCenterConfiguration config) { DomainStatistics domain = new DomainStatistics(config.getNamespace(), zkCluster.getZkAddr(), config.getNameAndNamespace()); addDomain(domain); return domain; } private synchronized void addDomain(DomainStatistics domain) { domainList.add(domain); } public void analyzeProcessCount(DomainStatistics domainStatistics, ZkClusterDailyCountAnalyzer zkClusterDailyCountAnalyzer, List<String> jobs, Map<String, JobStatistics> jobMap, RegistryCenterConfiguration config) { long processCountOfThisDomainAllTime = 0; long errorCountOfThisDomainAllTime = 0; long processCountOfThisDomainThisDay = 0; long errorCountOfThisDomainThisDay = 0; for (String job : jobs) { String jobDomainKey = job + "-" + config.getNamespace(); JobStatistics jobStatistics = jobMap.get(jobDomainKey); if (jobStatistics != null) { processCountOfThisDomainAllTime += jobStatistics.getProcessCountOfAllTime(); errorCountOfThisDomainAllTime += jobStatistics.getErrorCountOfAllTime(); processCountOfThisDomainThisDay += jobStatistics.getProcessCountOfTheDay(); errorCountOfThisDomainThisDay += jobStatistics.getFailureCountOfTheDay(); } } zkClusterDailyCountAnalyzer.incrTotalCount(processCountOfThisDomainThisDay); zkClusterDailyCountAnalyzer.incrErrorCount(errorCountOfThisDomainThisDay); domainStatistics.setErrorCountOfAllTime(errorCountOfThisDomainAllTime); domainStatistics.setProcessCountOfAllTime(processCountOfThisDomainAllTime); domainStatistics.setErrorCountOfTheDay(errorCountOfThisDomainThisDay); domainStatistics.setProcessCountOfTheDay(processCountOfThisDomainThisDay); } /** * 统计稳定性 */ public void analyzeShardingCount(CuratorRepository.CuratorFrameworkOp curatorFrameworkOp, DomainStatistics domainStatistics) { if (curatorFrameworkOp.checkExists(ExecutorNodePath.SHARDING_COUNT_PATH)) { String countStr = curatorFrameworkOp.getData(ExecutorNodePath.SHARDING_COUNT_PATH); if(StringUtils.isNotBlank(countStr)) { domainStatistics.setShardingCount(Integer.parseInt(countStr)); } } } public List<DomainStatistics> getDomainList() { return new ArrayList<DomainStatistics>(domainList); } }
apache-2.0
AlexandrebQueiroz/acal
src/telas/TelaLogin.java
10514
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package telas; import dao.DaoUsuario; import entidades.User; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import org.hibernate.Session; /** * * @author alexandre */ public class TelaLogin extends javax.swing.JFrame { /** * Creates new form TelaLogin */ //private TelaPrincipal telaPrincipal; public TelaLogin() { initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextFieldTelaLoginNome = new javax.swing.JTextField(); jButtonTelaLoginLogar = new javax.swing.JButton(); jPasswordFieldTelaPrincipalSenha = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setIconImage(new ImageIcon(getClass().getResource("/img/ico.png")).getImage()); setResizable(false); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Seja bem vindo")); jLabel1.setText("Nome"); jLabel2.setText("Senha"); jTextFieldTelaLoginNome.setText("root"); jTextFieldTelaLoginNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldTelaLoginNomeActionPerformed(evt); } }); jButtonTelaLoginLogar.setText("Logar"); jButtonTelaLoginLogar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTelaLoginLogarActionPerformed(evt); } }); jPasswordFieldTelaPrincipalSenha.setText("123"); jPasswordFieldTelaPrincipalSenha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jPasswordFieldTelaPrincipalSenhaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonTelaLoginLogar, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jTextFieldTelaLoginNome, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE) .addComponent(jPasswordFieldTelaPrincipalSenha)) .addContainerGap(22, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldTelaLoginNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jPasswordFieldTelaPrincipalSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addComponent(jButtonTelaLoginLogar) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonTelaLoginLogarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTelaLoginLogarActionPerformed comecar(); }//GEN-LAST:event_jButtonTelaLoginLogarActionPerformed private void jPasswordFieldTelaPrincipalSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordFieldTelaPrincipalSenhaActionPerformed comecar(); }//GEN-LAST:event_jPasswordFieldTelaPrincipalSenhaActionPerformed private void jTextFieldTelaLoginNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldTelaLoginNomeActionPerformed comecar(); }//GEN-LAST:event_jTextFieldTelaLoginNomeActionPerformed private void comecar(){ Session session = null; try { String log = jTextFieldTelaLoginNome.getText(); String pass = new String(jPasswordFieldTelaPrincipalSenha.getPassword()); DaoUsuario du = new DaoUsuario(); User usuario = du.BuscaUsuario(log, pass); if (usuario != null) { // session = new AnnotationConfiguration().configure("hibernate.cfg.xml").setProperty("hibernate.connection.username", log).setProperty("hibernate.connection.password", pass).buildSessionFactory().openSession(); Properties prop = new Properties(); File caminho = new File("properties/hibernate.properties"); File dir = new File("properties/"); if(!caminho.exists()){ dir.mkdir(); caminho.createNewFile(); } prop.setProperty("hibernate.connection.username", log); prop.setProperty("hibernate.connection.password", pass); FileOutputStream fo; try { fo = new FileOutputStream(caminho); prop.store(fo, null); fo.close(); } catch (IOException ex) { Logger.getLogger(TelaPrincipal.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } new TelaPrincipal().setVisible(true); dispose(); } else { throw new Exception(); } } catch (Exception e) { e.printStackTrace(); jTextFieldTelaLoginNome.setText(""); jPasswordFieldTelaPrincipalSenha.setText(""); jTextFieldTelaLoginNome.setFocusable(true); jTextFieldTelaLoginNome.requestFocus(); JOptionPane.showMessageDialog(this, "Verifique o nome do usuário e a senha", "Login", JOptionPane.OK_OPTION); } finally { if (session != null) { session.close(); } } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new TelaLogin().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonTelaLoginLogar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPasswordField jPasswordFieldTelaPrincipalSenha; private javax.swing.JTextField jTextFieldTelaLoginNome; // End of variables declaration//GEN-END:variables }
apache-2.0
ufoscout/jpattern
core/src/main/java/com/jpattern/core/command/AsyncRollbackCommandWrapper.java
468
package com.jpattern.core.command; /** * * @author Francesco Cina' * * 11/set/2011 */ public class AsyncRollbackCommandWrapper implements Runnable { private final ACommand<?> command; private final ACommandResult commandResult; AsyncRollbackCommandWrapper(ACommand<?> command, ACommandResult commandResult) { this.command = command; this.commandResult = commandResult; } @Override public void run() { command.doRollback( commandResult); } }
apache-2.0
ConsecroMUD/ConsecroMUD
com/suscipio_solutions/consecro_mud/Abilities/Songs/Skill_Conduct.java
3421
package com.suscipio_solutions.consecro_mud.Abilities.Songs; import java.util.Set; import java.util.Vector; import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability; import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg; import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB; import com.suscipio_solutions.consecro_mud.core.CMClass; import com.suscipio_solutions.consecro_mud.core.CMLib; import com.suscipio_solutions.consecro_mud.core.interfaces.Physical; @SuppressWarnings("rawtypes") public class Skill_Conduct extends BardSkill { @Override public String ID() { return "Skill_Conduct"; } private final static String localizedName = CMLib.lang().L("Conduct Symphony"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Conduct Symphony)"); @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode(){return CAN_MOBS;} @Override protected int canTargetCode(){return CAN_MOBS;} private static final String[] triggerStrings =I(new String[] {"CONDUCT"}); @Override public String[] triggerStrings(){return triggerStrings;} @Override public int classificationCode(){ return Ability.ACODE_SKILL|Ability.DOMAIN_PLAYING;} @Override public int maxRange(){return adjustedMaxInvokerRange(2);} @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { Ability SYMPHONY=mob.fetchAbility("Play_Symphony"); if((!auto)&&(SYMPHONY==null)) { mob.tell(L("But you don't know how to play a symphony.")); return false; } if(SYMPHONY==null) { SYMPHONY=CMClass.getAbility("Play_Symphony"); SYMPHONY.setProficiency(100); } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; if((!auto)&&(!CMLib.flags().aliveAwakeMobileUnbound(mob,false))) return false; final boolean success=proficiencyCheck(mob,0,auto); new Play().unplayAll(mob,mob); if(success) { String str=auto?L("^SSymphonic Conduction Begins!^?"):L("^S<S-NAME> begin(s) to wave <S-HIS-HER> arms in a mystical way!^?"); if((!auto)&&(mob.fetchEffect(this.ID())!=null)) str=L("^S<S-NAME> start(s) conducting the symphony over again.^?"); final CMMsg msg=CMClass.getMsg(mob,null,this,(auto?CMMsg.MASK_ALWAYS:0)|CMMsg.MSG_CAST_SOMANTIC_SPELL,str); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); invoker=mob; final Set<MOB> h=properTargets(mob,givenTarget,auto); if(h==null) return false; if(!h.contains(mob)) h.add(mob); for (final Object element : h) { final MOB follower=(MOB)element; // malicious songs must not affect the invoker! int affectType=CMMsg.MSG_CAST_SOMANTIC_SPELL; if(auto) affectType=affectType|CMMsg.MASK_ALWAYS; if(CMLib.flags().canBeSeenBy(invoker,follower)) { final CMMsg msg2=CMClass.getMsg(mob,follower,this,affectType,null); if(mob.location().okMessage(mob,msg2)) { follower.location().send(follower,msg2); if(msg2.value()<=0) SYMPHONY.invoke(follower,new Vector(),null,false,asLevel+(3*getXLEVELLevel(mob))); } } } mob.location().recoverRoomStats(); } } else mob.location().show(mob,null,CMMsg.MSG_NOISE,L("<S-NAME> wave(s) <S-HIS-HER> arms around, looking silly.")); return success; } }
apache-2.0
weld/core
tests-arquillian/src/test/java/org/jboss/weld/tests/producer/method/NamedProducerWithBinding.java
1151
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.weld.tests.producer.method; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Produces; import jakarta.inject.Named; import java.util.Date; /** * @author Dan Allen */ @Dependent public class NamedProducerWithBinding { public @Produces @Important @Named Date getDate() { return new Date(); } }
apache-2.0
galan/commons
src/test/java/de/galan/commons/net/mail/MailAddressTest.java
1642
package de.galan.commons.net.mail; import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*; import java.util.stream.Stream; import javax.mail.internet.AddressException; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * CUT MailAddress */ public class MailAddressTest { @ParameterizedTest @MethodSource("dataFormatValid") public void formatValid(DateItem item) throws AddressException { MailAddress ma = MailAddress.of(item.address); assertThat(ma.getAddress()).isEqualTo(item.email); assertThat(ma.getName()).isEqualTo(item.name); } public static Stream<DateItem> dataFormatValid() { return Stream.of( new DateItem("hello@example.com", "hello@example.com", null), new DateItem("huh+123@example.co.uk", "huh+123@example.co.uk", null), new DateItem("Mr. Soso <huh+123@example.co.uk>", "huh+123@example.co.uk", "Mr. Soso"), new DateItem(" Some One < some@example.de >", "some@example.de", "Some One"), new DateItem(" Some One < some@1.2.3.4 >", "some@1.2.3.4", "Some One")); } @ParameterizedTest @MethodSource("dataFormatInvalid") public void formatInvalid(String address) { assertThrows(AddressException.class, () -> { MailAddress.of(address); }); } public static Stream<String> dataFormatInvalid() { return Stream.of("@example.com", "Some One", "Some One <>"); } } /** Mock */ class DateItem { public DateItem(String address, String email, String name) { this.address = address; this.email = email; this.name = name; } String address; String email; String name; }
apache-2.0
Distrotech/fop
src/java/org/apache/fop/apps/FOUserAgent.java
22672
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.apps; // Java import java.io.File; import java.net.MalformedURLException; import java.util.Date; import java.util.Map; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xmlgraphics.image.loader.ImageContext; import org.apache.xmlgraphics.image.loader.ImageSessionContext; import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext; import org.apache.xmlgraphics.util.UnitConv; import org.apache.fop.Version; import org.apache.fop.accessibility.Accessibility; import org.apache.fop.accessibility.DummyStructureTreeEventHandler; import org.apache.fop.accessibility.StructureTreeEventHandler; import org.apache.fop.events.DefaultEventBroadcaster; import org.apache.fop.events.Event; import org.apache.fop.events.EventBroadcaster; import org.apache.fop.events.EventListener; import org.apache.fop.events.FOPEventListenerProxy; import org.apache.fop.events.LoggingEventListener; import org.apache.fop.fo.FOEventHandler; import org.apache.fop.render.Renderer; import org.apache.fop.render.RendererFactory; import org.apache.fop.render.XMLHandlerRegistry; import org.apache.fop.render.intermediate.IFDocumentHandler; /** * This is the user agent for FOP. * It is the entity through which you can interact with the XSL-FO processing and is * used by the processing to obtain user configurable options. * <p> * Renderer specific extensions (that do not produce normal areas on * the output) will be done like so: * <br> * The extension will create an area, custom if necessary * <br> * this area will be added to the user agent with a key * <br> * the renderer will know keys for particular extensions * <br> * eg. bookmarks will be held in a special hierarchical area representing * the title and bookmark structure * <br> * These areas may contain resolvable areas that will be processed * with other resolvable areas */ public class FOUserAgent { /** Defines the default target resolution (72dpi) for FOP */ public static final float DEFAULT_TARGET_RESOLUTION = FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; private static Log log = LogFactory.getLog("FOP"); private FopFactory factory; /** * The base URL for all URL resolutions, especially for * external-graphics. */ private String base = null; /** A user settable URI Resolver */ private URIResolver uriResolver = null; private float targetResolution = FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; private Map rendererOptions = new java.util.HashMap(); private File outputFile = null; private IFDocumentHandler documentHandlerOverride = null; private Renderer rendererOverride = null; private FOEventHandler foEventHandlerOverride = null; private boolean locatorEnabled = true; // true by default (for error messages). private boolean conserveMemoryPolicy = false; private EventBroadcaster eventBroadcaster = new FOPEventBroadcaster(); private StructureTreeEventHandler structureTreeEventHandler = DummyStructureTreeEventHandler.INSTANCE; /** Producer: Metadata element for the system/software that produces * the document. (Some renderers can store this in the document.) */ protected String producer = "Apache FOP Version " + Version.getVersion(); /** Creator: Metadata element for the user that created the * document. (Some renderers can store this in the document.) */ protected String creator = null; /** Creation Date: Override of the date the document was created. * (Some renderers can store this in the document.) */ protected Date creationDate = null; /** Author of the content of the document. */ protected String author = null; /** Title of the document. */ protected String title = null; /** Subject of the document. */ protected String subject = null; /** Set of keywords applicable to this document. */ protected String keywords = null; private ImageSessionContext imageSessionContext = new AbstractImageSessionContext() { public ImageContext getParentContext() { return getFactory(); } public float getTargetResolution() { return FOUserAgent.this.getTargetResolution(); } public Source resolveURI(String uri) { return FOUserAgent.this.resolveURI(uri); } }; /** * Main constructor. <b>This constructor should not be called directly. Please use the * methods from FopFactory to construct FOUserAgent instances!</b> * @param factory the factory that provides environment-level information * @see org.apache.fop.apps.FopFactory */ public FOUserAgent(FopFactory factory) { if (factory == null) { throw new NullPointerException("The factory parameter must not be null"); } this.factory = factory; setBaseURL(factory.getBaseURL()); setTargetResolution(factory.getTargetResolution()); setAccessibility(factory.isAccessibilityEnabled()); } /** @return the associated FopFactory instance */ public FopFactory getFactory() { return this.factory; } // ---------------------------------------------- rendering-run dependent stuff /** * Sets an explicit document handler to use which overrides the one that would be * selected by default. * @param documentHandler the document handler instance to use */ public void setDocumentHandlerOverride(IFDocumentHandler documentHandler) { if (isAccessibilityEnabled()) { setStructureTreeEventHandler(documentHandler.getStructureTreeEventHandler()); } this.documentHandlerOverride = documentHandler; } /** * Returns the overriding {@link IFDocumentHandler} instance, if any. * @return the overriding document handler or null */ public IFDocumentHandler getDocumentHandlerOverride() { return this.documentHandlerOverride; } /** * Sets an explicit renderer to use which overrides the one defined by the * render type setting. * @param renderer the Renderer instance to use */ public void setRendererOverride(Renderer renderer) { this.rendererOverride = renderer; } /** * Returns the overriding Renderer instance, if any. * @return the overriding Renderer or null */ public Renderer getRendererOverride() { return rendererOverride; } /** * Sets an explicit FOEventHandler instance which overrides the one * defined by the render type setting. * @param handler the FOEventHandler instance */ public void setFOEventHandlerOverride(FOEventHandler handler) { this.foEventHandlerOverride = handler; } /** * Returns the overriding FOEventHandler instance, if any. * @return the overriding FOEventHandler or null */ public FOEventHandler getFOEventHandlerOverride() { return this.foEventHandlerOverride; } /** * Sets the producer of the document. * @param producer source of document */ public void setProducer(String producer) { this.producer = producer; } /** * Returns the producer of the document * @return producer name */ public String getProducer() { return producer; } /** * Sets the creator of the document. * @param creator of document */ public void setCreator(String creator) { this.creator = creator; } /** * Returns the creator of the document * @return creator name */ public String getCreator() { return creator; } /** * Sets the creation date of the document. * @param creationDate date of document */ public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } /** * Returns the creation date of the document * @return creation date of document */ public Date getCreationDate() { return creationDate; } /** * Sets the author of the document. * @param author of document */ public void setAuthor(String author) { this.author = author; } /** * Returns the author of the document * @return author name */ public String getAuthor() { return author; } /** * Sets the title of the document. This will override any title coming from * an fo:title element. * @param title of document */ public void setTitle(String title) { this.title = title; } /** * Returns the title of the document * @return title name */ public String getTitle() { return title; } /** * Sets the subject of the document. * @param subject of document */ public void setSubject(String subject) { this.subject = subject; } /** * Returns the subject of the document * @return the subject */ public String getSubject() { return subject; } /** * Sets the keywords for the document. * @param keywords for the document */ public void setKeywords(String keywords) { this.keywords = keywords; } /** * Returns the keywords for the document * @return the keywords */ public String getKeywords() { return keywords; } /** * Returns the renderer options * @return renderer options */ public Map getRendererOptions() { return rendererOptions; } /** * Sets the base URL. * @param baseUrl base URL */ public void setBaseURL(String baseUrl) { this.base = baseUrl; } /** * Sets font base URL. * @param fontBaseUrl font base URL * @deprecated Use {@link org.apache.fop.fonts.FontManager#setFontBaseURL(String)} instead. */ public void setFontBaseURL(String fontBaseUrl) { try { getFactory().getFontManager().setFontBaseURL(fontBaseUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Returns the base URL. * @return the base URL */ public String getBaseURL() { return this.base; } /** * Sets the URI Resolver. * @param resolver the new URI resolver */ public void setURIResolver(URIResolver resolver) { this.uriResolver = resolver; } /** * Returns the URI Resolver. * @return the URI Resolver */ public URIResolver getURIResolver() { return this.uriResolver; } /** * Attempts to resolve the given URI. * Will use the configured resolver and if not successful fall back * to the default resolver. * @param uri URI to access * @return A {@link javax.xml.transform.Source} object, or null if the URI * cannot be resolved. * @see org.apache.fop.apps.FOURIResolver */ public Source resolveURI(String uri) { return resolveURI(uri, getBaseURL()); } /** * Attempts to resolve the given URI. * Will use the configured resolver and if not successful fall back * to the default resolver. * @param href URI to access * @param base the base URI to resolve against * @return A {@link javax.xml.transform.Source} object, or null if the URI * cannot be resolved. * @see org.apache.fop.apps.FOURIResolver */ public Source resolveURI(String href, String base) { Source source = null; //RFC 2397 data URLs don't need to be resolved, just decode them through FOP's default //URIResolver. boolean bypassURIResolution = href.startsWith("data:"); if (!bypassURIResolution && uriResolver != null) { try { source = uriResolver.resolve(href, base); } catch (TransformerException te) { log.error("Attempt to resolve URI '" + href + "' failed: ", te); } } if (source == null) { // URI Resolver not configured or returned null, use default resolver from the factory source = getFactory().resolveURI(href, base); } return source; } /** * Sets the output File. * @param f the output File */ public void setOutputFile(File f) { this.outputFile = f; } /** * Gets the output File. * @return the output File */ public File getOutputFile() { return outputFile; } /** * Returns the conversion factor from pixel units to millimeters. This * depends on the desired target resolution. * @return float conversion factor * @see #getTargetResolution() */ public float getTargetPixelUnitToMillimeter() { return UnitConv.IN2MM / this.targetResolution; } /** @return the resolution for resolution-dependant output */ public float getTargetResolution() { return this.targetResolution; } /** * Sets the target resolution in dpi. This value defines the target resolution of * bitmap images generated by the bitmap renderers (such as the TIFF renderer) and of * bitmap images generated by filter effects in Apache Batik. * @param dpi resolution in dpi */ public void setTargetResolution(float dpi) { this.targetResolution = dpi; if (log.isDebugEnabled()) { log.debug("target-resolution set to: " + targetResolution + "dpi (px2mm=" + getTargetPixelUnitToMillimeter() + ")"); } } /** * Sets the target resolution in dpi. This value defines the target resolution of * bitmap images generated by the bitmap renderers (such as the TIFF renderer) and of * bitmap images generated by filter effects in Apache Batik. * @param dpi resolution in dpi */ public void setTargetResolution(int dpi) { setTargetResolution((float)dpi); } /** * Returns the image session context for the image package. * @return the ImageSessionContext instance for this rendering run */ public ImageSessionContext getImageSessionContext() { return this.imageSessionContext; } // ---------------------------------------------- environment-level stuff // (convenience access to FopFactory methods) /** * Returns the font base URL. * @return the font base URL * @deprecated Use {@link org.apache.fop.fonts.FontManager#getFontBaseURL()} instead. * This method is not used by FOP. */ public String getFontBaseURL() { String fontBase = getFactory().getFontManager().getFontBaseURL(); return fontBase != null ? fontBase : getBaseURL(); } /** * Returns the conversion factor from pixel units to millimeters. This * depends on the desired source resolution. * @return float conversion factor * @see #getSourceResolution() */ public float getSourcePixelUnitToMillimeter() { return getFactory().getSourcePixelUnitToMillimeter(); } /** @return the resolution for resolution-dependant input */ public float getSourceResolution() { return getFactory().getSourceResolution(); } /** * Gets the default page-height to use as fallback, * in case page-height="auto" * * @return the page-height, as a String * @see FopFactory#getPageHeight() */ public String getPageHeight() { return getFactory().getPageHeight(); } /** * Gets the default page-width to use as fallback, * in case page-width="auto" * * @return the page-width, as a String * @see FopFactory#getPageWidth() */ public String getPageWidth() { return getFactory().getPageWidth(); } /** * Returns whether FOP is strictly validating input XSL * @return true of strict validation turned on, false otherwise * @see FopFactory#validateStrictly() */ public boolean validateStrictly() { return getFactory().validateStrictly(); } /** * @return true if the indent inheritance should be broken when crossing reference area * boundaries (for more info, see the javadoc for the relative member variable) * @see FopFactory#isBreakIndentInheritanceOnReferenceAreaBoundary() */ public boolean isBreakIndentInheritanceOnReferenceAreaBoundary() { return getFactory().isBreakIndentInheritanceOnReferenceAreaBoundary(); } /** * @return the RendererFactory */ public RendererFactory getRendererFactory() { return getFactory().getRendererFactory(); } /** * @return the XML handler registry */ public XMLHandlerRegistry getXMLHandlerRegistry() { return getFactory().getXMLHandlerRegistry(); } /** * Controls the use of SAXLocators to provide location information in error * messages. * * @param enableLocator <code>false</code> if SAX Locators should be disabled */ public void setLocatorEnabled(boolean enableLocator) { locatorEnabled = enableLocator; } /** * Checks if the use of Locators is enabled * @return true if context information should be stored on each node in the FO tree. */ public boolean isLocatorEnabled() { return locatorEnabled; } /** * Returns the event broadcaster that control events sent inside a processing run. Clients * can register event listeners with the event broadcaster to listen for events that occur * while a document is being processed. * @return the event broadcaster. */ public EventBroadcaster getEventBroadcaster() { return this.eventBroadcaster; } private class FOPEventBroadcaster extends DefaultEventBroadcaster { private EventListener rootListener; public FOPEventBroadcaster() { //Install a temporary event listener that catches the first event to //do some initialization. this.rootListener = new EventListener() { public void processEvent(Event event) { if (!listeners.hasEventListeners()) { //Backwards-compatibility: Make sure at least the LoggingEventListener is //plugged in so no events are just silently swallowed. addEventListener( new LoggingEventListener(LogFactory.getLog(FOUserAgent.class))); } //Replace with final event listener rootListener = new FOPEventListenerProxy( listeners, FOUserAgent.this); rootListener.processEvent(event); } }; } /** {@inheritDoc} */ public void broadcastEvent(Event event) { rootListener.processEvent(event); } } /** * Check whether memory-conservation is enabled. * * @return true if FOP is to conserve as much as possible */ public boolean isConserveMemoryPolicyEnabled() { return this.conserveMemoryPolicy; } /** * Control whether memory-conservation should be enabled * * @param conserveMemoryPolicy the cachingEnabled to set */ public void setConserveMemoryPolicy(boolean conserveMemoryPolicy) { this.conserveMemoryPolicy = conserveMemoryPolicy; } /** * Check whether complex script features are enabled. * * @return true if FOP is to use complex script features */ public boolean isComplexScriptFeaturesEnabled() { return factory.isComplexScriptFeaturesEnabled(); } /** * Control whether complex script features should be enabled * * @param useComplexScriptFeatures true if FOP is to use complex script features */ public void setComplexScriptFeaturesEnabled(boolean useComplexScriptFeatures) { factory.setComplexScriptFeaturesEnabled ( useComplexScriptFeatures ); } /** * Activates accessibility (for output formats that support it). * * @param accessibility <code>true</code> to enable accessibility support */ public void setAccessibility(boolean accessibility) { if (accessibility) { getRendererOptions().put(Accessibility.ACCESSIBILITY, Boolean.TRUE); } } /** * Check if accessibility is enabled. * @return true if accessibility is enabled */ public boolean isAccessibilityEnabled() { Boolean enabled = (Boolean)this.getRendererOptions().get(Accessibility.ACCESSIBILITY); if (enabled != null) { return enabled.booleanValue(); } else { return false; } } /** * Sets the document's structure tree event handler, for use by accessible * output formats. * * @param structureTreeEventHandler The structure tree event handler to set */ public void setStructureTreeEventHandler(StructureTreeEventHandler structureTreeEventHandler) { this.structureTreeEventHandler = structureTreeEventHandler; } /** * Returns the document's structure tree event handler, for use by * accessible output formats. * * @return The structure tree event handler */ public StructureTreeEventHandler getStructureTreeEventHandler() { return this.structureTreeEventHandler; } }
apache-2.0
java110/MicroCommunity
service-goods/src/main/java/com/java110/goods/bmo/storeOrderCartReturnEvent/impl/SaveStoreOrderCartReturnEventBMOImpl.java
1593
package com.java110.goods.bmo.storeOrderCartReturnEvent.impl; import com.java110.core.annotation.Java110Transactional; import com.java110.core.factory.GenerateCodeFactory; import com.java110.goods.bmo.storeOrderCartReturnEvent.ISaveStoreOrderCartReturnEventBMO; import com.java110.intf.goods.IStoreOrderCartReturnEventInnerServiceSMO; import com.java110.po.storeOrderCartReturnEvent.StoreOrderCartReturnEventPo; import com.java110.vo.ResultVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @Service("saveStoreOrderCartReturnEventBMOImpl") public class SaveStoreOrderCartReturnEventBMOImpl implements ISaveStoreOrderCartReturnEventBMO { @Autowired private IStoreOrderCartReturnEventInnerServiceSMO storeOrderCartReturnEventInnerServiceSMOImpl; /** * 添加小区信息 * * @param storeOrderCartReturnEventPo * @return 订单服务能够接受的报文 */ @Java110Transactional public ResponseEntity<String> save(StoreOrderCartReturnEventPo storeOrderCartReturnEventPo) { storeOrderCartReturnEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId)); int flag = storeOrderCartReturnEventInnerServiceSMOImpl.saveStoreOrderCartReturnEvent(storeOrderCartReturnEventPo); if (flag > 0) { return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功"); } return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败"); } }
apache-2.0
cltl/EventCoreference
src/main/java/eu/newsreader/eventcoreference/storyline/JsonFromCat.java
72481
package eu.newsreader.eventcoreference.storyline; import eu.kyotoproject.kaf.KafTerm; import eu.kyotoproject.kaf.KafWordForm; import eu.newsreader.eventcoreference.objects.JsonEvent; import eu.newsreader.eventcoreference.util.Util; import org.json.JSONException; import org.json.JSONObject; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.*; import java.util.*; /** * Created by piek on 27/06/16. */ @Deprecated public class JsonFromCat extends DefaultHandler { public class CatLink { private String source; private String target; private String linkId; private String relType; public CatLink() { init(); } public void init() { this.linkId = ""; this.source = ""; this.relType = ""; this.target = ""; } public String getRelType() { return relType; } public void setRelType(String relType) { if (relType!=null) this.relType = relType; } public String getLinkId() { return linkId; } public void setLinkId(String linkId) { this.linkId = linkId; } public String getSource() { return source; } public void setSource(String source) { if (source!=null) this.source = source; } public String getTarget() { return target; } public void setTarget(String target) { if (target!=null) this.target = target; } } public class PlotLink extends CatLink { /* <PLOT_LINK r_id="547121" CAUSED_BY="FALSE" CAUSES="TRUE" relType="FALLING_ACTION" SIGNAL="" > <source m_id="27" /> <target m_id="25" /> </PLOT_LINK> */ private String caused_by; private String causes; private String signal; public PlotLink () { init(); caused_by="FALSE"; causes="FALSE"; signal=""; } public String getCaused_by() { return caused_by; } public void setCaused_by(String caused_by) { this.caused_by = caused_by; } public String getCauses() { return causes; } public void setCauses(String causes) { this.causes = causes; } public String getSignal() { return signal; } public void setSignal(String signal) { this.signal = signal; } } public class TimeLink extends CatLink { /* <TLINK r_id="547988" relType="BEFORE" comment="" contextualModality="ACT" > <source m_id="23" /> <target m_id="59" /> </TLINK> */ private String contextualModality; public TimeLink () { init(); contextualModality = ""; } public String getContextualModality() { return contextualModality; } public void setContextualModality(String contextualModality) { this.contextualModality = contextualModality; } } public class LocationLink extends CatLink { } public class ActorLink extends CatLink { } public class TimeTerm extends KafTerm { private String anchorTimeId; private boolean dct; private String value; public TimeTerm () { anchorTimeId = ""; dct = false; value = ""; } public String getAnchorTimeId() { return anchorTimeId; } public void setAnchorTimeId(String anchorTimeId) { this.anchorTimeId = anchorTimeId; } public boolean isDct() { return dct; } public void setDct(boolean dct) { this.dct = dct; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } String value = ""; String span = ""; String source = ""; String target = ""; String relType = ""; String causedBy = ""; String causes = ""; String contextualModality = ""; String signal = ""; String crossDocId = ""; String singletonId = ""; KafWordForm kafWordForm; KafTerm kafTerm; TimeTerm timeTerm; boolean TIME; ArrayList<String> spans; public HashMap<String, String> termToCorefMap; public HashMap<String, String> eventToStoryMap; public HashMap<String, String> instanceToStoryMap; public HashMap<String, ArrayList<KafTerm>> eventCorefMap; public HashMap<String, ArrayList<String>> storyMap; public HashMap<String, ArrayList<ActorLink>> eventActorLinksMap; public HashMap<String, ArrayList<LocationLink>> eventLocationLinksMap; public HashMap<String, ArrayList<TimeLink>> eventTimeLinksMap; public HashMap<String, ArrayList<PlotLink>> eventPlotLinksMap; public HashMap<String, JSONObject> eventMentionMap; public ArrayList<KafWordForm> kafWordFormArrayList; public ArrayList<KafTerm> eventTermArrayList; public HashMap<String, KafTerm> actorMap; public HashMap<String, KafTerm> locationMap; public HashMap<String, TimeTerm> timeMap; public ArrayList<KafTerm> actorTermArrayList; public ArrayList<KafTerm> locationTermArrayList; public ArrayList<TimeTerm> timeTermArrayList; public ArrayList<TimeLink> timeLinks; public ArrayList<LocationLink> locationLinks; public ArrayList<PlotLink> plotLinks; public ArrayList<ActorLink> actorLinks; String fileName; boolean REFERSTO = false; public JsonFromCat () { initAll(); } public void makeGroupsForInstance () { HashMap<String, ArrayList<String>> groupings = new HashMap<String, ArrayList<String>>(); Set keySet = eventCorefMap.keySet(); Iterator<String> keys = keySet.iterator(); while (keys.hasNext()) { String corefId1 = keys.next(); ArrayList<String> group = new ArrayList<String>(); group.add(corefId1); Iterator<String> keys2 = keySet.iterator(); while (keys2.hasNext()) { String corefId2 = keys2.next(); if (!corefId1.equals(corefId2)) { if (areRelated(corefId1, corefId2)) { group.add(corefId2); } } } groupings.put(corefId1, group); } System.out.println("before chaining groupings.size() = " + groupings.size()); chainGroupings(groupings); System.out.println("after chaining groupings = " + groupings.size()); keySet = groupings.keySet(); keys = keySet.iterator(); while (keys.hasNext()) { String key = keys.next(); ArrayList<String> corefIds = groupings.get(key); if (corefIds.size()>0) { String climax = getClimaxEvent(corefIds); if (climax.isEmpty()) { climax = key; } if (!climax.isEmpty()) { System.out.println("climax = " + climax); for (int i = 0; i < corefIds.size(); i++) { String coref = corefIds.get(i); instanceToStoryMap.put(coref, climax); } } else { } } else { // System.out.println("absorbed key = " + key); } } } public int getClimaxScore (String corefId) { int cnt = 0; if (eventCorefMap.containsKey(corefId)) { ArrayList<KafTerm> eventTerms = eventCorefMap.get(corefId); for (int j = 0; j < eventTerms.size(); j++) { KafTerm eventTerm = eventTerms.get(j); String eventId = eventTerm.getTid(); if (eventPlotLinksMap.containsKey(eventId)) { ArrayList<PlotLink> plotLinks = eventPlotLinksMap.get(eventId); for (int k = 0; k < plotLinks.size(); k++) { PlotLink plotLink = plotLinks.get(k); if (plotLink.getSource().equals(eventId) && plotLink.getRelType().equalsIgnoreCase("FALLING_ACTION")) { cnt++; } else if (plotLink.getTarget().equals(eventId) && plotLink.getRelType().equalsIgnoreCase("PRECONDITION")) { cnt++; } } } } } return cnt; } public String getClimaxEvent (ArrayList<String> corefIds) { String climax = ""; int max = 0; for (int i = 0; i < corefIds.size(); i++) { String corefId = corefIds.get(i); int cnt = getClimaxScore(corefId); if (cnt>max) { climax = corefId; max = cnt; } } return climax; } public void chainGroupings (HashMap<String, ArrayList<String>> groupings) { boolean CHAIN = false; Set keySet = groupings.keySet(); Iterator<String> keys = keySet.iterator(); while (keys.hasNext()) { String key1 = keys.next(); ArrayList<String> group1 = groupings.get(key1); Iterator<String> keys2 = keySet.iterator(); while (keys2.hasNext()) { String key2 = keys2.next(); if (!key2.equals(key1)) { ArrayList<String> group2 = groupings.get(key2); if (!Collections.disjoint(group1, group2)) { ///absorb; for (int i = 0; i < group2.size(); i++) { String corefId = group2.get(i); if (!group1.contains(corefId)) { //System.out.println("adding corefId = " + corefId); group1.add(corefId); CHAIN = true; } } groupings.put(key2, new ArrayList<String>()); groupings.put(key1, group1); } } } } if (CHAIN) { chainGroupings(groupings); } } public boolean areRelated (String corefId1, String corefId2) { if (this.eventCorefMap.containsKey(corefId1) && this.eventCorefMap.containsKey(corefId2)) { ArrayList<KafTerm> eventTerms1 = this.eventCorefMap.get(corefId1); ArrayList<String> relatedMentions = new ArrayList<String>(); for (int i = 0; i < eventTerms1.size(); i++) { KafTerm eventTerm = eventTerms1.get(i); String eventId = eventTerm.getTid(); if (eventPlotLinksMap.containsKey(eventId)) { ArrayList<PlotLink> plotLinks = eventPlotLinksMap.get(eventId); for (int j = 0; j < plotLinks.size(); j++) { PlotLink plotLink = plotLinks.get(j); String otherEventId = ""; if (!plotLink.getSource().equals(eventId)) { otherEventId = plotLink.getSource(); } else { otherEventId = plotLink.getTarget(); } if (!relatedMentions.contains(otherEventId)) { relatedMentions.add(otherEventId); } } } if (eventTimeLinksMap.containsKey(eventId)) { ArrayList<TimeLink> tlinks = eventTimeLinksMap.get(eventId); for (int j = 0; j < tlinks.size(); j++) { TimeLink timeLink = tlinks.get(j); String otherEventId = ""; if (!timeLink.getSource().equals(eventId)) { otherEventId = timeLink.getSource(); } else { otherEventId = timeLink.getTarget(); } if (!relatedMentions.contains(otherEventId)) { relatedMentions.add(otherEventId); } } } if (eventLocationLinksMap.containsKey(eventId)) { ArrayList<LocationLink> lLinks = eventLocationLinksMap.get(eventId); for (int j = 0; j < lLinks.size(); j++) { LocationLink locationLink = lLinks.get(j); String otherEventId = ""; if (!locationLink.getSource().equals(eventId)) { otherEventId = locationLink.getSource(); } else { otherEventId = locationLink.getTarget(); } if (!relatedMentions.contains(otherEventId)) { relatedMentions.add(otherEventId); } } } } if (relatedMentions.size()>0) { ArrayList<KafTerm> eventTerms2 = this.eventCorefMap.get(corefId2); for (int i = 0; i < eventTerms2.size(); i++) { KafTerm term = eventTerms2.get(i); if (relatedMentions.contains(term.getTid())) { return true; } } } } return false; } /* public void makeInstanceGroups () { *//* We determine the climax from the Plot links - if relType="FALLING_ACTION" then source is climax event - if relType="PRECONDITION" then target is climax *//* ArrayList<String> coveredEvents = new ArrayList<String>(); Set keySet = eventCorefMap.keySet(); Iterator<String> keys = keySet.iterator(); while (keys.hasNext()) { String corefId = keys.next(); ArrayList<String> group = new ArrayList<String>(); makeInstanceGroup(coveredEvents,group, corefId); } keySet = eventToStoryMap.keySet(); keys = keySet.iterator(); while (keys.hasNext()) { String eventId = keys.next(); String storyId = eventToStoryMap.get(eventId); if (storyMap.containsKey(storyId)) { ArrayList<String> eventIds = storyMap.get(storyId); if (!eventIds.contains(eventId)) { eventIds.add(eventId); storyMap.put(storyId, eventIds); } } else { ArrayList<String> eventIds = new ArrayList<String>(); eventIds.add(eventId); storyMap.put(storyId, eventIds); } } } public String makeInstanceGroup (ArrayList<String> coveredEvents, ArrayList<String> group, String corefId) { String storyId = corefId; if (this.eventCorefMap.containsKey(corefId)) { ArrayList<KafTerm> eventTerms = this.eventCorefMap.get(corefId); ArrayList<String> relatedMentions = new ArrayList<String>(); for (int i = 0; i < eventTerms.size(); i++) { KafTerm eventTerm = eventTerms.get(i); String eventId = eventTerm.getTid(); if (!group.contains(eventId) && !coveredEvents.contains(eventId)) { coveredEvents.add(eventId); group.add(eventId); System.out.println("extending group = " + group); if (eventPlotLinksMap.containsKey(eventId)) { ArrayList<PlotLink> plotLinks = eventPlotLinksMap.get(eventId); for (int j = 0; j < plotLinks.size(); j++) { PlotLink plotLink = plotLinks.get(j); String otherEventId = ""; if (!plotLink.getSource().equals(eventId)) { otherEventId = plotLink.getSource(); } else { otherEventId = plotLink.getTarget(); } if (!relatedMentions.contains(otherEventId)) { relatedMentions.add(otherEventId); } } } if (eventTimeLinksMap.containsKey(eventId)) { ArrayList<TimeLink> tlinks = eventTimeLinksMap.get(eventId); for (int j = 0; j < tlinks.size(); j++) { TimeLink timeLink = tlinks.get(j); String otherEventId = ""; if (!timeLink.getSource().equals(eventId)) { otherEventId = timeLink.getSource(); } else { otherEventId = timeLink.getTarget(); } if (!relatedMentions.contains(otherEventId)) { relatedMentions.add(otherEventId); } } } if (eventLocationLinksMap.containsKey(eventId)) { ArrayList<LocationLink> lLinks = eventLocationLinksMap.get(eventId); for (int j = 0; j < lLinks.size(); j++) { LocationLink locationLink = lLinks.get(j); String otherEventId = ""; if (!locationLink.getSource().equals(eventId)) { otherEventId = locationLink.getSource(); } else { otherEventId = locationLink.getTarget(); } if (!relatedMentions.contains(otherEventId)) { relatedMentions.add(otherEventId); } } } } else { System.out.println("Covered eventId = " + eventId); } } System.out.println("BEFORE RECURSING"); System.out.println("storyId = " + storyId); System.out.println("group = " + group); if (relatedMentions.size()==0) { //// no relations, group is just the coref terms System.out.println("NO RELATED MENTIONS"); } else { System.out.println("relatedMentions = " + relatedMentions); boolean TAKEN = false; for (int i = 0; i < relatedMentions.size(); i++) { String eventId = relatedMentions.get(i); if (eventToStoryMap.containsKey(eventId)) { //// related event is already assigned storyId = eventToStoryMap.get(eventId); System.out.println("already exists storyId = " + storyId); TAKEN = true; break; /// this means we take the first } } if (!TAKEN) { /// related events were not considered, we recurse to extend the group for (int i = 0; i < relatedMentions.size(); i++) { String eventId = relatedMentions.get(i); System.out.println("eventId = " + eventId); *//* coveredEvents.add(eventId); group.add(eventId); *//* if (termToCorefMap.containsKey(eventId)) { String relatedCorefId = termToCorefMap.get(eventId); System.out.println("relatedCorefId = " + relatedCorefId); storyId = makeInstanceGroup(coveredEvents, group, relatedCorefId); System.out.println("storyId = " + storyId); //// this means we take the last instance } else { System.out.println("could not map eventId to coref Map= " + eventId); } } System.out.println("AFTER RECURSING"); System.out.println("group = " + group); System.out.println("storyId = " + storyId); } else { System.out.println("ALL NEW"); } } System.out.println("Adding complete group = " + group); System.out.println("To the storyId = " + storyId); for (int i = 0; i < group.size(); i++) { String eventId = group.get(i); eventToStoryMap.put(eventId, storyId); } } else { System.out.println("Cannot find the corefId = " + corefId); } return storyId; } public void makeGroups () { *//* We determine the climax from the Plot links - if relType="FALLING_ACTION" then source is climax event - if relType="PRECONDITION" then target is climax *//* ArrayList<String> group = new ArrayList<String>(); ArrayList<String> coveredEvents = new ArrayList<String>(); Set keySet = eventPlotLinksMap.keySet(); Iterator<String> keys = keySet.iterator(); while (keys.hasNext()) { String key = keys.next(); if (!coveredEvents.contains(key)) { group = new ArrayList<String>(); group.add(key); coveredEvents.add(key); makeGroup(coveredEvents, group, key); //System.out.println("group.size() = " + group.size()); // System.out.println("coveredEvents = " + coveredEvents.size()); storyMap.put(key, group); } } *//* Now we have story entries based on the climax event, we see if we can attach more through the tlinks *//* *//* for (int i = 0; i < timeLinks.size(); i++) { TimeLink timeLink = timeLinks.get(i); if (!timeLink.getRelType().equalsIgnoreCase("includes")) { //// any other relation than "includes"; check if target or source is a climaxEvent //// if so add the other identifier String climaxEvent = timeLink.getTarget(); if (storyMap.containsKey(climaxEvent)) { ArrayList<String> storyEvents = storyMap.get(climaxEvent); if (!storyEvents.contains(timeLink.getSource())) { storyEvents.add(timeLink.getSource()); storyMap.put(climaxEvent, storyEvents); } } else { climaxEvent = timeLink.getSource(); if (storyMap.containsKey(climaxEvent)) { ArrayList<String> storyEvents = storyMap.get(climaxEvent); if (!storyEvents.contains(timeLink.getTarget())) { storyEvents.add(timeLink.getSource()); storyMap.put(climaxEvent, storyEvents); } } } } } Finally if an event occurs at the same location as the climax event we add it as well HashMap<String, ArrayList<String>> locationMap = new HashMap<String, ArrayList<String>>(); for (int i = 0; i < locationLinks.size(); i++) { LocationLink locationLink = locationLinks.get(i); String event = locationLink.getSource(); String location = locationLink.getTarget(); if (locationMap.containsKey(location)) { ArrayList<String> storyEvents = locationMap.get(location); if (!storyEvents.contains(event)) { storyEvents.add(event); locationMap.put(location, storyEvents); } } else { ArrayList<String> storyEvents = new ArrayList<String>(); storyEvents.add(event); locationMap.put(location, storyEvents); } } keySet = locationMap.keySet(); keys = keySet.iterator(); while (keys.hasNext()) { String key = keys.next(); ArrayList<String> events = locationMap.get(key); for (int i = 0; i < events.size(); i++) { String eventId = events.get(i); if (storyMap.containsKey(eventId)) { ArrayList<String> storyEvents = storyMap.get(eventId); for (int j = 0; j < events.size(); j++) { String coLocatedEventId = events.get(j); if (!coLocatedEventId.equals(eventId) && !storyEvents.contains(coLocatedEventId)) { storyEvents.add(coLocatedEventId); storyMap.put(eventId, storyEvents); } } } } }*//* keySet = storyMap.keySet(); keys = keySet.iterator(); while (keys.hasNext()) { String storyKey = keys.next(); ArrayList<String> eventIds = storyMap.get(storyKey); for (int i = 0; i < eventIds.size(); i++) { String eventId = eventIds.get(i); // System.out.println("eventId = " + eventId+":"+storyKey); eventToStoryMap.put(eventId, storyKey); } } } public void makeGroup (ArrayList<String> coveredEvents, ArrayList<String> group, String eventId) { if (eventPlotLinksMap.containsKey(eventId)) { ArrayList<PlotLink> plotLinks = eventPlotLinksMap.get(eventId); for (int j = 0; j < plotLinks.size(); j++) { PlotLink plotLink = plotLinks.get(j); String otherEventId = ""; if (!plotLink.getSource().equals(eventId)) { otherEventId = plotLink.getSource(); } else { otherEventId = plotLink.getTarget(); } if (!group.contains(otherEventId)) { group.add(otherEventId); coveredEvents.add(otherEventId); makeGroup(coveredEvents, group,otherEventId); } } } if (eventTimeLinksMap.containsKey(eventId)) { ArrayList<TimeLink> tlinks = eventTimeLinksMap.get(eventId); for (int i = 0; i < tlinks.size(); i++) { TimeLink timeLink = tlinks.get(i); String otherEventId = ""; if (!timeLink.getSource().equals(eventId)) { otherEventId = timeLink.getSource(); } else { otherEventId = timeLink.getTarget(); } if (!group.contains(otherEventId)) { group.add(otherEventId); coveredEvents.add(otherEventId); makeGroup(coveredEvents, group,otherEventId); } } } if (eventLocationLinksMap.containsKey(eventId)) { ArrayList<LocationLink> lLinks = eventLocationLinksMap.get(eventId); for (int i = 0; i < lLinks.size(); i++) { LocationLink locationLink = lLinks.get(i); String otherEventId = ""; if (!locationLink.getSource().equals(eventId)) { otherEventId = locationLink.getSource(); } else { otherEventId = locationLink.getTarget(); } if (!group.contains(otherEventId)) { group.add(otherEventId); coveredEvents.add(otherEventId); makeGroup(coveredEvents, group,otherEventId); } } } } public void makeGroupsOrg () { *//* We determine the climax from the Plot links - if relType="FALLING_ACTION" then source is climax event - if relType="PRECONDITION" then target is climax *//* for (int i = 0; i < plotLinks.size(); i++) { PlotLink plotLink = plotLinks.get(i); if (plotLink.getRelType().equalsIgnoreCase("falling_action")) { String climaxEvent = plotLink.getSource(); if (storyMap.containsKey(climaxEvent)) { ArrayList<String> storyEvents = storyMap.get(climaxEvent); if (!storyEvents.contains(plotLink.getTarget())) { storyEvents.add(plotLink.getTarget()); storyMap.put(climaxEvent, storyEvents); } } else { ArrayList<String> storyEvents = new ArrayList<String>(); storyEvents.add(plotLink.getTarget()); storyMap.put(climaxEvent, storyEvents); } } else if (plotLink.getRelType().equalsIgnoreCase("precondition")) { /// source/target reversed String climaxEvent = plotLink.getTarget(); if (storyMap.containsKey(climaxEvent)) { ArrayList<String> storyEvents = storyMap.get(climaxEvent); if (!storyEvents.contains(plotLink.getSource())) { storyEvents.add(plotLink.getSource()); storyMap.put(climaxEvent, storyEvents); } } else { ArrayList<String> storyEvents = new ArrayList<String>(); storyEvents.add(plotLink.getSource()); storyMap.put(climaxEvent, storyEvents); } } } *//* Now we have story entries based on the climax event, we see if we can attach more through the tlinks *//* for (int i = 0; i < timeLinks.size(); i++) { TimeLink timeLink = timeLinks.get(i); if (!timeLink.getRelType().equalsIgnoreCase("includes")) { //// any other relation than "includes"; check if target or source is a climaxEvent //// if so add the other identifier String climaxEvent = timeLink.getTarget(); if (storyMap.containsKey(climaxEvent)) { ArrayList<String> storyEvents = storyMap.get(climaxEvent); if (!storyEvents.contains(timeLink.getSource())) { storyEvents.add(timeLink.getSource()); storyMap.put(climaxEvent, storyEvents); } } else { climaxEvent = timeLink.getSource(); if (storyMap.containsKey(climaxEvent)) { ArrayList<String> storyEvents = storyMap.get(climaxEvent); if (!storyEvents.contains(timeLink.getTarget())) { storyEvents.add(timeLink.getSource()); storyMap.put(climaxEvent, storyEvents); } } } } } *//* Finally if an event occurs at the same location as the climax event we add it as well *//* HashMap<String, ArrayList<String>> locationMap = new HashMap<String, ArrayList<String>>(); for (int i = 0; i < locationLinks.size(); i++) { LocationLink locationLink = locationLinks.get(i); String event = locationLink.getSource(); String location = locationLink.getTarget(); if (locationMap.containsKey(location)) { ArrayList<String> storyEvents = locationMap.get(location); if (!storyEvents.contains(event)) { storyEvents.add(event); locationMap.put(location, storyEvents); } } else { ArrayList<String> storyEvents = new ArrayList<String>(); storyEvents.add(event); locationMap.put(location, storyEvents); } } Set keySet = locationMap.keySet(); Iterator<String> keys = keySet.iterator(); while (keys.hasNext()) { String key = keys.next(); ArrayList<String> events = locationMap.get(key); for (int i = 0; i < events.size(); i++) { String eventId = events.get(i); if (storyMap.containsKey(eventId)) { ArrayList<String> storyEvents = storyMap.get(eventId); for (int j = 0; j < events.size(); j++) { String coLocatedEventId = events.get(j); if (!coLocatedEventId.equals(eventId) && !storyEvents.contains(coLocatedEventId)) { storyEvents.add(coLocatedEventId); storyMap.put(eventId, storyEvents); } } } } } keySet = storyMap.keySet(); keys = keySet.iterator(); while (keys.hasNext()) { String storyKey = keys.next(); ArrayList<String> eventIds = storyMap.get(storyKey); for (int i = 0; i < eventIds.size(); i++) { String eventId = eventIds.get(i); System.out.println("eventId = " + eventId+":"+storyKey); eventToStoryMap.put(eventId, storyKey); } } }*/ void initAll() { REFERSTO = false; value = ""; target = ""; source = ""; span = ""; fileName =""; TIME = false; singletonId = ""; crossDocId =""; kafWordForm = new KafWordForm(); kafTerm = new KafTerm(); timeTerm = new TimeTerm(); spans = new ArrayList<String>(); termToCorefMap = new HashMap<String, String>(); eventToStoryMap = new HashMap<String, String>(); instanceToStoryMap = new HashMap<String, String>(); eventCorefMap = new HashMap<String, ArrayList<KafTerm>>(); storyMap = new HashMap<String, ArrayList<String>>(); kafWordFormArrayList = new ArrayList<KafWordForm>(); actorTermArrayList = new ArrayList<KafTerm>(); eventTermArrayList = new ArrayList<KafTerm>(); locationTermArrayList = new ArrayList<KafTerm>(); timeTermArrayList = new ArrayList<TimeTerm>(); timeLinks = new ArrayList<TimeLink>(); locationLinks = new ArrayList<LocationLink>(); actorLinks = new ArrayList<ActorLink>(); plotLinks = new ArrayList<PlotLink>(); eventActorLinksMap = new HashMap<String, ArrayList<ActorLink>>(); eventTimeLinksMap = new HashMap<String, ArrayList<TimeLink>>(); eventLocationLinksMap = new HashMap<String, ArrayList<LocationLink>>(); eventPlotLinksMap = new HashMap<String, ArrayList<PlotLink>>(); eventMentionMap = new HashMap<String, JSONObject>(); actorMap = new HashMap<String, KafTerm>(); locationMap = new HashMap<String, KafTerm>(); timeMap = new HashMap<String, TimeTerm>(); } void initPart() { REFERSTO = false; value = ""; target = ""; source = ""; span = ""; fileName =""; TIME = false; singletonId = ""; crossDocId =""; kafWordForm = new KafWordForm(); kafTerm = new KafTerm(); timeTerm = new TimeTerm(); spans = new ArrayList<String>(); timeLinks = new ArrayList<TimeLink>(); locationLinks = new ArrayList<LocationLink>(); actorLinks = new ArrayList<ActorLink>(); plotLinks = new ArrayList<PlotLink>(); eventTermArrayList = new ArrayList<KafTerm>(); actorTermArrayList = new ArrayList<KafTerm>(); locationTermArrayList = new ArrayList<KafTerm>(); timeTermArrayList = new ArrayList<TimeTerm>(); kafWordFormArrayList = new ArrayList<KafWordForm>(); } public void buildMentionMap () throws JSONException { for (int i = 0; i < eventTermArrayList.size(); i++) { KafTerm eventTerm = eventTermArrayList.get(i); ///make snippet and mention //System.out.println("eventTerm.getTid() = " + eventTerm.getTid()); //System.out.println("getPhrase(eventTerm) = " + eventTerm.getTokenString()); String sentenceId = getSentenceId(eventTerm); //System.out.println("sentenceId = " + sentenceId); String sentence = getSentence(sentenceId); //System.out.println("sentence = " + sentence); JSONObject mentionObject = new JSONObject(); mentionObject.append("snippet", sentence); Integer offsetBegin = sentence.indexOf(eventTerm.getTokenString()); Integer offsetEnd = offsetBegin + eventTerm.getTokenString().length(); // mentionObject.put("uri", fileName); // mentionObject.append("char", offsetBegin); // mentionObject.append("char", offsetBegin); mentionObject.append("snippet_char", offsetBegin); mentionObject.append("snippet_char", offsetEnd); //eventObject.append("mentions", mentionObject); PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(new ArrayList<String>(), "", "", "", "", "", fileName, null); perspectiveJsonObject.setDefaultPerspectiveValue(); JSONObject attribution = perspectiveJsonObject.getJSONObject(); JSONObject perspective = new JSONObject(); perspective.put("attribution", attribution); perspective.put("source", "author:" + fileName); mentionObject.append("perspective", perspective); eventMentionMap.put(eventTerm.getTid(), mentionObject); } } public void buildTermMaps () { for (int i = 0; i < actorTermArrayList.size(); i++) { KafTerm term = actorTermArrayList.get(i); actorMap.put(term.getTid(), term); } actorTermArrayList = new ArrayList<KafTerm>(); for (int i = 0; i < locationTermArrayList.size(); i++) { KafTerm term = locationTermArrayList.get(i); locationMap.put(term.getTid(), term); } locationTermArrayList = new ArrayList<KafTerm>(); for (int i = 0; i < timeTermArrayList.size(); i++) { TimeTerm term = timeTermArrayList.get(i); timeMap.put(term.getTid(), term); } timeTermArrayList = new ArrayList<TimeTerm>(); } public void buildLinkMaps () { for (int i = 0; i < actorLinks.size(); i++) { ActorLink actorLink = actorLinks.get(i); String eventId = actorLink.getSource(); if (eventActorLinksMap.containsKey(eventId)) { ArrayList<ActorLink> aLinks = eventActorLinksMap.get(eventId); aLinks.add(actorLink); eventActorLinksMap.put(eventId, aLinks); } else { ArrayList<ActorLink> aLinks = new ArrayList<ActorLink>(); aLinks.add(actorLink); eventActorLinksMap.put(eventId, aLinks); } //System.out.println("eventActorLinksMap = " + eventActorLinksMap.size()); } for (int i = 0; i < locationLinks.size(); i++) { LocationLink locationLink = locationLinks.get(i); String eventId = locationLink.getSource(); if (eventLocationLinksMap.containsKey(eventId)) { ArrayList<LocationLink> locLinks = eventLocationLinksMap.get(eventId); locLinks.add(locationLink); eventLocationLinksMap.put(eventId, locLinks); } else { ArrayList<LocationLink> locLinks = new ArrayList<LocationLink>(); locLinks.add(locationLink); eventLocationLinksMap.put(eventId, locLinks); } } for (int i = 0; i < timeLinks.size(); i++) { TimeLink timeLink = timeLinks.get(i); String eventId = timeLink.getSource(); if (eventTimeLinksMap.containsKey(eventId)) { ArrayList<TimeLink> tLinks = eventTimeLinksMap.get(eventId); tLinks.add(timeLink); eventTimeLinksMap.put(eventId, tLinks); } else { ArrayList<TimeLink> tLinks = new ArrayList<TimeLink>(); tLinks.add(timeLink); eventTimeLinksMap.put(eventId, tLinks); } } for (int i = 0; i < plotLinks.size(); i++) { PlotLink plotLink = plotLinks.get(i); String eventId = plotLink.getSource(); if (eventPlotLinksMap.containsKey(eventId)) { ArrayList<PlotLink> tLinks = eventPlotLinksMap.get(eventId); tLinks.add(plotLink); eventPlotLinksMap.put(eventId, tLinks); } else { ArrayList<PlotLink> tLinks = new ArrayList<PlotLink>(); tLinks.add(plotLink); eventPlotLinksMap.put(eventId, tLinks); } eventId = plotLink.getTarget(); } } public void getPhrases () { for (int i = 0; i < eventTermArrayList.size(); i++) { KafTerm term = eventTermArrayList.get(i); setPhrase(term); } for (int i = 0; i < actorTermArrayList.size(); i++) { KafTerm term = actorTermArrayList.get(i); setPhrase(term); } for (int i = 0; i < locationTermArrayList.size(); i++) { KafTerm term = locationTermArrayList.get(i); setPhrase(term); } } public void parseFile(String filePath) { initPart(); fileName = new File(filePath).getName(); initSingletonId(filePath); String myerror = ""; try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); InputSource inp = new InputSource (new FileReader(filePath)); parser.parse(inp, this); /* System.out.println("eventTermArrayList.size(); = " + eventTermArrayList.size()); System.out.println("timeLinks = " + timeLinks.size()); System.out.println("locationLinks = " + locationLinks.size()); System.out.println("plotLinks = " + plotLinks.size()); */ } catch (SAXParseException err) { myerror = "\n** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId(); myerror += "\n" + err.getMessage(); System.out.println("myerror = " + myerror); } catch (SAXException e) { Exception x = e; if (e.getException() != null) x = e.getException(); myerror += "\nSAXException --" + x.getMessage(); System.out.println("myerror = " + myerror); } catch (Exception eee) { eee.printStackTrace(); myerror += "\nException --" + eee.getMessage(); System.out.println("myerror = " + myerror); } //System.out.println("myerror = " + myerror); }//--c public void initSingletonId (String filePath) { singletonId = getIntFromFileName(filePath); } public String getIntFromFileName (String filePath) { String intString = ""; String dig = "1234567890"; File file = new File (filePath); String name = file.getName(); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (dig.indexOf(c)>-1) { intString+=c; } } if (intString.length() < 4) { for (int i = intString.length(); i < 4; i++) { intString +="0"; } } if (name.indexOf("plus")>-1) { intString += "99"; } else { intString += "88"; } // System.out.println("intString = " + intString); return intString; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("token")) { kafWordForm = new KafWordForm(); kafWordForm.setWid(fileName+"_"+attributes.getValue("t_id")); Integer sentenceInt = Integer.parseInt(attributes.getValue("sentence")); /// HACK TO MAKE SENTENCE ID EQUAL TO SENTENCE ID OF WIKINEWS NAF GENERATED BY FBK sentenceInt++; kafWordForm.setSent(sentenceInt.toString()); } else if (qName.equalsIgnoreCase("CROSS_DOC_COREF") || qName.equalsIgnoreCase("INTRA_DOC_COREF")) { REFERSTO = true; if (qName.equalsIgnoreCase("CROSS_DOC_COREF")) { crossDocId = fixCrossDocId(attributes.getValue("note")); } else if (qName.equalsIgnoreCase("INTRA_DOC_COREF")) { crossDocId = singletonId+fixCrossDocId(attributes.getValue("r_id")); } } else if (qName.equalsIgnoreCase("ACTION_OCCURRENCE") || qName.equalsIgnoreCase("ACTION_CAUSATIVE") || qName.equalsIgnoreCase("ACTION_REPORTING") || qName.equalsIgnoreCase("ACTION_STATE") || qName.equalsIgnoreCase("HUMAN_PART_ORG") || qName.equalsIgnoreCase("HUMAN_PART_PER") || qName.equalsIgnoreCase("LOC_GEO") || qName.equalsIgnoreCase("LOC_FAC") ) { kafTerm = new KafTerm(); kafTerm.setType(qName); kafTerm.setTid(fileName+"_"+attributes.getValue("m_id")); TIME = false; } else if (qName.equalsIgnoreCase("TIME_DATE")) { timeTerm = new TimeTerm(); timeTerm.setType(qName); timeTerm.setTid(fileName+"_"+attributes.getValue("m_id")); timeTerm.setDct(attributes.getValue("DCT").equalsIgnoreCase("true")); timeTerm.setValue(attributes.getValue("value")); timeTerm.setAnchorTimeId(attributes.getValue("anchorTimeID")); TIME = true; } else if (qName.equalsIgnoreCase("token_anchor")) { span = fileName+"_"+attributes.getValue("t_id"); if (!TIME) { kafTerm.addSpans(span); } else { timeTerm.addSpans(span); } } else if (qName.equalsIgnoreCase("source")) { source = fileName+"_"+attributes.getValue("m_id"); //// sources are mentions that match with the same target. The same target can occur in different refers to mappings if (REFERSTO) { /// sources and targets can also occur for other relations than refersto String termId = fileName+"_"+attributes.getValue("m_id"); if (!crossDocId.isEmpty()) { termToCorefMap.put(termId, crossDocId); } } } else if (qName.equalsIgnoreCase("target")) { target = fileName+"_"+attributes.getValue("m_id"); } else if (qName.equalsIgnoreCase("tlink")) { relType =attributes.getValue("relType"); } else if (qName.equalsIgnoreCase("plot_link")) { relType = attributes.getValue("relType"); causes = attributes.getValue("causes"); causedBy = attributes.getValue("causedBy"); signal = attributes.getValue("signal"); contextualModality = attributes.getValue("contextualModality"); } value = ""; }//--startElement public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("token")) { kafWordForm.setWf(value.trim()); kafWordFormArrayList.add(kafWordForm); kafWordForm = new KafWordForm(); } else if (qName.equalsIgnoreCase("ACTION_OCCURRENCE") || qName.equalsIgnoreCase("ACTION_STATE") ) { eventTermArrayList.add(kafTerm); kafTerm = new KafTerm(); } else if (qName.equalsIgnoreCase("HUMAN_PART_ORG") || qName.equalsIgnoreCase("HUMAN_PART_PER") ) { actorTermArrayList.add(kafTerm); kafTerm = new KafTerm(); } else if (qName.equalsIgnoreCase("LOC_GEO") || qName.equalsIgnoreCase("LOC_FAC") ) { locationTermArrayList.add(kafTerm); kafTerm = new KafTerm(); } else if (qName.equalsIgnoreCase("ACTION_CAUSATIVE") || qName.equalsIgnoreCase("ACTION_REPORTING") ) { locationTermArrayList.add(kafTerm); kafTerm = new KafTerm(); } else if (qName.equalsIgnoreCase("TIME_DATE")) { timeTermArrayList.add(timeTerm); timeTerm = new TimeTerm(); TIME = false; } else if (qName.equalsIgnoreCase("LOCATION_LINK")) { LocationLink locationLink = new LocationLink(); locationLink.setSource(source); locationLink.setTarget(target); locationLinks.add(locationLink); source = ""; target = ""; } else if (qName.equalsIgnoreCase("TLINK")) { TimeLink timeLink = new TimeLink(); //// we need to switch between source and targets for includes links due to way it is annotated if (relType!=null && relType.equalsIgnoreCase("includes")) { timeLink.setSource(target); timeLink.setTarget(source); } else { timeLink.setSource(source); timeLink.setTarget(target); } timeLink.setRelType(relType); // System.out.println("timeLink.getTarget() = " + timeLink.getTarget()); // System.out.println("relType = " + relType); relType = ""; source = ""; target = ""; timeLinks.add(timeLink); } else if (qName.equalsIgnoreCase("PLOT_LINK")) { PlotLink plotLink = new PlotLink(); plotLink.setSource(source); plotLink.setTarget(target); plotLink.setRelType(relType); plotLink.setCaused_by(causedBy); plotLink.setCauses(causes); plotLink.setSignal(signal); relType = ""; source = ""; target = ""; plotLinks.add(plotLink); } else if (qName.equalsIgnoreCase("CROSS_DOC_COREF") || qName.equalsIgnoreCase("INTRA_DOC_COREF")) { REFERSTO = false; source = ""; target = ""; } } public void characters(char ch[], int start, int length) throws SAXException { value += new String(ch, start, length); // System.out.println("tagValue:"+value); } String fixCrossDocId (String id) { final String charString = "abcdefghijklmnopqrstuvwxyz"; String str = ""; for (int i = 0; i < id.length(); i++) { char c = id.toLowerCase().charAt(i); int idx = charString.indexOf(c); if (idx>-1) { str += idx+1; } else { str += c; } } //System.out.println("str = " + str); return str; } public void buildEventCorefMap () { for (int i = 0; i < eventTermArrayList.size(); i++) { KafTerm eventTerm = eventTermArrayList.get(i); String corefId = eventTerm.getTid(); /// this is for singletons if (termToCorefMap.containsKey(eventTerm.getTid())) { corefId = termToCorefMap.get(eventTerm.getTid()); } else { termToCorefMap.put(corefId, corefId); //// singleton } if (eventCorefMap.containsKey(corefId)) { ArrayList<KafTerm> events = eventCorefMap.get(corefId); events.add(eventTerm); eventCorefMap.put(corefId,events); } else { ArrayList<KafTerm> events = new ArrayList<KafTerm>(); events.add(eventTerm); eventCorefMap.put(corefId,events); } } } public void getActorLinks () { for (int i = 0; i < eventTermArrayList.size(); i++) { KafTerm eventTerm = eventTermArrayList.get(i); String sentence1 = getSentenceId(eventTerm); for (int j = 0; j < actorTermArrayList.size(); j++) { KafTerm actorTerm = actorTermArrayList.get(j); String sentence2 = getSentenceId(actorTerm); if (sentence1.equals(sentence2)) { ActorLink actorLink = new ActorLink(); actorLink.setSource(eventTerm.getTid()); actorLink.setTarget(actorTerm.getTid()); actorLinks.add(actorLink); } } } } public String getSentenceId (KafTerm kafTerm) { String sentence = ""; for (int j = 0; j < kafTerm.getSpans().size(); j++) { String s = kafTerm.getSpans().get(j); for (int k = 0; k < kafWordFormArrayList.size(); k++) { KafWordForm wordForm = kafWordFormArrayList.get(k); if (wordForm.getWid().equals(s)) { sentence = wordForm.getSent(); break; } } } return sentence; } /* public String getPhrase (KafTerm kafTerm) { String phrase = ""; for (int j = 0; j < kafTerm.getSpans().size(); j++) { String s = kafTerm.getSpans().get(j); for (int k = 0; k < kafWordFormArrayList.size(); k++) { KafWordForm wordForm = kafWordFormArrayList.get(k); if (wordForm.getWid().equals(s)) { phrase += " "+wordForm.getWf(); } } } //System.out.println("phrase = " + phrase); phrase = phrase.trim(); return phrase; }*/ public void setPhrase (KafTerm kafTerm) { String phrase = ""; for (int j = 0; j < kafTerm.getSpans().size(); j++) { String s = kafTerm.getSpans().get(j); for (int k = 0; k < kafWordFormArrayList.size(); k++) { KafWordForm wordForm = kafWordFormArrayList.get(k); if (wordForm.getWid().equals(s)) { phrase += " "+wordForm.getWf(); } } } kafTerm.setTokenString(phrase.trim()); } public String getSentence (String sentenceId) { String sentence = ""; for (int k = 0; k < kafWordFormArrayList.size(); k++) { KafWordForm wordForm = kafWordFormArrayList.get(k); if (wordForm.getSent().equals(sentenceId)) { sentence += " "+wordForm.getWf(); } } return sentence.trim(); } public ArrayList<JSONObject> getJsonObjectsFromCorefsets () throws JSONException { ArrayList<JSONObject> events = new ArrayList<JSONObject>(); Set keySet = eventCorefMap.keySet(); Iterator<String> keys = keySet.iterator(); while (keys.hasNext()) { String eventCorefKey = keys.next(); // System.out.println("eventCorefKey = " + eventCorefKey); JSONObject eventObject = new JSONObject(); JSONObject actors = new JSONObject(); ArrayList<String> actorStrings = new ArrayList<String>(); ArrayList<String> phraseStrings = new ArrayList<String>(); ArrayList<String> timeStrings = new ArrayList<String>(); ArrayList<KafTerm> eventTerms = eventCorefMap.get(eventCorefKey); Map<String, Integer> storyCount = new HashMap<String, Integer>(); for (int i = 0; i < eventTerms.size(); i++) { KafTerm eventTerm = eventTerms.get(i); String eventPhrase = eventTerm.getTokenString().replaceAll(" ", "_"); if (!eventPhrase.isEmpty()) { if (eventMentionMap.containsKey(eventTerm.getTid())) { JSONObject mention = eventMentionMap.get(eventTerm.getTid()); eventObject.append("mentions", mention); } if (!phraseStrings.contains(eventPhrase)) { eventObject.append("labels", eventPhrase); eventObject.append("prefLabel", eventPhrase); phraseStrings.add(eventPhrase); } if (eventActorLinksMap.containsKey(eventTerm.getTid())) { ArrayList<ActorLink> actorLinks = eventActorLinksMap.get(eventTerm.getTid()); for (int j = 0; j < actorLinks.size(); j++) { ActorLink actorLink = actorLinks.get(j); String targetId = actorLink.getTarget(); if (actorMap.containsKey(targetId)) { KafTerm actor = actorMap.get(targetId); String actorString = "act:" + actor.getTokenString().replaceAll(" ", "_"); if (!actorString.isEmpty()) { if (!actorStrings.contains(actorString)) { // System.out.println("actorString = " + actorString); actors.append("actor:", actorString); actorStrings.add(actorString); } } } else { // System.out.println("Could not find targetId = " + targetId); } } } if (eventLocationLinksMap.containsKey(eventTerm.getTid())) { ArrayList<LocationLink> locationLinks = eventLocationLinksMap.get(eventTerm.getTid()); for (int j = 0; j < locationLinks.size(); j++) { LocationLink locationLink = locationLinks.get(j); String targetId = locationLink.getTarget(); if (locationMap.containsKey(targetId)) { KafTerm location = locationMap.get(targetId); String locationString = "loc:" + location.getTokenString().replaceAll(" ", "_"); if (!locationString.isEmpty()) { if (!actorStrings.contains(locationString)) { actors.append("actor:", locationString); actorStrings.add(locationString); } } } } } if (eventTimeLinksMap.containsKey(eventTerm.getTid())) { ArrayList<TimeLink> timeLinks = eventTimeLinksMap.get(eventTerm.getTid()); String timeString = ""; for (int j = 0; j < timeLinks.size(); j++) { TimeLink timeLink = timeLinks.get(j); if (timeLink.getRelType() != null && timeLink.getRelType().equalsIgnoreCase("INCLUDES")) { String targetId = timeLink.getTarget(); if (timeMap.containsKey(targetId)) { TimeTerm time = timeMap.get(targetId); timeString = time.getValue().replaceAll("-", ""); if (timeString.length() == 4) timeString += "0101"; if (timeString.length() == 6) timeString += "01"; if (!timeString.isEmpty() && !timeStrings.contains(timeString)) { timeStrings.add(timeString); } } } } if (timeStrings.isEmpty()) { for (int j = 0; j < timeLinks.size(); j++) { TimeLink timeLink = timeLinks.get(j); String targetId = timeLink.getTarget(); if (timeMap.containsKey(targetId)) { TimeTerm time = timeMap.get(targetId); timeString = time.getValue().replaceAll("-", ""); if (timeString.length() == 4) timeString += "0101"; if (timeString.length() == 6) timeString += "01"; if (!timeString.isEmpty() && !timeStrings.contains(timeString)) { timeStrings.add(timeString); } } } } } } } /* System.out.println("phraseStrings = " + phraseStrings.toString()); System.out.println("actorStrings = " + actorStrings.toString()); System.out.println("timeStrings = " + timeStrings.toString()); */ if (actors.length() == 0) { actors.append("actor:", "noactors:"); } else { eventObject.put("actors", actors); String timeString = ""; Collections.sort(timeStrings); if (timeStrings.size() > 0) timeString = timeStrings.get(timeStrings.size() - 1); if (timeString.isEmpty()) { ////// timeString = "20160101"; //System.out.println("No timeString, timeStrings = " + timeStrings.toString()); } else { String group = instanceToStoryMap.get(eventCorefKey); int groupScore = getClimaxScore(group); int score = getClimaxScore(eventCorefKey); eventObject.put("time", timeString); eventObject.put("event", eventCorefKey); eventObject.put("group", groupScore + ":[" + group + "]"); eventObject.put("groupName", "[" + group + "]"); eventObject.put("groupScore", groupScore); eventObject.put("climax", score); events.add(eventObject); } } } JsonStoryUtil.minimalizeActors(events); return events; } /* */ static void writeJsonObjectArrayWithStructuredData (String pathToFolder, String project, ArrayList<JSONObject> objects, String structuredName, ArrayList<JSONObject> structured) { try { try { JSONObject timeLineObject = JsonEvent.createTimeLineProperty(new File(pathToFolder).getName(), project); timeLineObject.append("event_cnt", objects.size()); for (int j = 0; j < structured.size(); j++) { JSONObject jsonObject = structured.get(j); timeLineObject.append(structuredName, jsonObject); } for (int j = 0; j < objects.size(); j++) { JSONObject jsonObject = objects.get(j); timeLineObject.append("events", jsonObject); } File folder = new File(pathToFolder); String outputFile = folder.getAbsolutePath() + "/" + "contextual.timeline.json"; OutputStream jsonOut = new FileOutputStream(outputFile); String str = "{ \"timeline\":\n"; jsonOut.write(str.getBytes()); jsonOut.write(timeLineObject.toString(0).getBytes()); str ="}\n"; jsonOut.write(str.getBytes()); //// OR simply // jsonOut.write(timeLineObject.toString().getBytes()); jsonOut.close(); } catch (JSONException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } static void writeJsonObjectArray (String pathToFolder, String project, ArrayList<JSONObject> objects) { try { try { JSONObject timeLineObject = JsonEvent.createTimeLineProperty(new File(pathToFolder).getName(), project); timeLineObject.append("event_cnt", objects.size()); for (int j = 0; j < objects.size(); j++) { JSONObject jsonObject = objects.get(j); timeLineObject.append("events", jsonObject); } File folder = new File(pathToFolder); String outputFile = folder.getAbsolutePath() + "/" + "contextual.timeline.json"; OutputStream jsonOut = new FileOutputStream(outputFile); String str = "{ \"timeline\":\n"; jsonOut.write(str.getBytes()); jsonOut.write(timeLineObject.toString(0).getBytes()); str ="}\n"; jsonOut.write(str.getBytes()); //// OR simply // jsonOut.write(timeLineObject.toString().getBytes()); jsonOut.close(); } catch (JSONException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } static public void main (String[] args) { String demo = "/Users/piek/Desktop/WorkshopsConferences/StorylineWorkshop/UncertaintyVisualizationGold/app/data"; String folder = ""; String pathToCatFile = ""; String fileExtension = ""; //pathToCatFile = "/Users/piek/Desktop/StorylineWorkshop/ECB-manual/ECBplus_Topic37CAT/37_9ecbplus.xml"; folder = "/Users/piek/Desktop/WorkshopsConferences/StorylineWorkshop/ECB-manual/ECBStar-mergeT37"; fileExtension = ".xml"; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equalsIgnoreCase("--cat-file") && args.length > (i + 1)) { pathToCatFile = args[i + 1]; } else if (arg.equalsIgnoreCase("--folder") && args.length > (i + 1)) { folder = args[i + 1]; } else if (arg.equalsIgnoreCase("--file-extension") && args.length > (i + 1)) { fileExtension = args[i + 1]; } } System.out.println("fileExtension = " + fileExtension); System.out.println("folder = " + folder); JsonFromCat jsonFromCat = new JsonFromCat(); if (!pathToCatFile.isEmpty()) { File catFile = new File (pathToCatFile); folder = catFile.getParent(); jsonFromCat.parseFile(pathToCatFile); jsonFromCat.getPhrases(); jsonFromCat.getActorLinks(); jsonFromCat.buildEventCorefMap(); jsonFromCat.buildLinkMaps(); jsonFromCat.buildTermMaps(); try { jsonFromCat.buildMentionMap(); } catch (JSONException e) { e.printStackTrace(); } jsonFromCat.makeGroupsForInstance(); System.out.println("jsonFromCat.eventTermArrayList = " + jsonFromCat.eventTermArrayList.size()); System.out.println("jsonFromCat.eventCorefMap = " + jsonFromCat.eventCorefMap.size()); ArrayList<JSONObject> events = null; try { events = jsonFromCat.getJsonObjectsFromCorefsets(); } catch (JSONException e) { e.printStackTrace(); } jsonFromCat.writeJsonObjectArray(demo, "ecb*", events); } else if (!folder.isEmpty()) { ArrayList<File> files = Util.makeFlatFileList(new File(folder), fileExtension); ArrayList<JSONObject> events = new ArrayList<JSONObject>(); for (int i = 0; i < files.size(); i++) { File file = files.get(i); //System.out.println("file.getName() = " + file.getName()); jsonFromCat.parseFile(file.getAbsolutePath()); jsonFromCat.getPhrases(); jsonFromCat.getActorLinks(); jsonFromCat.buildEventCorefMap(); jsonFromCat.buildLinkMaps(); jsonFromCat.buildTermMaps(); try { jsonFromCat.buildMentionMap(); } catch (JSONException e) { e.printStackTrace(); } //System.out.println("jsonFromCat plotlinks = " + jsonFromCat.plotLinks.size()); } try { jsonFromCat.makeGroupsForInstance(); events = jsonFromCat.getJsonObjectsFromCorefsets(); } catch (JSONException e) { e.printStackTrace(); } System.out.println("jsonFromCat.eventCorefMap = " + jsonFromCat.eventCorefMap.size()); System.out.println("jsonFromCat.instanceToStoryMap.size() = " + jsonFromCat.instanceToStoryMap.size()); jsonFromCat.writeJsonObjectArray(demo, "ecb*", events); } System.out.println("DONE."); } } /* { "timeline": { "actor_cnt": [686], "event_cnt": [5238], "events": [ { "actors": {"actor:": [ "dbp:European_Union", "dbp:United_Kingdom", "co:eurozone", "co:financial", "dbp:London" ]}, "climax": 77, "event": "ev85", "group": "100:[European Investment Bank]", "groupName": "[European Investment Bank]", "groupScore": "100", "instance": "http://www.ft.com/thing/e5aeef74-8180-11e5-8095-ed1a37d1e096#ev85", "labels": ["aim"], "mentions": [{ "snippet": [" of the currency [area] in which they reside\u201d.\nThat clause is specifically aimed at protecting British financial groups from protectionist measures by the eurozone,"], "snippet_char": [ 75, 80 ], "uri": "http://www.ft.com/thing/e5aeef74-8180-11e5-8095-ed1a37d1e096" }], "prefLabel": ["aim"], "time": "20151102" } ], polls:{} "headline": "ECBplus_Topic37CAT", "text": "ecb*", "type": "default" }} */
apache-2.0
kagel/elasticsearch
src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java
37918
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.hamcrest; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.Version; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.action.admin.cluster.node.info.PluginInfo; import org.elasticsearch.action.admin.cluster.node.info.PluginsInfo; import org.elasticsearch.action.admin.indices.alias.exists.AliasesExistResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequestBuilder; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.count.CountResponse; import org.elasticsearch.action.exists.ExistsResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.percolate.PercolateResponse; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.action.support.broadcast.BroadcastOperationResponse; import org.elasticsearch.action.support.master.AcknowledgedRequestBuilder; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.suggest.Suggest; import org.elasticsearch.test.engine.MockInternalEngine; import org.elasticsearch.test.store.MockDirectoryHelper; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Assert; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.util.*; import java.util.concurrent.TimeUnit; import static com.google.common.base.Predicates.isNull; import static org.elasticsearch.test.ElasticsearchTestCase.*; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /** * */ public class ElasticsearchAssertions { public static void assertAcked(AcknowledgedRequestBuilder<?, ?, ?, ?> builder) { assertAcked(builder.get()); } public static void assertNoTimeout(ClusterHealthRequestBuilder requestBuilder) { assertNoTimeout(requestBuilder.get()); } public static void assertNoTimeout(ClusterHealthResponse response) { assertThat("ClusterHealthResponse has timed out - returned: [" + response + "]", response.isTimedOut(), is(false)); } public static void assertAcked(AcknowledgedResponse response) { assertThat(response.getClass().getSimpleName() + " failed - not acked", response.isAcknowledged(), equalTo(true)); assertVersionSerializable(response); } public static void assertAcked(DeleteIndexRequestBuilder builder) { assertAcked(builder.get()); } public static void assertAcked(DeleteIndexResponse response) { assertThat("Delete Index failed - not acked", response.isAcknowledged(), equalTo(true)); assertVersionSerializable(response); } public static String formatShardStatus(BroadcastOperationResponse response) { String msg = " Total shards: " + response.getTotalShards() + " Successful shards: " + response.getSuccessfulShards() + " & " + response.getFailedShards() + " shard failures:"; for (ShardOperationFailedException failure : response.getShardFailures()) { msg += "\n " + failure.toString(); } return msg; } public static String formatShardStatus(SearchResponse response) { String msg = " Total shards: " + response.getTotalShards() + " Successful shards: " + response.getSuccessfulShards() + " & " + response.getFailedShards() + " shard failures:"; for (ShardSearchFailure failure : response.getShardFailures()) { msg += "\n " + failure.toString(); } return msg; } /* * assertions */ public static void assertHitCount(SearchResponse searchResponse, long expectedHitCount) { if (searchResponse.getHits().totalHits() != expectedHitCount) { fail("Hit count is " + searchResponse.getHits().totalHits() + " but " + expectedHitCount + " was expected. " + formatShardStatus(searchResponse)); } assertVersionSerializable(searchResponse); } public static void assertSearchHits(SearchResponse searchResponse, String... ids) { String shardStatus = formatShardStatus(searchResponse); assertThat("Expected different hit count. " + shardStatus, searchResponse.getHits().hits().length, equalTo(ids.length)); Set<String> idsSet = new HashSet<>(Arrays.asList(ids)); for (SearchHit hit : searchResponse.getHits()) { assertThat("Expected id: " + hit.getId() + " in the result but wasn't." + shardStatus, idsSet.remove(hit.getId()), equalTo(true)); } assertThat("Expected ids: " + Arrays.toString(idsSet.toArray(new String[idsSet.size()])) + " in the result - result size differs." + shardStatus, idsSet.size(), equalTo(0)); assertVersionSerializable(searchResponse); } public static void assertSortValues(SearchResponse searchResponse, Object[]... sortValues) { assertSearchResponse(searchResponse); SearchHit[] hits = searchResponse.getHits().getHits(); assertEquals(sortValues.length, hits.length); for (int i = 0; i < sortValues.length; ++i) { final Object[] hitsSortValues = hits[i].getSortValues(); assertArrayEquals("Offset " + Integer.toString(i) + ", id " + hits[i].getId(), sortValues[i], hitsSortValues); } assertVersionSerializable(searchResponse); } public static void assertOrderedSearchHits(SearchResponse searchResponse, String... ids) { String shardStatus = formatShardStatus(searchResponse); assertThat("Expected different hit count. " + shardStatus, searchResponse.getHits().hits().length, equalTo(ids.length)); for (int i = 0; i < ids.length; i++) { SearchHit hit = searchResponse.getHits().hits()[i]; assertThat("Expected id: " + ids[i] + " at position " + i + " but wasn't." + shardStatus, hit.getId(), equalTo(ids[i])); } assertVersionSerializable(searchResponse); } public static void assertHitCount(CountResponse countResponse, long expectedHitCount) { if (countResponse.getCount() != expectedHitCount) { fail("Count is " + countResponse.getCount() + " but " + expectedHitCount + " was expected. " + formatShardStatus(countResponse)); } assertVersionSerializable(countResponse); } public static void assertExists(ExistsResponse existsResponse, boolean expected) { if (existsResponse.exists() != expected) { fail("Exist is " + existsResponse.exists() + " but " + expected + " was expected " + formatShardStatus(existsResponse)); } assertVersionSerializable(existsResponse); } public static void assertMatchCount(PercolateResponse percolateResponse, long expectedHitCount) { if (percolateResponse.getCount() != expectedHitCount) { fail("Count is " + percolateResponse.getCount() + " but " + expectedHitCount + " was expected. " + formatShardStatus(percolateResponse)); } assertVersionSerializable(percolateResponse); } public static void assertExists(GetResponse response) { String message = String.format(Locale.ROOT, "Expected %s/%s/%s to exist, but does not", response.getIndex(), response.getType(), response.getId()); assertThat(message, response.isExists(), is(true)); } public static void assertFirstHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 1, matcher); } public static void assertSecondHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 2, matcher); } public static void assertThirdHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 3, matcher); } public static void assertFourthHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 4, matcher); } public static void assertFifthHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 5, matcher); } public static void assertSearchHit(SearchResponse searchResponse, int number, Matcher<SearchHit> matcher) { assertThat(number, greaterThan(0)); assertThat("SearchHit number must be greater than 0", number, greaterThan(0)); assertThat(searchResponse.getHits().totalHits(), greaterThanOrEqualTo((long) number)); assertSearchHit(searchResponse.getHits().getAt(number - 1), matcher); assertVersionSerializable(searchResponse); } public static void assertNoFailures(SearchResponse searchResponse) { assertThat("Unexpected ShardFailures: " + Arrays.toString(searchResponse.getShardFailures()), searchResponse.getShardFailures().length, equalTo(0)); assertVersionSerializable(searchResponse); } public static void assertFailures(SearchResponse searchResponse) { assertThat("Expected at least one shard failure, got none", searchResponse.getShardFailures().length, greaterThan(0)); assertVersionSerializable(searchResponse); } public static void assertNoFailures(BulkResponse response) { assertThat("Unexpected ShardFailures: " + response.buildFailureMessage(), response.hasFailures(), is(false)); assertVersionSerializable(response); } public static void assertFailures(SearchRequestBuilder searchRequestBuilder, RestStatus restStatus, Matcher<String> reasonMatcher) { //when the number for shards is randomized and we expect failures //we can either run into partial or total failures depending on the current number of shards try { SearchResponse searchResponse = searchRequestBuilder.get(); assertThat("Expected shard failures, got none", searchResponse.getShardFailures().length, greaterThan(0)); for (ShardSearchFailure shardSearchFailure : searchResponse.getShardFailures()) { assertThat(shardSearchFailure.status(), equalTo(restStatus)); assertThat(shardSearchFailure.reason(), reasonMatcher); } assertVersionSerializable(searchResponse); } catch(SearchPhaseExecutionException e) { assertThat(e.status(), equalTo(restStatus)); assertThat(e.getMessage(), reasonMatcher); for (ShardSearchFailure shardSearchFailure : e.shardFailures()) { assertThat(shardSearchFailure.status(), equalTo(restStatus)); assertThat(shardSearchFailure.reason(), reasonMatcher); } } catch(Exception e) { fail("SearchPhaseExecutionException expected but got " + e.getClass()); } } public static void assertNoFailures(BroadcastOperationResponse response) { assertThat("Unexpected ShardFailures: " + Arrays.toString(response.getShardFailures()), response.getFailedShards(), equalTo(0)); assertVersionSerializable(response); } public static void assertAllSuccessful(BroadcastOperationResponse response) { assertNoFailures(response); assertThat("Expected all shards successful but got successful [" + response.getSuccessfulShards() + "] total [" + response.getTotalShards() + "]", response.getTotalShards(), equalTo(response.getSuccessfulShards())); assertVersionSerializable(response); } public static void assertAllSuccessful(SearchResponse response) { assertNoFailures(response); assertThat("Expected all shards successful but got successful [" + response.getSuccessfulShards() + "] total [" + response.getTotalShards() + "]", response.getTotalShards(), equalTo(response.getSuccessfulShards())); assertVersionSerializable(response); } public static void assertSearchHit(SearchHit searchHit, Matcher<SearchHit> matcher) { assertThat(searchHit, matcher); assertVersionSerializable(searchHit); } public static void assertHighlight(SearchResponse resp, int hit, String field, int fragment, Matcher<String> matcher) { assertHighlight(resp, hit, field, fragment, greaterThan(fragment), matcher); } public static void assertHighlight(SearchResponse resp, int hit, String field, int fragment, int totalFragments, Matcher<String> matcher) { assertHighlight(resp, hit, field, fragment, equalTo(totalFragments), matcher); } public static void assertHighlight(SearchHit hit, String field, int fragment, Matcher<String> matcher) { assertHighlight(hit, field, fragment, greaterThan(fragment), matcher); } public static void assertHighlight(SearchHit hit, String field, int fragment, int totalFragments, Matcher<String> matcher) { assertHighlight(hit, field, fragment, equalTo(totalFragments), matcher); } private static void assertHighlight(SearchResponse resp, int hit, String field, int fragment, Matcher<Integer> fragmentsMatcher, Matcher<String> matcher) { assertNoFailures(resp); assertThat("not enough hits", resp.getHits().hits().length, greaterThan(hit)); assertHighlight(resp.getHits().hits()[hit], field, fragment, fragmentsMatcher, matcher); assertVersionSerializable(resp); } private static void assertHighlight(SearchHit hit, String field, int fragment, Matcher<Integer> fragmentsMatcher, Matcher<String> matcher) { assertThat(hit.getHighlightFields(), hasKey(field)); assertThat(hit.getHighlightFields().get(field).fragments().length, fragmentsMatcher); assertThat(hit.highlightFields().get(field).fragments()[fragment].string(), matcher); } public static void assertNotHighlighted(SearchResponse resp, int hit, String field) { assertNoFailures(resp); assertThat("not enough hits", resp.getHits().hits().length, greaterThan(hit)); assertThat(resp.getHits().hits()[hit].getHighlightFields(), not(hasKey(field))); } public static void assertSuggestionSize(Suggest searchSuggest, int entry, int size, String key) { assertThat(searchSuggest, notNullValue()); String msg = "Suggest result: " + searchSuggest.toString(); assertThat(msg, searchSuggest.size(), greaterThanOrEqualTo(1)); assertThat(msg, searchSuggest.getSuggestion(key).getName(), equalTo(key)); assertThat(msg, searchSuggest.getSuggestion(key).getEntries().size(), greaterThanOrEqualTo(entry)); assertThat(msg, searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().size(), equalTo(size)); assertVersionSerializable(searchSuggest); } public static void assertSuggestionPhraseCollateMatchExists(Suggest searchSuggest, String key, int numberOfPhraseExists) { int counter = 0; assertThat(searchSuggest, notNullValue()); String msg = "Suggest result: " + searchSuggest.toString(); assertThat(msg, searchSuggest.size(), greaterThanOrEqualTo(1)); assertThat(msg, searchSuggest.getSuggestion(key).getName(), equalTo(key)); for (Suggest.Suggestion.Entry.Option option : searchSuggest.getSuggestion(key).getEntries().get(0).getOptions()) { if (option.collateMatch()) { counter++; } } assertThat(counter, equalTo(numberOfPhraseExists)); } public static void assertSuggestion(Suggest searchSuggest, int entry, int ord, String key, String text) { assertThat(searchSuggest, notNullValue()); String msg = "Suggest result: " + searchSuggest.toString(); assertThat(msg, searchSuggest.size(), greaterThanOrEqualTo(1)); assertThat(msg, searchSuggest.getSuggestion(key).getName(), equalTo(key)); assertThat(msg, searchSuggest.getSuggestion(key).getEntries().size(), greaterThanOrEqualTo(entry)); assertThat(msg, searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().size(), greaterThan(ord)); assertThat(msg, searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().get(ord).getText().string(), equalTo(text)); assertVersionSerializable(searchSuggest); } /** * Assert suggestion returns exactly the provided text. */ public static void assertSuggestion(Suggest searchSuggest, int entry, String key, String... text) { assertSuggestion(searchSuggest, entry, key, text.length, text); } /** * Assert suggestion returns size suggestions and the first are the provided * text. */ public static void assertSuggestion(Suggest searchSuggest, int entry, String key, int size, String... text) { assertSuggestionSize(searchSuggest, entry, size, key); for (int i = 0; i < text.length; i++) { assertSuggestion(searchSuggest, entry, i, key, text[i]); } } /** * Assert that an index template is missing */ public static void assertIndexTemplateMissing(GetIndexTemplatesResponse templatesResponse, String name) { List<String> templateNames = new ArrayList<>(); for (IndexTemplateMetaData indexTemplateMetaData : templatesResponse.getIndexTemplates()) { templateNames.add(indexTemplateMetaData.name()); } assertThat(templateNames, not(hasItem(name))); } /** * Assert that an index template exists */ public static void assertIndexTemplateExists(GetIndexTemplatesResponse templatesResponse, String name) { List<String> templateNames = new ArrayList<>(); for (IndexTemplateMetaData indexTemplateMetaData : templatesResponse.getIndexTemplates()) { templateNames.add(indexTemplateMetaData.name()); } assertThat(templateNames, hasItem(name)); } /** * Assert that aliases are missing */ public static void assertAliasesMissing(AliasesExistResponse aliasesExistResponse) { assertFalse("Aliases shouldn't exist", aliasesExistResponse.exists()); } /** * Assert that aliases exist */ public static void assertAliasesExist(AliasesExistResponse aliasesExistResponse) { assertTrue("Aliases should exist", aliasesExistResponse.exists()); } /* * matchers */ public static Matcher<SearchHit> hasId(final String id) { return new ElasticsearchMatchers.SearchHitHasIdMatcher(id); } public static Matcher<SearchHit> hasType(final String type) { return new ElasticsearchMatchers.SearchHitHasTypeMatcher(type); } public static Matcher<SearchHit> hasIndex(final String index) { return new ElasticsearchMatchers.SearchHitHasIndexMatcher(index); } public static Matcher<SearchHit> hasScore(final float score) { return new ElasticsearchMatchers.SearchHitHasScoreMatcher(score); } public static <T extends Query> T assertBooleanSubQuery(Query query, Class<T> subqueryType, int i) { assertThat(query, instanceOf(BooleanQuery.class)); BooleanQuery q = (BooleanQuery) query; assertThat(q.getClauses().length, greaterThan(i)); assertThat(q.getClauses()[i].getQuery(), instanceOf(subqueryType)); return (T) q.getClauses()[i].getQuery(); } /** * Run the request from a given builder and check that it throws an exception of the right type */ public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?, ?, ?> builder, Class<E> exceptionClass) { assertThrows(builder.execute(), exceptionClass); } /** * Run the request from a given builder and check that it throws an exception of the right type, with a given {@link org.elasticsearch.rest.RestStatus} */ public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?, ?, ?> builder, Class<E> exceptionClass, RestStatus status) { assertThrows(builder.execute(), exceptionClass, status); } /** * Run the request from a given builder and check that it throws an exception of the right type * * @param extraInfo extra information to add to the failure message */ public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?, ?, ?> builder, Class<E> exceptionClass, String extraInfo) { assertThrows(builder.execute(), exceptionClass, extraInfo); } /** * Run future.actionGet() and check that it throws an exception of the right type */ public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass) { assertThrows(future, exceptionClass, null, null); } /** * Run future.actionGet() and check that it throws an exception of the right type, with a given {@link org.elasticsearch.rest.RestStatus} */ public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass, RestStatus status) { assertThrows(future, exceptionClass, status, null); } /** * Run future.actionGet() and check that it throws an exception of the right type * * @param extraInfo extra information to add to the failure message */ public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass, String extraInfo) { assertThrows(future, exceptionClass, null, extraInfo); } /** * Run future.actionGet() and check that it throws an exception of the right type, optionally checking the exception's rest status * * @param exceptionClass expected exception class * @param status {@link org.elasticsearch.rest.RestStatus} to check for. Can be null to disable the check * @param extraInfo extra information to add to the failure message. Can be null. */ public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass, @Nullable RestStatus status, @Nullable String extraInfo) { boolean fail = false; extraInfo = extraInfo == null || extraInfo.isEmpty() ? "" : extraInfo + ": "; extraInfo += "expected a " + exceptionClass + " exception to be thrown"; if (status != null) { extraInfo += " with status [" + status + "]"; } try { future.actionGet(); fail = true; } catch (ElasticsearchException esException) { assertThat(extraInfo, esException.unwrapCause(), instanceOf(exceptionClass)); if (status != null) { assertThat(extraInfo, ExceptionsHelper.status(esException), equalTo(status)); } } catch (Throwable e) { assertThat(extraInfo, e, instanceOf(exceptionClass)); if (status != null) { assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status)); } } // has to be outside catch clause to get a proper message if (fail) { throw new AssertionError(extraInfo); } } public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?, ?, ?> builder, RestStatus status) { assertThrows(builder.execute(), status); } public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?, ?, ?> builder, RestStatus status, String extraInfo) { assertThrows(builder.execute(), status, extraInfo); } public static <E extends Throwable> void assertThrows(ActionFuture future, RestStatus status) { assertThrows(future, status, null); } public static void assertThrows(ActionFuture future, RestStatus status, String extraInfo) { boolean fail = false; extraInfo = extraInfo == null || extraInfo.isEmpty() ? "" : extraInfo + ": "; extraInfo += "expected a " + status + " status exception to be thrown"; try { future.actionGet(); fail = true; } catch (Throwable e) { assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status)); } // has to be outside catch clause to get a proper message if (fail) { throw new AssertionError(extraInfo); } } private static BytesReference serialize(Version version, Streamable streamable) throws IOException { BytesStreamOutput output = new BytesStreamOutput(); output.setVersion(version); streamable.writeTo(output); output.flush(); return output.bytes(); } public static void assertVersionSerializable(Streamable streamable) { assertTrue(Version.CURRENT.after(getPreviousVersion())); assertVersionSerializable(randomVersion(), streamable); } public static void assertVersionSerializable(Version version, Streamable streamable) { try { Streamable newInstance = tryCreateNewInstance(streamable); if (newInstance == null) { return; // can't create a new instance - we never modify a // streamable that comes in. } if (streamable instanceof ActionRequest) { ((ActionRequest<?>)streamable).validate(); } BytesReference orig = serialize(version, streamable); StreamInput input = new BytesStreamInput(orig); input.setVersion(version); newInstance.readFrom(input); assertThat("Stream should be fully read with version [" + version + "] for streamable [" + streamable + "]", input.available(), equalTo(0)); assertThat("Serialization failed with version [" + version + "] bytes should be equal for streamable [" + streamable + "]", serialize(version, streamable), equalTo(orig)); } catch (Throwable ex) { throw new RuntimeException("failed to check serialization - version [" + version + "] for streamable [" + streamable + "]", ex); } } private static Streamable tryCreateNewInstance(Streamable streamable) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { try { Class<? extends Streamable> clazz = streamable.getClass(); Constructor<? extends Streamable> constructor = clazz.getDeclaredConstructor(); assertThat(constructor, Matchers.notNullValue()); constructor.setAccessible(true); Streamable newInstance = constructor.newInstance(); return newInstance; } catch (Throwable e) { return null; } } /** * Applies basic assertions on the SearchResponse. This method checks if all shards were successful, if * any of the shards threw an exception and if the response is serializeable. */ public static SearchResponse assertSearchResponse(SearchRequestBuilder request) { return assertSearchResponse(request.get()); } /** * Applies basic assertions on the SearchResponse. This method checks if all shards were successful, if * any of the shards threw an exception and if the response is serializeable. */ public static SearchResponse assertSearchResponse(SearchResponse response) { assertNoFailures(response); assertThat("One or more shards were not successful but didn't trigger a failure", response.getSuccessfulShards(), equalTo(response.getTotalShards())); return response; } public static void assertAllSearchersClosed() { /* in some cases we finish a test faster than the freeContext calls make it to the * shards. Let's wait for some time if there are still searchers. If the are really * pending we will fail anyway.*/ try { if (awaitBusy(new Predicate<Object>() { public boolean apply(Object o) { return MockInternalEngine.INFLIGHT_ENGINE_SEARCHERS.isEmpty(); } }, 5, TimeUnit.SECONDS)) { return; } } catch (InterruptedException ex) { if (MockInternalEngine.INFLIGHT_ENGINE_SEARCHERS.isEmpty()) { return; } } try { RuntimeException ex = null; StringBuilder builder = new StringBuilder("Unclosed Searchers instance for shards: ["); for (Map.Entry<MockInternalEngine.AssertingSearcher, RuntimeException> entry : MockInternalEngine.INFLIGHT_ENGINE_SEARCHERS.entrySet()) { ex = entry.getValue(); builder.append(entry.getKey().shardId()).append(","); } builder.append("]"); throw new RuntimeException(builder.toString(), ex); } finally { MockInternalEngine.INFLIGHT_ENGINE_SEARCHERS.clear(); } } public static void assertAllFilesClosed() { try { for (final MockDirectoryHelper.ElasticsearchMockDirectoryWrapper w : MockDirectoryHelper.wrappers) { try { w.awaitClosed(5000); } catch (InterruptedException e) { Thread.interrupted(); } if (!w.successfullyClosed()) { if (w.closeException() == null) { try { w.close(); } catch (IOException e) { throw new ElasticsearchIllegalStateException("directory close threw IOException", e); } if (w.closeException() != null) { throw w.closeException(); } } else { throw w.closeException(); } } assertThat(w.isOpen(), is(false)); } } finally { MockDirectoryHelper.wrappers.clear(); } } public static void assertNodeContainsPlugins(NodesInfoResponse response, String nodeId, List<String> expectedJvmPluginNames, List<String> expectedJvmPluginDescriptions, List<String> expectedJvmVersions, List<String> expectedSitePluginNames, List<String> expectedSitePluginDescriptions, List<String> expectedSiteVersions) { Assert.assertThat(response.getNodesMap().get(nodeId), notNullValue()); PluginsInfo plugins = response.getNodesMap().get(nodeId).getPlugins(); Assert.assertThat(plugins, notNullValue()); List<String> pluginNames = FluentIterable.from(plugins.getInfos()).filter(jvmPluginPredicate).transform(nameFunction).toList(); for (String expectedJvmPluginName : expectedJvmPluginNames) { Assert.assertThat(pluginNames, hasItem(expectedJvmPluginName)); } List<String> pluginDescriptions = FluentIterable.from(plugins.getInfos()).filter(jvmPluginPredicate).transform(descriptionFunction).toList(); for (String expectedJvmPluginDescription : expectedJvmPluginDescriptions) { Assert.assertThat(pluginDescriptions, hasItem(expectedJvmPluginDescription)); } List<String> jvmPluginVersions = FluentIterable.from(plugins.getInfos()).filter(jvmPluginPredicate).transform(versionFunction).toList(); for (String pluginVersion : expectedJvmVersions) { Assert.assertThat(jvmPluginVersions, hasItem(pluginVersion)); } FluentIterable<String> jvmUrls = FluentIterable.from(plugins.getInfos()) .filter(Predicates.and(jvmPluginPredicate, Predicates.not(sitePluginPredicate))) .filter(isNull()) .transform(urlFunction); Assert.assertThat(Iterables.size(jvmUrls), is(0)); List<String> sitePluginNames = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate).transform(nameFunction).toList(); Assert.assertThat(sitePluginNames.isEmpty(), is(expectedSitePluginNames.isEmpty())); for (String expectedSitePluginName : expectedSitePluginNames) { Assert.assertThat(sitePluginNames, hasItem(expectedSitePluginName)); } List<String> sitePluginDescriptions = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate).transform(descriptionFunction).toList(); Assert.assertThat(sitePluginDescriptions.isEmpty(), is(expectedSitePluginDescriptions.isEmpty())); for (String sitePluginDescription : expectedSitePluginDescriptions) { Assert.assertThat(sitePluginDescriptions, hasItem(sitePluginDescription)); } List<String> sitePluginUrls = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate).transform(urlFunction).toList(); Assert.assertThat(sitePluginUrls, not(contains(nullValue()))); List<String> sitePluginVersions = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate).transform(versionFunction).toList(); Assert.assertThat(sitePluginVersions.isEmpty(), is(expectedSiteVersions.isEmpty())); for (String pluginVersion : expectedSiteVersions) { Assert.assertThat(sitePluginVersions, hasItem(pluginVersion)); } } private static Predicate<PluginInfo> jvmPluginPredicate = new Predicate<PluginInfo>() { public boolean apply(PluginInfo pluginInfo) { return pluginInfo.isJvm(); } }; private static Predicate<PluginInfo> sitePluginPredicate = new Predicate<PluginInfo>() { public boolean apply(PluginInfo pluginInfo) { return pluginInfo.isSite(); } }; private static Function<PluginInfo, String> nameFunction = new Function<PluginInfo, String>() { public String apply(PluginInfo pluginInfo) { return pluginInfo.getName(); } }; private static Function<PluginInfo, String> descriptionFunction = new Function<PluginInfo, String>() { public String apply(PluginInfo pluginInfo) { return pluginInfo.getDescription(); } }; private static Function<PluginInfo, String> urlFunction = new Function<PluginInfo, String>() { public String apply(PluginInfo pluginInfo) { return pluginInfo.getUrl(); } }; private static Function<PluginInfo, String> versionFunction = new Function<PluginInfo, String>() { public String apply(PluginInfo pluginInfo) { return pluginInfo.getVersion(); } }; /** * Check if a file exists */ public static void assertFileExists(File file) { assertThat("file/dir [" + file + "] should exist.", file.exists(), is(true)); } /** * Check if a file exists */ public static void assertFileExists(Path file) { assertFileExists(file.toFile()); } /** * Check if a directory exists */ public static void assertDirectoryExists(File dir) { assertFileExists(dir); } /** * Check if a directory exists */ public static void assertDirectoryExists(Path dir) { assertFileExists(dir); } }
apache-2.0
elasticlib/elasticlib
elasticlib-common/src/main/java/org/elasticlib/common/model/AgentInfo.java
3372
/* * Copyright 2014 Guillaume Masclet <guillaume.masclet@yahoo.fr>. * * 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.elasticlib.common.model; import static com.google.common.base.MoreObjects.toStringHelper; import java.util.Map; import static java.util.Objects.hash; import org.elasticlib.common.mappable.MapBuilder; import org.elasticlib.common.mappable.Mappable; import org.elasticlib.common.util.EqualsBuilder; import org.elasticlib.common.value.Value; /** * Holds info about a live agent. */ public final class AgentInfo implements Mappable { private static final String CUR_SEQ = "curSeq"; private static final String MAX_SEQ = "maxSeq"; private static final String STATE = "state"; private final long curSeq; private final long maxSeq; private final AgentState state; /** * Constructor. * * @param curSeq The currentSeq attribute. * @param maxSeq The maxSeq attribute. * @param state The state attribute. */ public AgentInfo(long curSeq, long maxSeq, AgentState state) { this.curSeq = curSeq; this.maxSeq = maxSeq; this.state = state; } /** * @return The latest processed event seq. */ public long getCurSeq() { return curSeq; } /** * @return The maximum event seq value. */ public long getMaxSeq() { return maxSeq; } /** * @return The agent state. */ public AgentState getState() { return state; } @Override public Map<String, Value> toMap() { return new MapBuilder() .put(CUR_SEQ, curSeq) .put(MAX_SEQ, maxSeq) .put(STATE, state.toString()) .build(); } /** * Read a new instance from supplied map of values. * * @param map A map of values. * @return A new instance. */ public static AgentInfo fromMap(Map<String, Value> map) { return new AgentInfo(map.get(CUR_SEQ).asLong(), map.get(MAX_SEQ).asLong(), AgentState.fromString(map.get(STATE).asString())); } @Override public String toString() { return toStringHelper(this) .add(CUR_SEQ, curSeq) .add(MAX_SEQ, maxSeq) .add(STATE, state) .toString(); } @Override public int hashCode() { return hash(curSeq, maxSeq, state); } @Override public boolean equals(Object obj) { if (!(obj instanceof AgentInfo)) { return false; } AgentInfo other = (AgentInfo) obj; return new EqualsBuilder() .append(curSeq, other.curSeq) .append(maxSeq, other.maxSeq) .append(state, other.state) .build(); } }
apache-2.0
T145/magistics
src/main/java/T145/magistics/common/network/base/MessageBase.java
854
package T145.magistics.common.network.base; import java.io.IOException; import com.google.common.base.Throwables; import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; public abstract class MessageBase implements IMessage { @Override public final void toBytes(ByteBuf buffer) { serialize(new PacketBuffer(buffer)); } @Override public final void fromBytes(ByteBuf buffer) { try { deserialize(new PacketBuffer(buffer)); } catch (IOException err) { Throwables.propagate(err); } } public abstract void serialize(PacketBuffer buffer); public abstract void deserialize(PacketBuffer buffer) throws IOException; public abstract IMessage process(MessageContext context); }
apache-2.0
consulo/consulo
modules/base/platform-impl/src/main/java/consulo/start/CommandLineArgs.java
3131
/* * Copyright 2013-2016 consulo.io * * 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 consulo.start; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; /** * @author VISTALL * @since 23-Dec-16 */ public class CommandLineArgs { @Option(name = "--no-splash", usage = "Disable splash at start") private boolean myNoSplash; @Option(name = "--no-recent-projects", usage = "Disable opening recent projects at start") private boolean myNoRecentProjects; @Option(name = "--line", metaVar = "<line>", usage = "Line of file") private int myLine = -1; @Option(name = "--json", metaVar = "<json>", usage = "JSON file of API request after start") private String myJson; @Option(name = "--version", usage = "Print version") private boolean myShowVersion; @Option(name = "--help", help = true, usage = "Show help") private boolean myShowHelp; @Argument(usage = "File or project for open", metaVar = "<file>") private String file; public boolean isShowVersion() { return myShowVersion; } public boolean isNoRecentProjects() { return myNoRecentProjects; } public int getLine() { return myLine; } public boolean isNoSplash() { return myNoSplash; } public boolean isShowHelp() { return myShowHelp; } public void setFile(String file) { this.file = file; } public void setNoRecentProjects(boolean noRecentProjects) { myNoRecentProjects = noRecentProjects; } public String getFile() { return file; } public String getJson() { return myJson; } public void setJson(String json) { myJson = json; } public static CommandLineArgs parse(String[] args) { CommandLineArgs o = new CommandLineArgs(); CmdLineParser parser = new CmdLineParser(o); try { parser.parseArgument(args); } catch (CmdLineException e) { parser.printUsage(System.out); } return o; } public static void printUsage() { System.out.println("Command line options:"); CmdLineParser parser = new CmdLineParser(new CommandLineArgs()); parser.printUsage(System.out); } @Override public String toString() { final StringBuilder sb = new StringBuilder("CommandLineArgs{"); sb.append("myNoSplash=").append(myNoSplash); sb.append(", myLine=").append(myLine); sb.append(", myShowVersion=").append(myShowVersion); sb.append(", myShowHelp=").append(myShowHelp); sb.append(", file='").append(file).append('\''); sb.append('}'); return sb.toString(); } }
apache-2.0
b2ihealthcare/snow-owl
cis/com.b2international.snowowl.snomed.cis/src/com/b2international/snowowl/snomed/cis/model/PublicationData.java
1429
/* * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.cis.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * @since 4.5 */ public class PublicationData extends RequestData { @JsonProperty("sctid") private String sctId; public PublicationData(final String namespace, final String software, final String sctId) { super(namespace, software); this.sctId = sctId; } @JsonCreator public PublicationData( @JsonProperty("namespace") final int namespace, @JsonProperty("software") final String software, @JsonProperty("sctid") final String sctId) { super(namespace, software); this.sctId = sctId; } public String getSctId() { return sctId; } public void setSctId(String sctId) { this.sctId = sctId; } }
apache-2.0
emil-wcislo/sbql4j8
sbql4j8/src/test/openjdk/tools/javac/7079713/TestCircularClassfile.java
6205
/* * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 7079713 * @summary javac hangs when compiling a class that references a cyclically inherited class * @run main TestCircularClassfile */ import java.io.*; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import sbql4j8.com.sun.source.util.JavacTask; public class TestCircularClassfile { enum SourceKind { A_EXTENDS_B("class B {} class A extends B { void m() {} }"), B_EXTENDS_A("class A { void m() {} } class B extends A {}"); String sourceStr; private SourceKind(String sourceStr) { this.sourceStr = sourceStr; } SimpleJavaFileObject getSource() { return new SimpleJavaFileObject(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return sourceStr; } }; } } enum TestKind { REPLACE_A("A.class"), REPLACE_B("B.class"); String targetClass; private TestKind(String targetClass) { this.targetClass = targetClass; } } enum ClientKind { METHOD_CALL1("A a = null; a.m();"), METHOD_CALL2("B b = null; b.m();"), CONSTR_CALL1("new A();"), CONSTR_CALL2("new B();"), ASSIGN1("A a = null; B b = a;"), ASSIGN2("B b = null; A a = b;"); String mainMethod; private ClientKind(String mainMethod) { this.mainMethod = mainMethod; } SimpleJavaFileObject getSource() { return new SimpleJavaFileObject(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return "class Test { public static void main(String[] args) { #M } }" .replace("#M", mainMethod); } }; } } public static void main(String... args) throws Exception { JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null); int count = 0; for (SourceKind sk1 : SourceKind.values()) { for (SourceKind sk2 : SourceKind.values()) { for (TestKind tk : TestKind.values()) { for (ClientKind ck : ClientKind.values()) { new TestCircularClassfile("sub_"+count++, sk1, sk2, tk, ck).check(comp, fm); } } } } } static String workDir = System.getProperty("user.dir"); String destPath; SourceKind sk1; SourceKind sk2; TestKind tk; ClientKind ck; TestCircularClassfile(String destPath, SourceKind sk1, SourceKind sk2, TestKind tk, ClientKind ck) { this.destPath = destPath; this.sk1 = sk1; this.sk2 = sk2; this.tk = tk; this.ck = ck; } void check(JavaCompiler comp, StandardJavaFileManager fm) throws Exception { //step 1: compile first source code in the test subfolder File destDir = new File(workDir, destPath); destDir.mkdir(); //output dir must be set explicitly as we are sharing the fm (see bug 7026941) fm.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir)); JavacTask ct = (JavacTask)comp.getTask(null, fm, null, null, null, Arrays.asList(sk1.getSource())); ct.generate(); //step 2: compile second source code in a temp folder File tmpDir = new File(destDir, "tmp"); tmpDir.mkdir(); //output dir must be set explicitly as we are sharing the fm (see bug 7026941) fm.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(tmpDir)); ct = (JavacTask)comp.getTask(null, fm, null, null, null, Arrays.asList(sk2.getSource())); ct.generate(); //step 3: move a classfile from the temp folder to the test subfolder File fileToMove = new File(tmpDir, tk.targetClass); File target = new File(destDir, tk.targetClass); target.delete(); boolean success = fileToMove.renameTo(target); if (!success) { throw new AssertionError("error when moving file " + tk.targetClass); } //step 4: compile the client class against the classes in the test subfolder //input/output dir must be set explicitly as we are sharing the fm (see bug 7026941) fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir)); fm.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(destDir)); ct = (JavacTask)comp.getTask(null, fm, null, null, null, Arrays.asList(ck.getSource())); ct.generate(); } }
apache-2.0
zccmj/java-telegram-bot-api
src/main/java/com/pengrad/telegrambot/model/UserOrGroupChat.java
333
package com.pengrad.telegrambot.model; /** * stas * 8/5/15. */ public class UserOrGroupChat { public Integer id; //User public String first_name; public String last_name; public String username; //Group public String title; public boolean isUser() { return first_name != null; } }
apache-2.0
omindra/schema_org_java_api
core/main/java/org/schema/api/model/thing/intangible/offer/Offer.java
10565
package org.schema.api.model.thing.intangible.offer; import org.schema.api.model.thing.intangible.Intangible; import org.schema.api.model.thing.intangible.offer.Offer; import org.schema.api.model.thing.intangible.structuredValue.QuantitativeValue; import org.schema.api.model.thing.intangible.rating.AggregateRating; import org.schema.api.model.thing.intangible.enumeration.ItemAvailability; import java.util.Date; import java.util.Date; import org.schema.api.model.thing.place.Place; import org.schema.api.model.thing.intangible.enumeration.deliveryMethod.DeliveryMethod; import org.schema.api.model.thing.intangible.enumeration.BusinessFunction; import org.schema.api.model.thing.intangible.structuredValue.QuantitativeValue; import org.schema.api.model.thing.intangible.enumeration.BusinessEntityType; import org.schema.api.model.thing.intangible.structuredValue.QuantitativeValue; import org.schema.api.model.thing.intangible.structuredValue.QuantitativeValue; import org.schema.api.model.thing.intangible.structuredValue.priceSpecification.PriceSpecification; import org.schema.api.model.thing.intangible.structuredValue.TypeAndQuantityNode; import org.schema.api.model.thing.intangible.structuredValue.QuantitativeValue; import org.schema.api.model.thing.intangible.enumeration.OfferItemCondition; import org.schema.api.model.thing.product.Product; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.intangible.structuredValue.priceSpecification.PriceSpecification; import java.util.Date; import org.schema.api.model.thing.creativeWork.Review; import org.schema.api.model.thing.organization.Organization; import java.util.Date; import java.util.Date; import org.schema.api.model.thing.intangible.structuredValue.WarrantyPromise; public class Offer extends Intangible { private LoanOrCredit acceptedPaymentMethod;//Notes - Allowed types- [LoanOrCredit, PaymentMethod] private Offer addOn; private QuantitativeValue advanceBookingRequirement; private AggregateRating aggregateRating; private String areaServed;//Notes - Allowed types- [AdministrativeArea, GeoShape, Place, Text, serviceArea] private ItemAvailability availability; private Date availabilityEnds; private Date availabilityStarts; private Place availableAtOrFrom; private DeliveryMethod availableDeliveryMethod; private BusinessFunction businessFunction; private String category;//Notes - Allowed types- [PhysicalActivityCategory, Text, Thing] private QuantitativeValue deliveryLeadTime; private BusinessEntityType eligibleCustomerType; private QuantitativeValue eligibleDuration; private QuantitativeValue eligibleQuantity; private String eligibleRegion;//Notes - Allowed types- [GeoShape, Place, Text] private PriceSpecification eligibleTransactionVolume; private String gtin12; private String gtin13; private String gtin14; private String gtin8; private TypeAndQuantityNode includesObject; private String ineligibleRegion;//Notes - Allowed types- [GeoShape, Place, Text] private QuantitativeValue inventoryLevel; private OfferItemCondition itemCondition; private Product itemOffered;//Notes - Allowed types- [Product, Service] private String mpn; private Organization offeredBy;//Notes - Allowed types- [Organization, Person, makesOffer] private Number price;//Notes - Allowed types- [Number, Text] private String priceCurrency;//Notes - Allowed types- [Text, PriceSpecification] private PriceSpecification priceSpecification; private Date priceValidUntil; private Review review;//Notes - Allowed types- [Review, reviews] private Organization seller;//Notes - Allowed types- [Organization, Person] private String serialNumber; private String sku; private Date validFrom; private Date validThrough; private WarrantyPromise warranty;//Notes - Allowed types- [WarrantyPromise, warrantyPromise] public LoanOrCredit getAcceptedPaymentMethod() { return acceptedPaymentMethod; } public void setAcceptedPaymentMethod(LoanOrCredit acceptedPaymentMethod) { this.acceptedPaymentMethod = acceptedPaymentMethod; } public Offer getAddOn() { return addOn; } public void setAddOn(Offer addOn) { this.addOn = addOn; } public QuantitativeValue getAdvanceBookingRequirement() { return advanceBookingRequirement; } public void setAdvanceBookingRequirement(QuantitativeValue advanceBookingRequirement) { this.advanceBookingRequirement = advanceBookingRequirement; } public AggregateRating getAggregateRating() { return aggregateRating; } public void setAggregateRating(AggregateRating aggregateRating) { this.aggregateRating = aggregateRating; } public String getAreaServed() { return areaServed; } public void setAreaServed(String areaServed) { this.areaServed = areaServed; } public ItemAvailability getAvailability() { return availability; } public void setAvailability(ItemAvailability availability) { this.availability = availability; } public Date getAvailabilityEnds() { return availabilityEnds; } public void setAvailabilityEnds(Date availabilityEnds) { this.availabilityEnds = availabilityEnds; } public Date getAvailabilityStarts() { return availabilityStarts; } public void setAvailabilityStarts(Date availabilityStarts) { this.availabilityStarts = availabilityStarts; } public Place getAvailableAtOrFrom() { return availableAtOrFrom; } public void setAvailableAtOrFrom(Place availableAtOrFrom) { this.availableAtOrFrom = availableAtOrFrom; } public DeliveryMethod getAvailableDeliveryMethod() { return availableDeliveryMethod; } public void setAvailableDeliveryMethod(DeliveryMethod availableDeliveryMethod) { this.availableDeliveryMethod = availableDeliveryMethod; } public BusinessFunction getBusinessFunction() { return businessFunction; } public void setBusinessFunction(BusinessFunction businessFunction) { this.businessFunction = businessFunction; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public QuantitativeValue getDeliveryLeadTime() { return deliveryLeadTime; } public void setDeliveryLeadTime(QuantitativeValue deliveryLeadTime) { this.deliveryLeadTime = deliveryLeadTime; } public BusinessEntityType getEligibleCustomerType() { return eligibleCustomerType; } public void setEligibleCustomerType(BusinessEntityType eligibleCustomerType) { this.eligibleCustomerType = eligibleCustomerType; } public QuantitativeValue getEligibleDuration() { return eligibleDuration; } public void setEligibleDuration(QuantitativeValue eligibleDuration) { this.eligibleDuration = eligibleDuration; } public QuantitativeValue getEligibleQuantity() { return eligibleQuantity; } public void setEligibleQuantity(QuantitativeValue eligibleQuantity) { this.eligibleQuantity = eligibleQuantity; } public String getEligibleRegion() { return eligibleRegion; } public void setEligibleRegion(String eligibleRegion) { this.eligibleRegion = eligibleRegion; } public PriceSpecification getEligibleTransactionVolume() { return eligibleTransactionVolume; } public void setEligibleTransactionVolume(PriceSpecification eligibleTransactionVolume) { this.eligibleTransactionVolume = eligibleTransactionVolume; } public String getGtin12() { return gtin12; } public void setGtin12(String gtin12) { this.gtin12 = gtin12; } public String getGtin13() { return gtin13; } public void setGtin13(String gtin13) { this.gtin13 = gtin13; } public String getGtin14() { return gtin14; } public void setGtin14(String gtin14) { this.gtin14 = gtin14; } public String getGtin8() { return gtin8; } public void setGtin8(String gtin8) { this.gtin8 = gtin8; } public TypeAndQuantityNode getIncludesObject() { return includesObject; } public void setIncludesObject(TypeAndQuantityNode includesObject) { this.includesObject = includesObject; } public String getIneligibleRegion() { return ineligibleRegion; } public void setIneligibleRegion(String ineligibleRegion) { this.ineligibleRegion = ineligibleRegion; } public QuantitativeValue getInventoryLevel() { return inventoryLevel; } public void setInventoryLevel(QuantitativeValue inventoryLevel) { this.inventoryLevel = inventoryLevel; } public OfferItemCondition getItemCondition() { return itemCondition; } public void setItemCondition(OfferItemCondition itemCondition) { this.itemCondition = itemCondition; } public Product getItemOffered() { return itemOffered; } public void setItemOffered(Product itemOffered) { this.itemOffered = itemOffered; } public String getMpn() { return mpn; } public void setMpn(String mpn) { this.mpn = mpn; } public Organization getOfferedBy() { return offeredBy; } public void setOfferedBy(Organization offeredBy) { this.offeredBy = offeredBy; } public Number getPrice() { return price; } public void setPrice(Number price) { this.price = price; } public String getPriceCurrency() { return priceCurrency; } public void setPriceCurrency(String priceCurrency) { this.priceCurrency = priceCurrency; } public PriceSpecification getPriceSpecification() { return priceSpecification; } public void setPriceSpecification(PriceSpecification priceSpecification) { this.priceSpecification = priceSpecification; } public Date getPriceValidUntil() { return priceValidUntil; } public void setPriceValidUntil(Date priceValidUntil) { this.priceValidUntil = priceValidUntil; } public Review getReview() { return review; } public void setReview(Review review) { this.review = review; } public Organization getSeller() { return seller; } public void setSeller(Organization seller) { this.seller = seller; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public Date getValidFrom() { return validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidThrough() { return validThrough; } public void setValidThrough(Date validThrough) { this.validThrough = validThrough; } public WarrantyPromise getWarranty() { return warranty; } public void setWarranty(WarrantyPromise warranty) { this.warranty = warranty; } }
apache-2.0
v-lukashin/aerospike-hadoop
mapreduce/src/main/java/com/aerospike/hadoop/mapreduce/AsyncClientPool.java
1186
package com.aerospike.hadoop.mapreduce; import com.aerospike.client.Host; import com.aerospike.client.async.AsyncClient; import com.aerospike.client.async.AsyncClientPolicy; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; public class AsyncClientPool { private static final ConcurrentHashMap<String, AsyncClient> instances = new ConcurrentHashMap<String, AsyncClient>(); public static AsyncClient getInstance(AsyncClientPolicy policy, Host... hosts) { String[] strHosts = new String[hosts.length]; for (int i = 0; i < hosts.length; i++) strHosts[i] = hosts[i].toString(); Arrays.sort(strHosts); StringBuilder sb = new StringBuilder(); for (String strHost : strHosts) sb.append(strHost).append(','); String key = sb.toString(); AsyncClient client; if (instances.containsKey(key)) client = instances.get(key); else synchronized (instances) { if (instances.containsKey(key)) client = instances.get(key); else instances.put(key, client = new AsyncClient(policy, hosts)); } return client; } }
apache-2.0
irudyak/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/wal/IgniteWalFlushMultiNodeFailoverAbstractSelfTest.java
9850
/* * 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.ignite.internal.processors.cache.persistence.db.wal; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheRebalanceMode; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.WALMode; import org.apache.ignite.failure.StopNodeFailureHandler; import org.apache.ignite.internal.pagemem.wal.IgniteWriteAheadLogManager; import org.apache.ignite.internal.processors.cache.persistence.file.FileIO; import org.apache.ignite.internal.processors.cache.persistence.file.FileIODecorator; import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory; import org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory; import org.apache.ignite.internal.processors.cache.persistence.wal.FileWriteAheadLogManager; import org.apache.ignite.internal.processors.cache.persistence.wal.FsyncModeFileWriteAheadLogManager; import org.apache.ignite.internal.util.lang.GridAbsPredicate; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.transactions.Transaction; import org.apache.ignite.transactions.TransactionConcurrency; import org.apache.ignite.transactions.TransactionIsolation; import java.nio.file.OpenOption; import java.util.concurrent.atomic.AtomicBoolean; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; /** * Tests error recovery while node flushing */ public abstract class IgniteWalFlushMultiNodeFailoverAbstractSelfTest extends GridCommonAbstractTest { /** */ private static final String TEST_CACHE = "testCache"; /** */ private static final int ITRS = 2000; /** */ private AtomicBoolean canFail = new AtomicBoolean(); /** * @return Node count. */ protected abstract int gridCount(); /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); stopAllGrids(); cleanPersistenceDir(); System.setProperty(IgniteSystemProperties.IGNITE_WAL_MMAP, Boolean.toString(mmap())); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); cleanPersistenceDir(); System.clearProperty(IgniteSystemProperties.IGNITE_WAL_MMAP); super.afterTest(); } /** {@inheritDoc} */ @Override protected long getTestTimeout() { return 60_000; } /** * @return WAL mode used in test. */ protected abstract WALMode walMode(); /** * @return {@code True} if test should use MMAP buffer mode. */ protected boolean mmap() { return false; } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setConsistentId(gridName); CacheConfiguration cacheCfg = new CacheConfiguration(TEST_CACHE) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL) .setBackups(1) .setRebalanceMode(CacheRebalanceMode.SYNC) .setAffinity(new RendezvousAffinityFunction(false, 32)); cfg.setCacheConfiguration(cacheCfg); DataStorageConfiguration memCfg = new DataStorageConfiguration() .setDefaultDataRegionConfiguration( new DataRegionConfiguration().setMaxSize(2048L * 1024 * 1024).setPersistenceEnabled(true)) .setWalMode(this.walMode()) .setWalSegmentSize(512 * 1024) .setWalBufferSize(512 * 1024); cfg.setDataStorageConfiguration(memCfg); cfg.setFailureHandler(new StopNodeFailureHandler()); return cfg; } /** * Test flushing error recovery when flush is triggered while node starting * * @throws Exception In case of fail */ public void testFailWhileStart() throws Exception { failWhilePut(true); } /** * Test flushing error recovery when flush is triggered after node started * * @throws Exception In case of fail */ public void testFailAfterStart() throws Exception { failWhilePut(false); } /** * @throws Exception if failed. */ public void failWhilePut(boolean failWhileStart) throws Exception { final Ignite grid = startGridsMultiThreaded(gridCount()); grid.cluster().active(true); IgniteCache<Object, Object> cache = grid.cache(TEST_CACHE); for (int i = 0; i < ITRS; i++) { while (true) { try (Transaction tx = grid.transactions().txStart( TransactionConcurrency.PESSIMISTIC, TransactionIsolation.READ_COMMITTED)) { cache.put(i, "testValue" + i); tx.commit(); break; } catch (Exception expected) { // Expected exception. } } if (i == ITRS / 4) { try { if (failWhileStart) canFail.set(true); startGrid(gridCount()); setFileIOFactory(grid(gridCount()).context().cache().context().wal()); grid.cluster().setBaselineTopology(grid.cluster().topologyVersion()); waitForRebalancing(); } catch (Throwable expected) { // There can be any exception. Do nothing. } } if (i == ITRS / 2) canFail.set(true); } // We should await successful stop of node. GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return grid.cluster().nodes().size() == gridCount(); } }, getTestTimeout()); stopAllGrids(); canFail.set(false); Ignite grid0 = startGrids(gridCount() + 1); setFileIOFactory(grid(gridCount()).context().cache().context().wal()); grid0.cluster().active(true); cache = grid0.cache(TEST_CACHE); for (int i = 0; i < ITRS; i++) assertEquals(cache.get(i), "testValue" + i); } /** */ private void setFileIOFactory(IgniteWriteAheadLogManager wal) { if (wal instanceof FileWriteAheadLogManager) ((FileWriteAheadLogManager)wal).setFileIOFactory(new FailingFileIOFactory(canFail)); else if (wal instanceof FsyncModeFileWriteAheadLogManager) ((FsyncModeFileWriteAheadLogManager)wal).setFileIOFactory(new FailingFileIOFactory(canFail)); else fail(wal.getClass().toString()); } /** * Create File I/O which fails after second attempt to write to File */ private static class FailingFileIOFactory implements FileIOFactory { /** */ private static final long serialVersionUID = 0L; /** */ private final AtomicBoolean fail; /** */ private final FileIOFactory delegateFactory = new RandomAccessFileIOFactory(); /** */ FailingFileIOFactory(AtomicBoolean fail) { this.fail = fail; } /** {@inheritDoc} */ @Override public FileIO create(File file) throws IOException { return create(file, CREATE, READ, WRITE); } /** {@inheritDoc} */ @Override public FileIO create(File file, OpenOption... modes) throws IOException { final FileIO delegate = delegateFactory.create(file, modes); return new FileIODecorator(delegate) { /** {@inheritDoc} */ @Override public int write(ByteBuffer srcBuf) throws IOException { if (fail != null && fail.get()) throw new IOException("No space left on device"); return super.write(srcBuf); } /** {@inheritDoc} */ @Override public MappedByteBuffer map(int sizeBytes) throws IOException { if (fail != null && fail.get()) throw new IOException("No space left on deive"); return delegate.map(sizeBytes); } }; } } }
apache-2.0
felix9064/IdeaProjects
CrazyJava/src/com/felix/crazyjava/item0602/EqualTest.java
1003
package com.felix.crazyjava.item0602; /** * Created with IntelliJ IDEA. * Description: equal()和==的区别,字符串及基本数据类型比较时用==,对象或引用类型的比较用equal()方法 * Author: Felix * Date: 2017/3/17 * Time: 15:27 */ public class EqualTest { public static void main(String[] args) { int it = 65; float fl = 65.0f; System.out.println("65和65.0f是否相等?" + (it == fl)); char ch = 'A'; System.out.println("65和'A'是否相等?" + (it == ch)); String s1 = "felix"; String s2 = "felix"; System.out.println("s1==s2是否相等?" + (s1 == s2)); System.out.println("s1.equals(s2)是否相等?" + (s1.equals(s2))); String str1 = new String("hello"); String str2 = new String("hello"); System.out.println("str1==str2是否相等?" + (str1 == str2)); System.out.println("str1.equals(str2)是否相等?" + (str1.equals(str2))); } }
apache-2.0
gwtproject/gwt-event-dom
gwt-event-dom/src/main/java/org/gwtproject/event/dom/client/ErrorHandler.java
966
/* * Copyright © 2019 The GWT Project 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.gwtproject.event.dom.client; import org.gwtproject.event.legacy.shared.EventHandler; /** Handler interface for {@link ErrorEvent} events. */ public interface ErrorHandler extends EventHandler { /** * Called when ErrorEvent is fired. * * @param event the {@link ErrorEvent} that was fired */ void onError(ErrorEvent event); }
apache-2.0
dailystudio/devbricks
src/androidTest/java/com/dailystudio/dataobject/database/DatabaseConnectivityDirectSQLImplTest.java
27079
package com.dailystudio.dataobject.database; import java.util.List; import java.util.Random; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import com.dailystudio.GlobalContextWrapper; import com.dailystudio.dataobject.Column; import com.dailystudio.dataobject.DatabaseObject; import com.dailystudio.dataobject.DatabaseObjectFactory; import com.dailystudio.dataobject.Template; import com.dailystudio.dataobject.query.ExpressionToken; import com.dailystudio.dataobject.query.OrderingToken; import com.dailystudio.dataobject.query.Query; import com.dailystudio.dataobject.samples.ProjectionObject; import com.dailystudio.dataobject.samples.QueryObject; import com.dailystudio.dataobject.samples.SampleObject1; import com.dailystudio.dataobject.samples.SampleObject2; import com.dailystudio.development.Logger; import com.dailystudio.test.ActivityTestCase; import com.dailystudio.test.Asserts; public class DatabaseConnectivityDirectSQLImplTest extends ActivityTestCase { private Random mRandom = new Random(); @Override protected void setUp() throws Exception { super.setUp(); GlobalContextWrapper.bindContext(mContext); } @Override protected void tearDown() throws Exception { super.tearDown(); GlobalContextWrapper.unbindContext(mContext); } private byte[] randomBytesArray(int length) { assertTrue(length > 0); byte[] bytes = new byte[length]; for (int i = 0; i <length; i++) { bytes[i] = (byte)mRandom.nextInt(255); } return bytes; } private byte[] fillBytesArray(int length, byte sample) { assertTrue(length > 0); byte[] bytes = new byte[length]; for (int i = 0; i <length; i++) { bytes[i] = sample; } return bytes; } public void testInsertDatabaseObject() { AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject2.class); assertNotNull(connectivity); DatabaseObject object = DatabaseObjectFactory.createDatabaseObject(SampleObject2.class); assertNotNull(object); object.setValue(SampleObject2.COLUMN_LAT, 0.1); object.setValue(SampleObject2.COLUMN_LON, 0.2); object.setValue(SampleObject2.COLUMN_ALT, 0.3); final byte[] rbtyes = randomBytesArray(1024); object.setValue(SampleObject2.COLUMN_BIN, rbtyes); long rowId = connectivity.insert(object); assertEquals(true, (rowId > 0)); DatabaseOpenHandler handler = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject2.class), 0x1); assertNotNull(handler); SQLiteDatabase sqlDB = handler.getReadableDatabase(); assertNotNull(sqlDB); Cursor c = sqlDB.query(DatabaseObject.classToTable(SampleObject2.class), null, null, null, null, null, null); assertNotNull(c); assertEquals(1, c.getCount()); assertEquals(true, c.moveToFirst()); assertEquals(0.1, c.getDouble(c.getColumnIndex(SampleObject2.COLUMN_LAT.getName()))); assertEquals(0.2, c.getDouble(c.getColumnIndex(SampleObject2.COLUMN_LON.getName()))); assertEquals(0.3, c.getDouble(c.getColumnIndex(SampleObject2.COLUMN_ALT.getName()))); Asserts.assertEquals(rbtyes, c.getBlob(c.getColumnIndex(SampleObject2.COLUMN_BIN.getName()))); c.close(); sqlDB.close(); connectivity.delete(new Query(SampleObject2.class)); } public void testInsertDatabaseObjects() { AbsDatabaseConnectivity connectivity1 = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject1.class); assertNotNull(connectivity1); AbsDatabaseConnectivity connectivity2 = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject2.class); assertNotNull(connectivity2); final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { object = DatabaseObjectFactory.createDatabaseObject(SampleObject1.class); assertNotNull(object); object.setValue(SampleObject1.COLUMN_TIME, (1000l * i)); } else { object = DatabaseObjectFactory.createDatabaseObject(SampleObject2.class); assertNotNull(object); object.setValue(SampleObject2.COLUMN_LAT, 0.1 * i); object.setValue(SampleObject2.COLUMN_LON, 0.2 * i); object.setValue(SampleObject2.COLUMN_ALT, 0.3 * i); object.setValue(SampleObject2.COLUMN_BIN, fillBytesArray(i, (byte)i)); } objects[i] = object; } connectivity1.insert(objects); connectivity2.insert(objects); DatabaseOpenHandler handler1 = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject1.class), 0x1); assertNotNull(handler1); DatabaseOpenHandler handler2 = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject2.class), 0x1); assertNotNull(handler2); SQLiteDatabase sqlDB = null; Cursor c = null; sqlDB = handler1.getReadableDatabase(); assertNotNull(sqlDB); c = sqlDB.query(DatabaseObject.classToTable(SampleObject1.class), null, null, null, null, null, null); assertNotNull(c); assertEquals(5, c.getCount()); assertEquals(true, c.moveToFirst()); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { assertEquals(i * 1000l, c.getLong(c.getColumnIndex("time"))); c.moveToNext(); } } c.close(); sqlDB.close(); sqlDB = handler2.getReadableDatabase(); assertNotNull(sqlDB); c = sqlDB.query(DatabaseObject.classToTable(SampleObject2.class), null, null, null, null, null, null); assertNotNull(c); assertEquals(5, c.getCount()); assertEquals(true, c.moveToFirst()); for (int i = 0; i < 5; i++) { if (i % 2 != 0) { assertEquals(0.1 * i, c.getDouble(c.getColumnIndex("latitude"))); assertEquals(0.2 * i, c.getDouble(c.getColumnIndex("longitude"))); assertEquals(0.3 * i, c.getDouble(c.getColumnIndex("altitude"))); assertEquals(0.3 * i, c.getDouble(c.getColumnIndex("altitude"))); Asserts.assertEquals(fillBytesArray(i, (byte)i), c.getBlob(c.getColumnIndex("binary"))); c.moveToNext(); } } c.close(); sqlDB.close(); connectivity1.delete(new Query(SampleObject1.class)); connectivity2.delete(new Query(SampleObject2.class)); } public void testDeleteDatabaseObjects() { AbsDatabaseConnectivity connectivity1 = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject1.class); assertNotNull(connectivity1); AbsDatabaseConnectivity connectivity2 = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject2.class); assertNotNull(connectivity2); final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { object = DatabaseObjectFactory.createDatabaseObject(SampleObject1.class); assertNotNull(object); object.setValue(SampleObject1.COLUMN_TIME, (1000l * i)); } else { object = DatabaseObjectFactory.createDatabaseObject(SampleObject2.class); assertNotNull(object); object.setValue(SampleObject2.COLUMN_LAT, 0.1 * i); object.setValue(SampleObject2.COLUMN_LON, 0.2 * i); object.setValue(SampleObject2.COLUMN_ALT, 0.3 * i); } objects[i] = object; } connectivity1.insert(objects); connectivity2.insert(objects); Query query1 = new Query(SampleObject1.class); assertNotNull(query1); ExpressionToken selection1 = SampleObject1.COLUMN_TIME.gt(5000l); assertNotNull(selection1); query1.setSelection(selection1); connectivity1.delete(query1); Query qParams2 = new Query(SampleObject2.class); assertNotNull(qParams2); ExpressionToken selection2 = SampleObject2.COLUMN_LAT.gt(0.2).and(SampleObject2.COLUMN_LON.lt(0.8)); assertNotNull(selection2); qParams2.setSelection(selection2); connectivity2.delete(qParams2); DatabaseOpenHandler handler1 = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject1.class), 0x1); assertNotNull(handler1); DatabaseOpenHandler handler2 = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject2.class), 0x1); assertNotNull(handler2); SQLiteDatabase sqlDB = null; Cursor c = null; sqlDB = handler1.getReadableDatabase(); assertNotNull(sqlDB); c = sqlDB.query(DatabaseObject.classToTable(SampleObject1.class), null, null, null, null, null, null); assertNotNull(c); assertEquals(3, c.getCount()); assertEquals(true, c.moveToFirst()); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { if (i * 1000l > 5000l) { continue; } else { assertEquals(i * 1000l, c.getLong(c.getColumnIndex("time"))); } c.moveToNext(); } } c.close(); sqlDB.close(); sqlDB = handler2.getReadableDatabase(); assertNotNull(sqlDB); c = sqlDB.query(DatabaseObject.classToTable(SampleObject2.class), null, null, null, null, null, null); assertNotNull(c); assertEquals(4, c.getCount()); assertEquals(true, c.moveToFirst()); for (int i = 0; i < 5; i++) { if (i % 2 != 0) { if ((0.1 * i > 0.2) && (0.2 * i < 0.8)) { continue; } else { assertEquals(0.1 * i, c.getDouble(c.getColumnIndex("latitude"))); assertEquals(0.2 * i, c.getDouble(c.getColumnIndex("longitude"))); assertEquals(0.3 * i, c.getDouble(c.getColumnIndex("altitude"))); } c.moveToNext(); } } c.close(); sqlDB.close(); connectivity1.delete(new Query(SampleObject1.class)); connectivity2.delete(new Query(SampleObject2.class)); } public void testDeleteAllDatabaseObjects() { AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject1.class); assertNotNull(connectivity); final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { object = DatabaseObjectFactory.createDatabaseObject(SampleObject1.class); assertNotNull(object); object.setValue(SampleObject1.COLUMN_TIME, (1000l * i)); objects[i] = object; } connectivity.insert(objects); Query query = new Query(SampleObject1.class); assertNotNull(query); connectivity.delete(query); DatabaseOpenHandler handler = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject1.class), 0x1); assertNotNull(handler); SQLiteDatabase sqlDB = handler.getReadableDatabase(); assertNotNull(sqlDB); boolean catched = false; try { sqlDB.query(DatabaseObject.classToTable(SampleObject1.class), null, null, null, null, null, null); catched = false; } catch (SQLException e) { e.printStackTrace(); catched = true; } sqlDB.close(); assertTrue(catched); connectivity.delete(new Query(SampleObject1.class)); } public void testUpdateDatabaseObjects() { AbsDatabaseConnectivity connectivity1 = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject1.class); assertNotNull(connectivity1); AbsDatabaseConnectivity connectivity2 = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, SampleObject2.class); assertNotNull(connectivity2); final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { object = DatabaseObjectFactory.createDatabaseObject(SampleObject1.class); assertNotNull(object); object.setValue(SampleObject1.COLUMN_TIME, (1000l * i)); } else { object = DatabaseObjectFactory.createDatabaseObject(SampleObject2.class); assertNotNull(object); object.setValue(SampleObject2.COLUMN_LAT, 0.1 * i); object.setValue(SampleObject2.COLUMN_LON, 0.2 * i); object.setValue(SampleObject2.COLUMN_ALT, 0.3 * i); object.setValue(SampleObject2.COLUMN_BIN, fillBytesArray(i, (byte)i)); } objects[i] = object; } connectivity1.insert(objects); connectivity2.insert(objects); DatabaseObject updateObject = null; Query query1 = new Query(SampleObject1.class); assertNotNull(query1); ExpressionToken selection1 = SampleObject1.COLUMN_TIME.gt(5000l); assertNotNull(selection1); query1.setSelection(selection1); updateObject = DatabaseObjectFactory.createDatabaseObject(SampleObject1.class); updateObject.setValue(SampleObject1.COLUMN_TIME, 0l); connectivity1.update(query1, updateObject); Query query2 = new Query(SampleObject2.class); assertNotNull(query2); ExpressionToken selection2 = SampleObject2.COLUMN_LAT.gt(0.2).and(SampleObject2.COLUMN_LON.lt(0.8)); assertNotNull(selection2); query2.setSelection(selection2); updateObject = DatabaseObjectFactory.createDatabaseObject(SampleObject2.class); updateObject.setValue(SampleObject2.COLUMN_ALT, 12.34); updateObject.setValue(SampleObject2.COLUMN_BIN, fillBytesArray(100, (byte)0xFF)); connectivity2.update(query2, updateObject); DatabaseOpenHandler handler1 = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject1.class), 0x1); assertNotNull(handler1); DatabaseOpenHandler handler2 = DatabaseOpenHandler.getInstance(mTargetContext, DatabaseObject.classToDatabase(SampleObject2.class), 0x1); assertNotNull(handler2); SQLiteDatabase sqlDB = null; Cursor c = null; sqlDB = handler1.getReadableDatabase(); assertNotNull(sqlDB); c = sqlDB.query(DatabaseObject.classToTable(SampleObject1.class), null, null, null, null, null, null); assertNotNull(c); assertEquals(5, c.getCount()); assertEquals(true, c.moveToFirst()); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { if (i * 1000l > 5000l) { assertEquals(0, c.getLong(c.getColumnIndex("time"))); } else { assertEquals(i * 1000l, c.getLong(c.getColumnIndex("time"))); } c.moveToNext(); } } c.close(); sqlDB.close(); sqlDB = handler2.getReadableDatabase(); assertNotNull(sqlDB); c = sqlDB.query(DatabaseObject.classToTable(SampleObject2.class), null, null, null, null, null, null); assertNotNull(c); assertEquals(5, c.getCount()); assertEquals(true, c.moveToFirst()); for (int i = 0; i < 5; i++) { if (i % 2 != 0) { if ((0.1 * i > 0.2) && (0.2 * i < 0.8)) { assertEquals(0.1 * i, c.getDouble(c.getColumnIndex("latitude"))); assertEquals(0.2 * i, c.getDouble(c.getColumnIndex("longitude"))); assertEquals(12.34, c.getDouble(c.getColumnIndex("altitude"))); object.setValue(SampleObject2.COLUMN_BIN, fillBytesArray(i, (byte)i)); } else { assertEquals(0.1 * i, c.getDouble(c.getColumnIndex("latitude"))); assertEquals(0.2 * i, c.getDouble(c.getColumnIndex("longitude"))); assertEquals(0.3 * i, c.getDouble(c.getColumnIndex("altitude"))); object.setValue(SampleObject2.COLUMN_BIN, fillBytesArray(100, (byte)0xFF)); } c.moveToNext(); } } c.close(); sqlDB.close(); connectivity1.delete(new Query(SampleObject1.class)); connectivity2.delete(new Query(SampleObject2.class)); } public void testSimpleQuery() { final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { object = DatabaseObjectFactory.createDatabaseObject(QueryObject.class); assertNotNull(object); object.setValue("intValue", i); object.setValue("doubleValue", ((double) i * 2)); object.setValue("textValue", String.format("%04d", i * 3)); objects[i] = object; } AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, QueryObject.class); assertNotNull(connectivity); connectivity.insert(objects); final Template templ = object.getTemplate(); Column col = templ.getColumn("intValue"); Query query = new Query(QueryObject.class); assertNotNull(query); ExpressionToken selToken = col.gt(5).and(col.lt(9)); query.setSelection(selToken); List<DatabaseObject> results = connectivity.query(query); assertNotNull(results); assertEquals(3, results.size()); DatabaseObject resultObject = null; for (int i = 6; i <= 8; i++) { resultObject = results.get(i - 6); assertNotNull(resultObject); Logger.debug("resultObject(%s)", resultObject.toSQLSelectionString()); Integer iVal = resultObject.getIntegerValue("intValue"); assertNotNull(iVal); assertEquals(i, iVal.intValue()); Double dVal = resultObject.getDoubleValue("doubleValue"); assertNotNull(dVal); assertEquals(((double) i * 2), dVal.doubleValue()); String sVal = resultObject.getTextValue("textValue"); assertNotNull(sVal); assertEquals(String.format("%04d", i * 3), sVal); } connectivity.delete(new Query(QueryObject.class)); } public void testQueryWithGroupBy() { final int count = (3 * 10); DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 3; i++) { for (int j = 0; j < 10; j++) { object = DatabaseObjectFactory.createDatabaseObject(QueryObject.class); assertNotNull(object); object.setValue("intValue", i); object.setValue("doubleValue", ((double) i * 2)); object.setValue("textValue", String.format("%04d", i * 3)); objects[i * 10 + j] = object; } } AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, QueryObject.class); assertNotNull(connectivity); connectivity.insert(objects); final Template templ = object.getTemplate(); Column col = templ.getColumn("intValue"); Query query = new Query(QueryObject.class); assertNotNull(query); ExpressionToken selToken = col.gte(0).and(col.lt(2)); query.setSelection(selToken); OrderingToken groupByToken = col.groupBy(); query.setGroupBy(groupByToken); List<DatabaseObject> results = connectivity.query(query); assertNotNull(results); assertEquals(2, results.size()); DatabaseObject resultObject = null; for (int i = 0; i < 2; i++) { resultObject = results.get(i); assertNotNull(resultObject); Logger.debug("resultObject(%s)", resultObject.toSQLSelectionString()); Integer iVal = resultObject.getIntegerValue("intValue"); assertNotNull(iVal); assertEquals(i, iVal.intValue()); Double dVal = resultObject.getDoubleValue("doubleValue"); assertNotNull(dVal); assertEquals(((double) i * 2), dVal.doubleValue()); String sVal = resultObject.getTextValue("textValue"); assertNotNull(sVal); assertEquals(String.format("%04d", i * 3), sVal); } connectivity.delete(new Query(QueryObject.class)); } public void testQueryWithOrderBy() { final int count = (3 * 10); DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 3; i++) { for (int j = 0; j < 10; j++) { object = DatabaseObjectFactory.createDatabaseObject(QueryObject.class); assertNotNull(object); object.setValue("intValue", j); object.setValue("doubleValue", ((double) j * 2)); object.setValue("textValue", String.format("%04d", j * 3)); objects[i * 10 + j] = object; } } AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, QueryObject.class); assertNotNull(connectivity); connectivity.insert(objects); final Template templ = object.getTemplate(); Column col = templ.getColumn("intValue"); Query query = null; List<DatabaseObject> results = null; OrderingToken orderByToken = null; DatabaseObject resultObject = null; query = new Query(QueryObject.class); assertNotNull(query); orderByToken = col.orderByAscending(); query.setOrderBy(orderByToken); results = connectivity.query(query); assertNotNull(results); assertEquals(30, results.size()); for (int j = 0; j < 10; j++) { for (int i = 0; i < 3; i++) { resultObject = results.get(j * 3 + i); assertNotNull(resultObject); Logger.debug("resultObject(%s)", resultObject.toSQLSelectionString()); Integer iVal = resultObject.getIntegerValue("intValue"); assertNotNull(iVal); assertEquals(j, iVal.intValue()); Double dVal = resultObject.getDoubleValue("doubleValue"); assertNotNull(dVal); assertEquals(((double) j * 2), dVal.doubleValue()); String sVal = resultObject.getTextValue("textValue"); assertNotNull(sVal); assertEquals(String.format("%04d", j * 3), sVal); } } query = new Query(QueryObject.class); assertNotNull(query); orderByToken = col.orderByDescending(); query.setOrderBy(orderByToken); results = connectivity.query(query); assertNotNull(results); assertEquals(30, results.size()); for (int j = 9; j >= 0; j--) { for (int i = 0; i < 3; i++) { resultObject = results.get((9 - j) * 3 + i); assertNotNull(resultObject); Logger.debug("resultObject(%s)", resultObject.toSQLSelectionString()); Integer iVal = resultObject.getIntegerValue("intValue"); assertNotNull(iVal); assertEquals(j, iVal.intValue()); Double dVal = resultObject.getDoubleValue("doubleValue"); assertNotNull(dVal); assertEquals(((double) j * 2), dVal.doubleValue()); String sVal = resultObject.getTextValue("textValue"); assertNotNull(sVal); assertEquals(String.format("%04d", j * 3), sVal); } } connectivity.delete(new Query(QueryObject.class)); } public void testLimitQuery() { final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { object = DatabaseObjectFactory.createDatabaseObject(QueryObject.class); assertNotNull(object); object.setValue("intValue", i); object.setValue("doubleValue", ((double) i * 2)); object.setValue("textValue", String.format("%04d", i * 3)); objects[i] = object; } AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, QueryObject.class); assertNotNull(connectivity); connectivity.insert(objects); Query query = new Query(QueryObject.class); assertNotNull(query); ExpressionToken limit = new ExpressionToken("5"); query.setLimit(limit); List<DatabaseObject> results = connectivity.query(query); assertNotNull(results); assertEquals(5, results.size()); DatabaseObject resultObject = null; for (int i = 0; i < 5; i++) { resultObject = results.get(i); assertNotNull(resultObject); Logger.debug("resultObject(%s)", resultObject.toSQLSelectionString()); Integer iVal = resultObject.getIntegerValue("intValue"); assertNotNull(iVal); assertEquals(i, iVal.intValue()); Double dVal = resultObject.getDoubleValue("doubleValue"); assertNotNull(dVal); assertEquals(((double) i * 2), dVal.doubleValue()); String sVal = resultObject.getTextValue("textValue"); assertNotNull(sVal); assertEquals(String.format("%04d", i * 3), sVal); } connectivity.delete(new Query(QueryObject.class)); } public void testQueryWithProjectionClass() { final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { object = DatabaseObjectFactory.createDatabaseObject(QueryObject.class); assertNotNull(object); object.setValue("intValue", i); object.setValue("doubleValue", ((double) i * 2)); object.setValue("textValue", String.format("%04d", i * 3)); objects[i] = object; } AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, QueryObject.class); assertNotNull(connectivity); connectivity.insert(objects); final Template templ = object.getTemplate(); Column col = templ.getColumn("intValue"); Query query = new Query(QueryObject.class); assertNotNull(query); ExpressionToken selToken = col.gt(5).and(col.lt(9)); query.setSelection(selToken); List<DatabaseObject> results = connectivity.query(query, ProjectionObject.class); assertNotNull(results); assertEquals(1, results.size()); DatabaseObject resultObject = results.get(0); Integer iCount = resultObject.getIntegerValue("count( _id )"); assertNotNull(iCount); assertEquals(3, iCount.intValue()); connectivity.delete(new Query(QueryObject.class)); } public void testQueryCursor() { final int count = 10; DatabaseObject object = null; DatabaseObject[] objects = new DatabaseObject[count]; assertNotNull(objects); for (int i = 0; i < 10; i++) { object = DatabaseObjectFactory.createDatabaseObject(QueryObject.class); assertNotNull(object); object.setValue("intValue", i); object.setValue("doubleValue", ((double) i * 2)); object.setValue("textValue", String.format("%04d", i * 3)); objects[i] = object; } AbsDatabaseConnectivity connectivity = new DatabaseConnectivityDirectSQLiteImpl(mTargetContext, QueryObject.class); assertNotNull(connectivity); connectivity.insert(objects); final Template templ = object.getTemplate(); Column col = templ.getColumn("intValue"); Query query = null; ExpressionToken selToken = null; DatabaseObject resultObject = null; Cursor c = null; query = new Query(QueryObject.class); assertNotNull(query); selToken = col.gt(5).and(col.lt(9)); query.setSelection(selToken); c = connectivity.queryCursor(query); assertNotNull(c); assertEquals(3, c.getCount()); assertTrue(c.moveToFirst()); for (int i = 6; i <= 8; i++, c.moveToNext()) { resultObject = connectivity.fromCursor(c, QueryObject.class); assertNotNull(resultObject); Logger.debug("resultObject(%s)", resultObject.toSQLSelectionString()); Integer iVal = resultObject.getIntegerValue("intValue"); assertNotNull(iVal); assertEquals(i, iVal.intValue()); Double dVal = resultObject.getDoubleValue("doubleValue"); assertNotNull(dVal); assertEquals(((double) i * 2), dVal.doubleValue()); String sVal = resultObject.getTextValue("textValue"); assertNotNull(sVal); assertEquals(String.format("%04d", i * 3), sVal); } c.close(); selToken = col.gt(5).and(col.lt(9)); query.setSelection(selToken); c = connectivity.queryCursor(query, ProjectionObject.class); assertNotNull(c); assertEquals(1, c.getCount()); assertTrue(c.moveToFirst()); resultObject = connectivity.fromCursor(c, ProjectionObject.class); Integer iCount = resultObject.getIntegerValue("count( _id )"); assertNotNull(iCount); assertEquals(3, iCount.intValue()); c.close(); connectivity.delete(new Query(QueryObject.class)); } }
apache-2.0
SocraticGrid/UCS-API
src/main/java/org/socraticgrid/hl7/services/uc/logging/package-info.java
1092
/* * Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedciine.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. */ @XmlSchema(xmlns = @XmlNs(prefix = "model", namespaceURI = "http://org.socraticgrid.hl7.services.uc.logging"), namespace = "http://org.socraticgrid.hl7.services.uc.logging", elementFormDefault = XmlNsForm.QUALIFIED, attributeFormDefault = XmlNsForm.QUALIFIED) package org.socraticgrid.hl7.services.uc.logging; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema;
apache-2.0
nenko-tabakov/dev-tools
src/online/devtools/eclipse/handlers/FieldsProvider.java
1148
package online.devtools.eclipse.handlers; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.viewers.ITreeContentProvider; class FieldsProvider implements ITreeContentProvider { private static final Object[] EMPTY = new Object[0]; @Override public boolean hasChildren(Object element) { Object[] children = getElements(element); return children != null && children.length > 0; } @Override public Object getParent(Object element) { if (element instanceof IJavaElement) { return ((IJavaElement) element).getParent(); } return null; } @Override public Object[] getElements(Object inputElement) { if (inputElement instanceof IType) { return getFields((IType) inputElement); } return EMPTY; } @Override public Object[] getChildren(Object parentElement) { return EMPTY; } public static IField[] getFields(IType type) { try { return type.getFields(); } catch (JavaModelException e) { e.printStackTrace(); } return new IField[0]; } }
apache-2.0
sacjaya/siddhi-3
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/executor/condition/compare/equal/EqualCompareConditionExecutorLongLong.java
1244
/* * Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.siddhi.core.executor.condition.compare.equal; import org.wso2.siddhi.core.executor.expression.ExpressionExecutor; public class EqualCompareConditionExecutorLongLong extends EqualCompareConditionExecutor { public EqualCompareConditionExecutorLongLong( ExpressionExecutor leftExpressionExecutor, ExpressionExecutor rightExpressionExecutor) { super(leftExpressionExecutor, rightExpressionExecutor); } @Override protected Boolean execute(Object left, Object right) { return ((Long) left).longValue() == (Long) right; } }
apache-2.0
foundation-runtime/configuration
configuration-lib/src/main/java/com/cisco/oss/foundation/configuration/DynamicReloadSupport.java
6694
/* * Copyright 2015 Cisco Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package com.cisco.oss.foundation.configuration; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.PropertiesConfiguration; import org.slf4j.*; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; /** * This class reads the configuration to determine if dynamic reload of the configuration in case of config file changes should be enabled or not.<br> * When enabled the configuration in memory map will be updated upon file changes within a configuration refresh delay period.<br> * Client interested in getting notifications of configuration reload should register via {@link FoundationConfigurationListenerRegistry#addFoundationConfigurationListener(FoundationConfigurationListener)} API. * * @author Yair Ogen */ public class DynamicReloadSupport { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicReloadSupport.class); private final CompositeConfiguration configuration; private DynamicReloadSupport(CompositeConfiguration configuration) { super(); this.configuration = configuration; } public void init() { LOGGER.debug("in DynamicReloadSupport init method"); boolean isDynamicReLoadEnabled = configuration.getBoolean("configuration.dynamicConfigReload.enabled", false); boolean isDynamicReloadAutoUpdateEnabled = true;//configuration.getBoolean("configuration.dynamicConfigReload.autoUpdateEnabled"); long refreshDelay = configuration.getLong("configuration.dynamicConfigReload.refreshDelay", 30000); if (isDynamicReLoadEnabled) { LOGGER.info("configuration dynamic reload is enabled!"); int numberOfConfigurations = configuration.getNumberOfConfigurations(); for (int index = 0; index < numberOfConfigurations; index++) { Configuration config = configuration.getConfiguration(index); // file reload only supported on file based configurations. // cab configuration only supports properties configuration. if (config instanceof PropertiesConfiguration) { PropertiesConfiguration propertiesConfiguration = (PropertiesConfiguration) config; // TODO: ignore default config files String fileName = propertiesConfiguration.getFileName(); if (fileName == null) { fileName = propertiesConfiguration.getBasePath(); } if (fileName.startsWith("default")) { // do not support reload for default config files. continue; } LOGGER.debug("Setting reload strategy on: " + propertiesConfiguration.getPath()); FoundationFileChangedReloadingStrategy strategy = new FoundationFileChangedReloadingStrategy(); strategy.setRefreshDelay(refreshDelay); propertiesConfiguration.setReloadingStrategy(strategy); } } if (isDynamicReloadAutoUpdateEnabled) { startDynamicReloadAutoUpdateDeamon(configuration, refreshDelay); } } } /** * @param refreshDelay */ private void startDynamicReloadAutoUpdateDeamon(final Configuration configuration, final long refreshDelay) { // run as daemon Timer timer = new Timer("DynamicReloadAutoUpdate", true); timer.schedule(new DynamicReloadTask().init(), refreshDelay, refreshDelay); } private class DynamicReloadTask extends TimerTask { private Field configCacheField; private Field modifiersField; public DynamicReloadTask() { init(); } public DynamicReloadTask init() { try { configCacheField = FoundationCompositeConfiguration.class.getDeclaredField("DISABLE_CACHE"); configCacheField.setAccessible(true); modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(configCacheField, configCacheField.getModifiers() & ~Modifier.FINAL); } catch (Exception e) { LOGGER.trace(e.toString(), e); } return this; } @Override public void run() { try { LOGGER.trace("Configuration reload started."); if (configCacheField == null) init(); Boolean disableCache = (Boolean) configCacheField.get(null); if (!disableCache) { configCacheField.set(null, Boolean.TRUE); // just for triggering reload mechanism boolean loaded = false; Iterator<String> configIterator = ConfigResourcesLoader.customerPropertyNames.iterator(); while (configIterator.hasNext() && !loaded) { String propName = configIterator.next(); try { configuration.getProperty(propName); loaded = true; } catch (Exception e) { LOGGER.trace(e.toString(), e); } } configCacheField.set(null, Boolean.FALSE); } else { // just for triggering reload mechanism configuration.getProperty("configuration.dynamicConfigReload.enabled"); } LOGGER.trace("Configuration reload finished."); } catch (Exception e) { LOGGER.error("problem reloading the configuration", e); } } } }
apache-2.0
atcult/mod-cataloging
src/main/java/org/folio/marccat/resources/domain/HeadingTypeCollection.java
1639
package org.folio.marccat.resources.domain; import com.fasterxml.jackson.annotation.*; import javax.annotation.Generated; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({"headingTypes"}) public class HeadingTypeCollection { /** * (Required) */ @JsonProperty("headingTypes") @Valid @NotNull private List<HeadingType> headingTypes = new ArrayList<HeadingType>(); @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * (Required) * * @return The headingTypes */ @JsonProperty("headingTypes") public List<HeadingType> getHeadingTypes() { return headingTypes; } /** * (Required) * * @param headingTypes The headingTypes */ @JsonProperty("headingTypes") public void setHeadingTypes(List<HeadingType> headingTypes) { this.headingTypes = headingTypes; } public HeadingTypeCollection withHeadingTypes(List<HeadingType> headingTypes) { this.headingTypes = headingTypes; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public HeadingTypeCollection withAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); return this; } }
apache-2.0
GaneshSPatil/gocd
plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/commons/PluginsZipTest.java
13985
/* * Copyright 2021 ThoughtWorks, 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.thoughtworks.go.plugin.infra.commons; import com.thoughtworks.go.plugin.FileHelper; import com.thoughtworks.go.plugin.infra.PluginManager; import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginBundleDescriptor; import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor; import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.collections4.EnumerationUtils; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.zip.ZipFile; import static com.thoughtworks.go.util.SystemEnvironment.*; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.Mockito.*; class PluginsZipTest { private SystemEnvironment systemEnvironment; private PluginsZip pluginsZip; private String expectedZipPath; private File externalPluginsDir; private PluginManager pluginManager; private GoPluginBundleDescriptor bundledTaskPlugin; private GoPluginBundleDescriptor externalTaskPlugin; private GoPluginBundleDescriptor externalElasticAgentPlugin; private File bundledPluginsDir; private FileHelper temporaryFolder; @BeforeEach void setUp(@TempDir File rootDir) throws Exception { temporaryFolder = new FileHelper(rootDir); pluginManager = mock(PluginManager.class); temporaryFolder.newFolder(); systemEnvironment = mock(SystemEnvironment.class); bundledPluginsDir = temporaryFolder.newFolder("plugins-bundled"); expectedZipPath = temporaryFolder.newFile("go-plugins-all.zip").getAbsolutePath(); externalPluginsDir = temporaryFolder.newFolder("plugins-external"); when(systemEnvironment.get(PLUGIN_GO_PROVIDED_PATH)).thenReturn(bundledPluginsDir.getAbsolutePath()); when(systemEnvironment.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(externalPluginsDir.getAbsolutePath()); when(systemEnvironment.get(ALL_PLUGINS_ZIP_PATH)).thenReturn(expectedZipPath); pluginsZip = spy(new PluginsZip(systemEnvironment, pluginManager)); File bundledTask1Jar = createPluginFile(this.bundledPluginsDir, "bundled-task-1.jar", "Bundled1"); File bundledAuth2Jar = createPluginFile(this.bundledPluginsDir, "bundled-auth-2.jar", "Bundled2"); File bundledscm3Jar = createPluginFile(this.bundledPluginsDir, "bundled-scm-3.jar", "Bundled3"); File bundledPackageMaterialJar = createPluginFile(this.bundledPluginsDir, "bundled-package-material-4.jar", "Bundled4"); File externalTask1Jar = createPluginFile(externalPluginsDir, "external-task-1.jar", "External1"); File externalElastic1Jar = createPluginFile(externalPluginsDir, "external-elastic-agent-2.jar", "External2"); File externalscm3Jar = createPluginFile(externalPluginsDir, "external-scm-3.jar", "External3"); File externalPackageMaterialJar = createPluginFile(externalPluginsDir, "external-package-material-4.jar", "External3"); bundledTaskPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("bundled-task-1", bundledTask1Jar, true)); GoPluginBundleDescriptor bundledAuthPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("bundled-auth-2", bundledAuth2Jar, true)); GoPluginBundleDescriptor bundledSCMPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("bundled-scm-3", bundledscm3Jar, true)); GoPluginBundleDescriptor bundledPackageMaterialPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("bundled-package-material-4", bundledPackageMaterialJar, true)); externalTaskPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("external-task-1", externalTask1Jar, false)); externalElasticAgentPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("external-elastic-agent-2", externalElastic1Jar, false)); GoPluginBundleDescriptor externalSCMPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("external-scm-3", externalscm3Jar, false)); GoPluginBundleDescriptor externalPackageMaterialPlugin = new GoPluginBundleDescriptor(getPluginDescriptor("external-package-material-4", externalPackageMaterialJar, false)); when(pluginManager.plugins()).thenReturn(List.of( bundledTaskPlugin.descriptors().get(0), bundledAuthPlugin.descriptors().get(0), bundledSCMPlugin.descriptors().get(0), bundledPackageMaterialPlugin.descriptors().get(0), externalTaskPlugin.descriptors().get(0), externalElasticAgentPlugin.descriptors().get(0), externalSCMPlugin.descriptors().get(0), externalPackageMaterialPlugin.descriptors().get(0) )); when(pluginManager.isPluginOfType("task", "bundled-task-1")).thenReturn(true); when(pluginManager.isPluginOfType("task", "external-task-1")).thenReturn(true); when(pluginManager.isPluginOfType("package-repository", "bundled-package-material-4")).thenReturn(true); when(pluginManager.isPluginOfType("scm", "bundled-scm-3")).thenReturn(true); when(pluginManager.isPluginOfType("scm", "external-scm-3")).thenReturn(true); when(pluginManager.isPluginOfType("package-repository", "external-package-material-4")).thenReturn(true); } @Test void shouldZipTaskPluginsIntoOneZipEveryTime() throws Exception { pluginsZip.create(); assertThat(new File(expectedZipPath).exists()).as(expectedZipPath + " should exist").isTrue(); try (ZipFile zipFile = new ZipFile(expectedZipPath)) { assertThat(zipFile.getEntry("bundled/bundled-task-1.jar")).isNotNull(); assertThat(zipFile.getEntry("bundled/bundled-scm-3.jar")).isNotNull(); assertThat(zipFile.getEntry("bundled/bundled-package-material-4.jar")).isNotNull(); assertThat(zipFile.getEntry("external/external-task-1.jar")).isNotNull(); assertThat(zipFile.getEntry("external/external-scm-3.jar")).isNotNull(); assertThat(zipFile.getEntry("external/external-package-material-4.jar")).isNotNull(); assertThat(zipFile.getEntry("bundled/bundled-auth-2.jar")).isNull(); assertThat(zipFile.getEntry("external/external-elastic-agent-2.jar")).isNull(); } } @Test void shouldGetChecksumIfFileWasCreated() { pluginsZip.create(); String md5 = pluginsZip.md5(); assertThat(md5).isNotNull(); } @Test void shouldUpdateChecksumIfFileIsReCreated() throws Exception { pluginsZip.create(); String oldMd5 = pluginsZip.md5(); FileUtils.writeStringToFile(new File(externalPluginsDir, "external-task-1.jar"), UUID.randomUUID().toString(), UTF_8); pluginsZip.create(); assertThat(pluginsZip.md5()).isNotEqualTo(oldMd5); } @Test void shouldFailGracefullyWhenExternalFileCannotBeRead() throws Exception { File bundledPluginsDir = temporaryFolder.newFolder("plugins-bundled-ext"); SystemEnvironment systemEnvironmentFail = mock(SystemEnvironment.class); when(systemEnvironmentFail.get(PLUGIN_GO_PROVIDED_PATH)).thenReturn(bundledPluginsDir.getAbsolutePath()); when(systemEnvironmentFail.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(""); when(systemEnvironmentFail.get(ALL_PLUGINS_ZIP_PATH)).thenReturn(""); FileUtils.writeStringToFile(new File(bundledPluginsDir, "bundled-task-1.jar"), "Bundled1", UTF_8); PluginsZip pluginsZipFail = new PluginsZip(systemEnvironmentFail, pluginManager); assertThatCode(pluginsZipFail::create) .isInstanceOf(FileAccessRightsCheckException.class); } @Test void shouldFailGracefullyWhenBundledFileCannotBeRead() throws Exception { SystemEnvironment systemEnvironmentFail = mock(SystemEnvironment.class); when(systemEnvironmentFail.get(PLUGIN_GO_PROVIDED_PATH)).thenReturn(""); when(systemEnvironmentFail.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(externalPluginsDir.getAbsolutePath()); when(systemEnvironmentFail.get(ALL_PLUGINS_ZIP_PATH)).thenReturn(""); FileUtils.writeStringToFile(new File(externalPluginsDir, "external-task-1.jar"), "External1", UTF_8); PluginsZip pluginsZipFail = new PluginsZip(systemEnvironmentFail, pluginManager); assertThatCode(pluginsZipFail::create) .isInstanceOf(FileAccessRightsCheckException.class); } @Test void fileAccessErrorShouldContainPathToTheFolderInWhichTheErrorOccurred() throws Exception { SystemEnvironment systemEnvironmentFail = mock(SystemEnvironment.class); when(systemEnvironmentFail.get(PLUGIN_GO_PROVIDED_PATH)).thenReturn("/dummy"); when(systemEnvironmentFail.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(externalPluginsDir.getAbsolutePath()); when(systemEnvironmentFail.get(ALL_PLUGINS_ZIP_PATH)).thenReturn(""); FileUtils.writeStringToFile(new File(externalPluginsDir, "external-task-1.jar"), "External1", UTF_8); PluginsZip pluginsZipFail = new PluginsZip(systemEnvironmentFail, pluginManager); assertThatCode(pluginsZipFail::create) .isInstanceOf(FileAccessRightsCheckException.class) .hasMessageContaining("dummy"); } @Test void shouldCreatePluginsWhenTaskPluginsAreAdded() { GoPluginDescriptor plugin = GoPluginDescriptor.builder().id("curl-task-plugin").build(); when(pluginManager.isPluginOfType("task", plugin.id())).thenReturn(true); pluginsZip.pluginLoaded(plugin); verify(pluginsZip, times(1)).create(); } @Test void shouldCreatePluginsWhenTaskPluginsAreRemoved() { pluginsZip.pluginUnLoaded(externalTaskPlugin.descriptors().get(0)); verify(pluginsZip, times(1)).create(); } @Test void shouldDoNothingWhenAPluginThatIsNotATaskOrScmOrPackageMaterialPluginPluginIsAdded() { pluginsZip.pluginLoaded(externalElasticAgentPlugin.descriptors().get(0)); verify(pluginsZip, never()).create(); } @Test void shouldDoNothingWhenAPluginThatIsNotATaskOrScmOrPackageMaterialPluginPluginIsRemoved() { pluginsZip.pluginUnLoaded(externalElasticAgentPlugin.descriptors().get(0)); verify(pluginsZip, never()).create(); } @Test void shouldCreateAZipWithOneCopyOfEachJar_ForAPluginBundleWithMultiplePluginsInIt() throws IOException { File bundledPluginJarLocation = createPluginFile(bundledPluginsDir, "bundled-multi-plugin-1.jar", "Bundled1"); File externalPluginJarLocation = createPluginFile(externalPluginsDir, "external-multi-plugin-1.jar", "External1"); bundledTaskPlugin = new GoPluginBundleDescriptor( getPluginDescriptor("bundled-plugin-1", bundledPluginJarLocation, true), getPluginDescriptor("bundled-plugin-2", bundledPluginJarLocation, true) ); externalTaskPlugin = new GoPluginBundleDescriptor( getPluginDescriptor("external-plugin-1", externalPluginJarLocation, false), getPluginDescriptor("external-plugin-2", externalPluginJarLocation, false) ); when(pluginManager.plugins()).thenReturn(Arrays.asList( bundledTaskPlugin.descriptors().get(0), bundledTaskPlugin.descriptors().get(1), externalTaskPlugin.descriptors().get(0), externalTaskPlugin.descriptors().get(1) )); when(pluginManager.isPluginOfType("task", "bundled-plugin-1")).thenReturn(true); when(pluginManager.isPluginOfType("scm", "bundled-plugin-2")).thenReturn(true); when(pluginManager.isPluginOfType("task", "external-plugin-1")).thenReturn(true); when(pluginManager.isPluginOfType("artifact", "external-plugin-2")).thenReturn(true); pluginsZip = spy(new PluginsZip(systemEnvironment, pluginManager)); pluginsZip.create(); try (ZipFile zipFile = new ZipFile(expectedZipPath)) { assertThat(new File(expectedZipPath).exists()).as(expectedZipPath + " should exist").isTrue(); assertThat(EnumerationUtils.toList(zipFile.entries()).size()).isEqualTo(2); assertThat(zipFile.getEntry("bundled/bundled-multi-plugin-1.jar")).isNotNull(); assertThat(zipFile.getEntry("external/external-multi-plugin-1.jar")).isNotNull(); } } private GoPluginDescriptor getPluginDescriptor(String id, File jarFileLocation, boolean bundledPlugin) { return GoPluginDescriptor.builder() .id(id) .version("1.0") .isBundledPlugin(bundledPlugin) .pluginJarFileLocation(jarFileLocation.getAbsolutePath()) .build(); } private File createPluginFile(File pluginsDir, String pluginJarFileName, String contents) throws IOException { File bundledTask1Jar = new File(pluginsDir, pluginJarFileName); FileUtils.writeStringToFile(bundledTask1Jar, contents, UTF_8); return bundledTask1Jar; } }
apache-2.0
Epi-Info/Epi-Info-Android
src/main/java/gov/cdc/epiinfo/interpreter/functions/Rule_Minute.java
1039
package gov.cdc.epiinfo.interpreter.functions; import gov.cdc.epiinfo.interpreter.EnterRule; import gov.cdc.epiinfo.interpreter.Rule_Context; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.creativewidgetworks.goldparser.engine.Reduction; public class Rule_Minute extends EnterRule { private List<EnterRule> ParameterList = new ArrayList<EnterRule>(); public Rule_Minute(Rule_Context pContext, Reduction pToken) { super(pContext); this.ParameterList = EnterRule.GetFunctionParameters(pContext, pToken); } /// <summary> /// Executes the reduction. /// </summary> /// <returns>Returns the date difference in years between two dates.</returns> @Override public Object Execute() { Object result = null; Object p1 = this.ParameterList.get(0).Execute(); if (p1 instanceof Date) { Date param1 = (Date)p1; result = param1.getMinutes(); } return result; } }
apache-2.0
lmjacksoniii/hazelcast
hazelcast/src/test/java/com/hazelcast/internal/diagnostics/DiagnosticsLogTest.java
6099
package com.hazelcast.internal.diagnostics; import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.instance.Node; import com.hazelcast.internal.metrics.LongProbeFunction; import com.hazelcast.internal.metrics.MetricsRegistry; import com.hazelcast.internal.metrics.ProbeLevel; import com.hazelcast.spi.impl.NodeEngineImpl; import com.hazelcast.spi.properties.HazelcastProperties; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.QuickTest; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.List; import static com.hazelcast.nio.IOUtil.deleteQuietly; import static com.hazelcast.util.StringUtil.LINE_SEPARATOR; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class DiagnosticsLogTest extends HazelcastTestSupport { private DiagnosticsLogFile diagnosticsLogFile; private MetricsRegistry metricsRegistry; @Before public void setup() { Config config = new Config() .setProperty(Diagnostics.ENABLED.getName(), "true") .setProperty(Diagnostics.MAX_ROLLED_FILE_SIZE_MB.getName(), "0.2") .setProperty(Diagnostics.MAX_ROLLED_FILE_COUNT.getName(), "3") .setProperty(MetricsPlugin.PERIOD_SECONDS.getName(), "1"); HazelcastInstance hz = createHazelcastInstance(config); Diagnostics diagnostics = getDiagnostics(hz); diagnosticsLogFile = diagnostics.diagnosticsLogFile; metricsRegistry = getMetricsRegistry(hz); } @AfterClass public static void afterClass() { String userDir = System.getProperty("user.dir"); File[] files = new File(userDir).listFiles(); if (files != null) { for (File file : files) { String name = file.getName(); if (name.startsWith("diagnostics-") && name.endsWith(".log")) { deleteQuietly(file); } } } } @Test public void testDisabledByDefault() { HazelcastProperties hazelcastProperties = new HazelcastProperties(new Config()); assertFalse(hazelcastProperties.getBoolean(Diagnostics.ENABLED)); } @Test public void testRollover() { String id = generateRandomString(10000); final List<File> files = new LinkedList<File>(); LongProbeFunction f = new LongProbeFunction() { @Override public long get(Object source) throws Exception { return 0; } }; for (int k = 0; k < 10; k++) { metricsRegistry.register(this, id + k, ProbeLevel.MANDATORY, f); } // we run for some time to make sure we get enough rollovers. while (files.size() < 3) { final File file = diagnosticsLogFile.file; if (file != null) { if (!files.contains(file)) { files.add(file); } assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertExist(file); } }); } sleepMillis(100); } // eventually all these files should be gone. assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { for (File file : files) { assertNotExist(file); } } }); } private static void assertNotExist(File file) { assertFalse("file:" + file + " should not exist", file.exists()); } private static void assertExist(File file) { assertTrue("file:" + file + " should exist", file.exists()); } @Test public void test() throws InterruptedException { assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { String content = loadLogfile(); assertNotNull(content); assertContains(content, "SystemProperties["); assertContains(content, "BuildInfo["); assertContains(content, "ConfigProperties["); assertContains(content, "Metrics["); } }); } private String loadLogfile() { File file = diagnosticsLogFile.file; if (file == null || !file.exists()) { return null; } try { BufferedReader br = new BufferedReader(new FileReader(file)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(LINE_SEPARATOR); line = br.readLine(); } return sb.toString(); } finally { br.close(); } } catch (IOException e) { throw new RuntimeException(e); } } public Diagnostics getDiagnostics(HazelcastInstance hazelcastInstance) { Node node = getNode(hazelcastInstance); NodeEngineImpl nodeEngine = node.nodeEngine; try { Field field = NodeEngineImpl.class.getDeclaredField("diagnostics"); field.setAccessible(true); return (Diagnostics) field.get(nodeEngine); } catch (Exception e) { throw new RuntimeException(e); } } }
apache-2.0
mohideen/fcrepo-camel-toolbox
fcrepo-indexing-solr/src/test/java/org/fcrepo/camel/indexing/solr/integration/RouteDeleteIT.java
8298
/* * Copyright 2016 DuraSpace, 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 org.fcrepo.camel.indexing.solr.integration; import static com.jayway.awaitility.Awaitility.await; import static org.fcrepo.camel.RdfNamespaces.REPOSITORY; import static org.hamcrest.Matchers.equalTo; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.camel.EndpointInject; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.apache.camel.util.ObjectHelper; import org.fcrepo.camel.JmsHeaders; import org.fcrepo.client.FcrepoClient; import org.fcrepo.camel.FcrepoHeaders; import org.fcrepo.client.FcrepoResponse; import org.fcrepo.camel.indexing.solr.SolrRouter; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Test the route workflow. * * @author Aaron Coburn * @since 2015-04-10 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/spring-test/test-container.xml"}) public class RouteDeleteIT extends CamelTestSupport { @EndpointInject(uri = "mock:result") protected MockEndpoint resultEndpoint; @Produce(uri = "direct:start") protected ProducerTemplate template; private String fullPath = ""; @Override protected void doPreSetup() throws Exception { final String webPort = System.getProperty("fcrepo.dynamic.test.port", "8080"); final String jettyPort = System.getProperty("jetty.dynamic.test.port", "8080"); final FcrepoClient client = new FcrepoClient(null, null, null, true); final FcrepoResponse res = client.post( URI.create("http://localhost:" + webPort + "/rest"), ObjectHelper.loadResourceAsStream("indexable.ttl"), "text/turtle"); fullPath = res.getLocation().toString(); TestUtils.httpPost("http://localhost:" + jettyPort + "/solr/testCore/update?commit=true", "<delete><query>*:*</query></delete>", "application/xml"); final String solrDoc = "[{\"id\":[\"" + fullPath + "\"]}]"; TestUtils.httpPost("http://localhost:" + jettyPort + "/solr/testCore/update?commit=true", solrDoc, "application/json"); } @Override public boolean isUseAdviceWith() { return true; } @Override protected RouteBuilder createRouteBuilder() { return new SolrRouter(); } @Override protected Properties useOverridePropertiesWithPropertiesComponent() { final String webPort = System.getProperty("fcrepo.dynamic.test.port", "8080"); final String jettyPort = System.getProperty("jetty.dynamic.test.port", "8080"); final String jmsPort = System.getProperty("fcrepo.dynamic.jms.port", "61616"); final Properties props = new Properties(); props.put("indexing.predicate", "true"); props.put("error.maxRedeliveries", "10"); props.put("indexing.predicate", "true"); props.put("fcrepo.baseUrl", "localhost:" + webPort + "/rest"); props.put("fcrepo.defaultTransform", "default"); props.put("solr.baseUrl", "http4:localhost:" + jettyPort + "/solr/testCore"); props.put("solr.commitWithin", "100"); props.put("input.stream", "direct:start"); props.put("solr.reindex.stream", "seda:reindex"); props.put("audit.container", "/audit"); return props; } @Test public void testDeletedJmsEventRouter() throws Exception { final String jettyPort = System.getProperty("jetty.dynamic.test.port", "8080"); final String webPort = System.getProperty("fcrepo.dynamic.test.port", "8080"); final String jmsPort = System.getProperty("fcrepo.dynamic.jms.port", "61616"); final String path = fullPath.replaceFirst("http://localhost:[0-9]+/rest", ""); final String solrEndpoint = "mock:http4:localhost:" + jettyPort + "/solr/testCore/update"; final String fcrepoEndpoint = "mock:fcrepo:localhost:" + webPort + "/rest"; final String url = "http://localhost:" + jettyPort + "/solr/testCore/select?q=*&wt=json"; context.getRouteDefinition("FcrepoSolrRouter").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { mockEndpoints("*"); } }); context.getRouteDefinition("FcrepoSolrDeleter").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { mockEndpoints("*"); } }); context.start(); final Map<String, Object> headers = new HashMap<>(); headers.put(JmsHeaders.IDENTIFIER, path); headers.put(JmsHeaders.BASE_URL, "http://localhost:" + webPort + "/rest"); headers.put(JmsHeaders.EVENT_TYPE, REPOSITORY + "NODE_REMOVED"); headers.put(JmsHeaders.TIMESTAMP, 1428360320168L); headers.put(JmsHeaders.PROPERTIES, ""); getMockEndpoint(solrEndpoint).expectedMessageCount(1); getMockEndpoint("mock://direct:delete.solr").expectedMessageCount(1); getMockEndpoint("mock://direct:update.solr").expectedMessageCount(0); getMockEndpoint(fcrepoEndpoint).expectedMessageCount(0); template.sendBodyAndHeaders("direct:start", "", headers); assertMockEndpointsSatisfied(); await().until(TestUtils.solrCount(url), equalTo(0)); } @Test public void testDeletedInternalEventRouter() throws Exception { final String webPort = System.getProperty("fcrepo.dynamic.test.port", "8080"); final String jettyPort = System.getProperty("jetty.dynamic.test.port", "8080"); final String jmsPort = System.getProperty("fcrepo.dynamic.jms.port", "61616"); final String path = fullPath.replaceFirst("http://localhost:[0-9]+/rest", ""); final String solrEndpoint = "mock:http4:localhost:" + jettyPort + "/solr/testCore/update"; final String fcrepoEndpoint = "mock:fcrepo:localhost:" + webPort + "/rest"; final String url = "http://localhost:" + jettyPort + "/solr/testCore/select?q=*&wt=json"; context.getRouteDefinition("FcrepoSolrRouter").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { mockEndpoints("*"); } }); context.getRouteDefinition("FcrepoSolrDeleter").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { mockEndpoints("*"); } }); context.start(); final Map<String, Object> headers = new HashMap<>(); headers.put(FcrepoHeaders.FCREPO_IDENTIFIER, path); headers.put(FcrepoHeaders.FCREPO_BASE_URL, "http://localhost:" + webPort + "/rest"); headers.put(JmsHeaders.EVENT_TYPE, REPOSITORY + "NODE_REMOVED"); getMockEndpoint(solrEndpoint).expectedMessageCount(1); getMockEndpoint("mock://direct:delete.solr").expectedMessageCount(1); getMockEndpoint("mock://direct:update.solr").expectedMessageCount(0); getMockEndpoint(fcrepoEndpoint).expectedMessageCount(0); template.sendBodyAndHeaders("direct:start", "", headers); assertMockEndpointsSatisfied(); await().until(TestUtils.solrCount(url), equalTo(0)); } }
apache-2.0
Joshua-Chin/SchemingBat
datatypes/Atom.java
670
package datatypes; import java.util.List; import main.Environment; /** * * @author Joshua * * *Atom is the simplest expression, representing a single object */ public class Atom extends Expression { private final Object o; public String linenumber=""; public Atom(Object obj) { o = obj; } @Override public Atom simplify(Environment e) { return this; } public Object value() { return o; } @Override public String toString() { if(o==null){ return ""; }else if(o instanceof List){ return o.toString().replaceAll(",", ""); }else{ return o.toString(); } } @Override public String linenumber() { return linenumber; } }
apache-2.0
markus1978/emf-fragments
de.hub.emffrag.testmodels/gen-src/de/hub/emffrag/testmodels/testmodel/frag/impl/TestObjectIndexImpl.java
1732
/** * Copyright 2012 Markus Scheidgen * * 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 de.hub.emffrag.testmodels.testmodel.frag.impl; import org.eclipse.emf.ecore.EClass; import de.hub.emffrag.datastore.KeyType; import de.hub.emffrag.datastore.StringKeyType; import de.hub.emffrag.model.emffrag.impl.IndexedMapImpl; import de.hub.emffrag.testmodels.testmodel.TestObject; import de.hub.emffrag.testmodels.testmodel.TestObjectIndex; import de.hub.emffrag.testmodels.testmodel.frag.meta.TestModelPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Test Object Index</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class TestObjectIndexImpl extends IndexedMapImpl<String, TestObject> implements TestObjectIndex { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TestObjectIndexImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TestModelPackage.Literals.TEST_OBJECT_INDEX; } @Override public KeyType<String> getKeytype() { return StringKeyType.instance; } } //TestObjectIndexImpl
apache-2.0
markosbg/debug
rabix-bindings-cwl/src/main/java/org/rabix/bindings/cwl/processor/callback/CWLFilePropertiesProcessorCallback.java
4004
package org.rabix.bindings.cwl.processor.callback; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.rabix.bindings.cwl.CWLProcessor; import org.rabix.bindings.cwl.expression.CWLExpressionException; import org.rabix.bindings.cwl.helper.CWLDirectoryValueHelper; import org.rabix.bindings.cwl.helper.CWLFileValueHelper; import org.rabix.bindings.cwl.helper.CWLSchemaHelper; import org.rabix.bindings.cwl.processor.CWLPortProcessorCallback; import org.rabix.bindings.cwl.processor.CWLPortProcessorResult; import org.rabix.bindings.model.ApplicationPort; import org.rabix.common.helper.CloneHelper; public class CWLFilePropertiesProcessorCallback implements CWLPortProcessorCallback { @Override public CWLPortProcessorResult process(Object value, ApplicationPort port) throws Exception { if (CWLSchemaHelper.isFileFromValue(value) || CWLSchemaHelper.isDirectoryFromValue(value)) { Object clonedValue = CloneHelper.deepCopy(value); String path = CWLFileValueHelper.getPath(clonedValue); File file = new File(path); CWLFileValueHelper.setSize(file.length(), clonedValue); CWLFileValueHelper.setName(file.getName(), clonedValue); int dotIndex = file.getName().lastIndexOf("."); if (dotIndex != -1) { CWLFileValueHelper.setNameext(file.getName().substring(dotIndex), clonedValue); CWLFileValueHelper.setNameroot(file.getName().substring(0, dotIndex), clonedValue); } CWLFileValueHelper.setDirname(file.getParentFile().getAbsolutePath(), clonedValue); List<Map<String, Object>> secondaryFiles = CWLFileValueHelper.getSecondaryFiles(clonedValue); if (secondaryFiles != null) { for (Map<String, Object> secondaryFileValue : secondaryFiles) { String secondaryFilePath = CWLFileValueHelper.getPath(secondaryFileValue); CWLFileValueHelper.setSize(new File(secondaryFilePath).length(), secondaryFileValue); } } if (CWLSchemaHelper.isDirectoryFromValue(clonedValue)) { List<Object> listing = new ArrayList<>(); File[] list = file.listFiles(); if(list != null) { for (File childFile : file.listFiles()) { listing.add(formFileValue(childFile)); } } CWLDirectoryValueHelper.setListing(listing, clonedValue); } return new CWLPortProcessorResult(clonedValue, true); } return new CWLPortProcessorResult(value, false); } public Map<String, Object> formFileValue(File file) throws CWLExpressionException, IOException { if (file.isDirectory()) { Map<String, Object> directory = new HashMap<>(); CWLDirectoryValueHelper.setDirectoryType(directory); CWLDirectoryValueHelper.setSize(file.length(), directory); CWLDirectoryValueHelper.setName(file.getName(), directory); CWLDirectoryValueHelper.setPath(file.getAbsolutePath(), directory); File[] list = file.listFiles(); List<Object> listing = new ArrayList<>(); for (File subfile : list) { switch (subfile.getName()) { case CWLProcessor.JOB_FILE: case CWLProcessor.RESULT_FILENAME: case CWLProcessor.RESERVED_EXECUTOR_CMD_LOG_FILE_NAME: case CWLProcessor.RESERVED_EXECUTOR_ERROR_LOG_FILE_NAME: continue; default: break; } listing.add(formFileValue(subfile)); } CWLDirectoryValueHelper.setListing(listing, directory); return directory; } Map<String, Object> fileData = new HashMap<>(); CWLFileValueHelper.setFileType(fileData); CWLFileValueHelper.setSize(file.length(), fileData); CWLFileValueHelper.setName(file.getName(), fileData); CWLFileValueHelper.setDirname(file.getParentFile().getAbsolutePath(), fileData); CWLFileValueHelper.setPath(file.getAbsolutePath(), fileData); return fileData; } }
apache-2.0
whyDK37/pinenut
storage/src/test/java/mc/memcached/UnitTests.java
12156
/** * Copyright (c) 2008 Greg Whalin * All rights reserved. * <p> * This library is free software; you can redistribute it and/or * modify it under the terms of the BSD license * <p> * This library 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. * <p> * You should have received a copy of the BSD License along with this * library. * * @author Kevin Burton * @author greg whalin <greg@meetup.com> */ package mc.memcached; import com.meetup.memcached.Logger; import com.meetup.memcached.MemcachedClient; import com.meetup.memcached.SockIOPool; import java.io.Serializable; import java.util.Arrays; import java.util.Date; import java.util.Map; public class UnitTests { // logger private static Logger log = Logger.getLogger(UnitTests.class.getName()); public static MemcachedClient mc = null; /** * This runs through some simple tests of the MemcacheClient. * <p> * Command line args: * args[0] = number of threads to spawn * args[1] = number of runs per jdk.thread * args[2] = size of object to store * * @param args the command line arguments */ public static void main(String[] args) { if (!UnitTests.class.desiredAssertionStatus()) { System.err.println("WARNING: assertions are disabled!"); try { Thread.sleep(3000); } catch (InterruptedException e) { } } String[] serverlist = { "172.16.170.128:11211", // "192.168.1.50:1621", // "192.168.1.50:1622", // "192.168.1.50:1623", // "192.168.1.50:1624", // "192.168.1.50:1625", // "192.168.1.50:1626", // "192.168.1.50:1627", // "192.168.1.50:1628", // "192.168.1.50:1629" }; Integer[] weights = {1, 1, 1, 1, 10, 5, 1, 1, 1, 3}; if (args.length > 0) serverlist = args; // initialize the pool for memcache servers SockIOPool pool = SockIOPool.getInstance("test"); pool.setServers(serverlist); pool.setWeights(weights); pool.setMaxConn(250); pool.setNagle(false); pool.setHashingAlg(SockIOPool.CONSISTENT_HASH); pool.initialize(); mc = new MemcachedClient("test"); runAlTests(mc); } public static void runAlTests(MemcachedClient mc) { test14(); for (int t = 0; t < 2; t++) { mc.setCompressEnable((t & 1) == 1); // test1(); // test2(); // test3(); // test4(); // test5(); // test6(); // test7(); // test8(); // test9(); // test10(); test11(); test12(); // test13(); // test15(); // test16(); // test17(); // test21(); // test22(); test23(); // test24(); // // for ( int i = 0; i < 3; i++ ) // test19(); // // test20( 8191, 1, 0 ); // test20( 8192, 1, 0 ); // test20( 8193, 1, 0 ); // // test20( 16384, 100, 0 ); // test20( 17000, 128, 0 ); // // test20( 128*1024, 1023, 0 ); // test20( 128*1024, 1023, 1 ); // test20( 128*1024, 1024, 0 ); // test20( 128*1024, 1024, 1 ); // // test20( 128*1024, 1023, 0 ); // test20( 128*1024, 1023, 1 ); // test20( 128*1024, 1024, 0 ); // test20( 128*1024, 1024, 1 ); // // test20( 900*1024, 32*1024, 0 ); // test20( 900*1024, 32*1024, 1 ); } } public static void test1() { mc.set("foo", Boolean.TRUE); Boolean b = (Boolean) mc.get("foo"); assert b.booleanValue(); log.error("+ store/retrieve Boolean type test passed"); } public static void test2() { mc.set("foo", new Integer(Integer.MAX_VALUE)); Integer i = (Integer) mc.get("foo"); assert i.intValue() == Integer.MAX_VALUE; log.error("+ store/retrieve Integer type test passed"); } public static void test3() { String input = "test of string encoding"; mc.set("foo", input); String s = (String) mc.get("foo"); assert s.equals(input); log.error("+ store/retrieve String type test passed"); } public static void test4() { mc.set("foo", new Character('z')); Character c = (Character) mc.get("foo"); assert c.charValue() == 'z'; log.error("+ store/retrieve Character type test passed"); } public static void test5() { mc.set("foo", new Byte((byte) 127)); Byte b = (Byte) mc.get("foo"); assert b.byteValue() == 127; log.error("+ store/retrieve Byte type test passed"); } public static void test6() { mc.set("foo", new StringBuffer("hello")); StringBuffer o = (StringBuffer) mc.get("foo"); assert o.toString().equals("hello"); log.error("+ store/retrieve StringBuffer type test passed"); } public static void test7() { mc.set("foo", new Short((short) 100)); Short o = (Short) mc.get("foo"); assert o.shortValue() == 100; log.error("+ store/retrieve Short type test passed"); } public static void test8() { mc.set("foo", new Long(Long.MAX_VALUE)); Long o = (Long) mc.get("foo"); assert o.longValue() == Long.MAX_VALUE; log.error("+ store/retrieve Long type test passed"); } public static void test9() { mc.set("foo", new Double(1.1)); Double o = (Double) mc.get("foo"); assert o.doubleValue() == 1.1; log.error("+ store/retrieve Double type test passed"); } public static void test10() { mc.set("foo", new Float(1.1f)); Float o = (Float) mc.get("foo"); assert o.floatValue() == 1.1f; log.error("+ store/retrieve Float type test passed"); } public static void test11() { mc.set("foo", new Integer(100), new Date(System.currentTimeMillis())); try { Thread.sleep(1000); } catch (Exception ex) { } assert mc.get("foo") == null; log.error("+ store/retrieve w/ expiration test passed"); } public static void test12() { long i = 0; mc.storeCounter("foo", i); mc.incr("foo"); // foo now == 1 mc.incr("foo", (long) 5); // foo now == 6 long j = mc.decr("foo", (long) 2); // foo now == 4 assert j == 4; assert j == mc.getCounter("foo"); log.error("+ incr/decr test passed"); } public static void test13() { Date d1 = new Date(); mc.set("foo", d1); Date d2 = (Date) mc.get("foo"); assert d1.equals(d2); log.error("+ store/retrieve Date type test passed"); } public static void test14() { assert !mc.keyExists("foobar123"); mc.set("foobar123", new Integer(100000)); assert mc.keyExists("foobar123"); log.error("+ store/retrieve test passed"); assert !mc.keyExists("counterTest123"); mc.storeCounter("counterTest123", 0); assert mc.keyExists("counterTest123"); log.error("+ counter store test passed"); } public static void test15() { Map stats = mc.statsItems(); assert stats != null; stats = mc.statsSlabs(); assert stats != null; log.error("+ stats test passed"); } public static void test16() { assert !mc.set("foo", null); log.error("+ invalid data store [null] test passed"); } public static void test17() { mc.set("foo bar", Boolean.TRUE); Boolean b = (Boolean) mc.get("foo bar"); assert b.booleanValue(); log.error("+ store/retrieve Boolean type test passed"); } public static void test18() { long i = 0; mc.addOrIncr("foo"); // foo now == 0 mc.incr("foo"); // foo now == 1 mc.incr("foo", (long) 5); // foo now == 6 mc.addOrIncr("foo"); // foo now 7 long j = mc.decr("foo", (long) 3); // foo now == 4 assert j == 4; assert j == mc.getCounter("foo"); log.error("+ incr/decr test passed"); } public static void test19() { int max = 100; String[] keys = new String[max]; for (int i = 0; i < max; i++) { keys[i] = Integer.toString(i); mc.set(keys[i], "value" + i); } Map<String, Object> results = mc.getMulti(keys); for (int i = 0; i < max; i++) { assert results.get(keys[i]).equals("value" + i); } log.error("+ getMulti test passed"); } public static void test20(int max, int skip, int start) { log.warn(String.format("test 20 starting with start=%5d skip=%5d max=%7d", start, skip, max)); int numEntries = max / skip + 1; String[] keys = new String[numEntries]; byte[][] vals = new byte[numEntries][]; int size = start; for (int i = 0; i < numEntries; i++) { keys[i] = Integer.toString(size); vals[i] = new byte[size + 1]; for (int j = 0; j < size + 1; j++) vals[i][j] = (byte) j; mc.set(keys[i], vals[i]); size += skip; } Map<String, Object> results = mc.getMulti(keys); for (int i = 0; i < numEntries; i++) assert Arrays.equals((byte[]) results.get(keys[i]), vals[i]); log.warn(String.format("test 20 finished with start=%5d skip=%5d max=%7d", start, skip, max)); } public static void test21() { mc.set("foo", new StringBuilder("hello")); StringBuilder o = (StringBuilder) mc.get("foo"); assert o.toString().equals("hello"); log.error("+ store/retrieve StringBuilder type test passed"); } public static void test22() { byte[] b = new byte[10]; for (int i = 0; i < 10; i++) b[i] = (byte) i; mc.set("foo", b); assert Arrays.equals((byte[]) mc.get("foo"), b); log.error("+ store/retrieve byte[] type test passed"); } public static void test23() { TestClass tc = new TestClass("foo", "bar", new Integer(32)); mc.set("foo", tc); assert tc.equals((TestClass) mc.get("foo")); log.error("+ store/retrieve serialized object test passed"); } public static void test24() { String[] allKeys = {"key1", "key2", "key3", "key4", "key5", "key6", "key7"}; String[] setKeys = {"key1", "key3", "key5", "key7"}; for (String key : setKeys) { mc.set(key, key); } Map<String, Object> results = mc.getMulti(allKeys); assert allKeys.length == results.size(); for (String key : setKeys) { String val = (String) results.get(key); assert key.equals(val); } log.error("+ getMulti w/ keys that don't exist test passed"); } /** * Class for testing serializing of objects. * * @author $Author: $ * @version $Revision: $ $Date: $ */ public static final class TestClass implements Serializable { private String field1; private String field2; private Integer field3; public TestClass(String field1, String field2, Integer field3) { this.field1 = field1; this.field2 = field2; this.field3 = field3; } public String getField1() { return this.field1; } public String getField2() { return this.field2; } public Integer getField3() { return this.field3; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TestClass)) return false; TestClass obj = (TestClass) o; return ((this.field1 == obj.getField1() || (this.field1 != null && this.field1.equals(obj.getField1()))) && (this.field2 == obj.getField2() || (this.field2 != null && this.field2.equals(obj.getField2()))) && (this.field3 == obj.getField3() || (this.field3 != null && this.field3.equals(obj.getField3())))); } } }
apache-2.0
CanangTechnologies/grapevine
src/main/java/net/canang/grapevine/client/GrapevineService.java
665
package net.canang.grapevine.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import net.canang.grapevine.client.model.ScoopModel; import java.util.List; /** * @author rafizan.baharum * @since 10/25/13 */ @RemoteServiceRelativePath("grapevineService") public interface GrapevineService extends RemoteService { void save(ScoopModel model) throws RuntimeException; void delete(ScoopModel model) throws RuntimeException; List<ScoopModel> findScoops() throws RuntimeException; List<ScoopModel> findScoops(Float latitude, Float longitude) throws RuntimeException; }
apache-2.0
jflory7/SFHSAPCompSci2015
src/main/java/com/justinwflory/assignments/spring/elevens-lab/Shuffler.java
3508
/** * This class provides a convenient way to test shuffling methods. * SFHS AP Computer Science 2015 */ public class Shuffler { /** * The number of consecutive shuffle steps to be performed in each call * to each sorting procedure. Experiement with different values. */ private static final int SHUFFLE_COUNT = 8; /** * The number of values to fill the values array with. Experiment with different values, * including both even numbers and odd numbers. */ private static final int VALUE_COUNT = 52; /** * Tests shuffling methods. * @param args is not used. */ public static void main(String[] args) { System.out.println("Results of " + SHUFFLE_COUNT + " consecutive perfect shuffles:"); int[] values1 = new int[VALUE_COUNT]; for (int i = 0; i < VALUE_COUNT; i++) { values1[i] = i; } for (int j = 1; j <= SHUFFLE_COUNT; j++) { perfectShuffle(values1); System.out.print(" " + j + ":"); for (int k = 0; k < values1.length; k++) { System.out.print(" " + values1[k]); } System.out.println(); } System.out.println(); System.out.println("Results of " + SHUFFLE_COUNT + " consecutive efficient selection shuffles:"); int[] values2 = new int[VALUE_COUNT]; for (int i = 0; i < VALUE_COUNT; i++) { values2[i] = i; } for (int j = 1; j <= SHUFFLE_COUNT; j++) { selectionShuffle(values2); System.out.print(" " + j + ":"); for (int k = 0; k < values2.length; k++) { System.out.print(" " + values2[k]); } System.out.println(); } System.out.println(); } /** * Apply a "perfect shuffle" to the argument. * The perfect shuffle algorithm splits the deck in half, then interleaves * the cards in one half with the cards in the other. * @param values is an array of integers simulating cards to be shuffled. */ public static void perfectShuffle(int[] values) { int[] shuffled = new int[VALUE_COUNT]; int indexCount = 0; for (int i=0; i<VALUE_COUNT/2; i++) { shuffled[indexCount] = values[i]; indexCount += 2; } indexCount = 1; for (int i=VALUE_COUNT/2; i<shuffled.length; i++) { if (indexCount == shuffled.length) break; shuffled[indexCount] = values[i]; indexCount += 2; } for (int i=0; i<VALUE_COUNT; i++) { values[i] = shuffled[i]; } } /** * Apply an "efficient selection shuffle" to the argument. * The selection shuffle algorithm conceptually maintains two sequences * of cards: the selected cards (initially empty) and the not-yet-selected * cards (initially the entire deck). It repeatedly does the following until * all cards have been selected: randomly remove a card from those not yet * selected and add it to the selected cards. * An efficient version of this algorithm makes use of arrays to avoid * searching for an as-yet-unselected card. * @param values is an array of integers simulating cards to be shuffled. */ public static void selectionShuffle(int[] values) { int indexCount = VALUE_COUNT - 1; int randomInt; int temp; for (indexCount=indexCount; indexCount>1; indexCount--) { randomInt = (int) (Math.random() * VALUE_COUNT); temp = values[indexCount]; values[indexCount] = values[randomInt]; values[randomInt] = temp; } } }
apache-2.0
XiaoMi/galaxy-sdk-java
galaxy-thrift-api/src/main/thrift-java/com/xiaomi/infra/galaxy/sds/thrift/SLFileMeta.java
19325
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.xiaomi.infra.galaxy.sds.thrift; import libthrift091.scheme.IScheme; import libthrift091.scheme.SchemeFactory; import libthrift091.scheme.StandardScheme; import libthrift091.scheme.TupleScheme; import libthrift091.protocol.TTupleProtocol; import libthrift091.protocol.TProtocolException; import libthrift091.EncodingUtils; import libthrift091.TException; import libthrift091.async.AsyncMethodCallback; import libthrift091.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) /** * SLFile格式存储元信息 */ @Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2019-4-24") public class SLFileMeta implements libthrift091.TBase<SLFileMeta, SLFileMeta._Fields>, java.io.Serializable, Cloneable, Comparable<SLFileMeta> { private static final libthrift091.protocol.TStruct STRUCT_DESC = new libthrift091.protocol.TStruct("SLFileMeta"); private static final libthrift091.protocol.TField TYPE_FIELD_DESC = new libthrift091.protocol.TField("type", libthrift091.protocol.TType.I32, (short)1); private static final libthrift091.protocol.TField DATUM_MAP_META_FIELD_DESC = new libthrift091.protocol.TField("datumMapMeta", libthrift091.protocol.TType.STRUCT, (short)2); private static final libthrift091.protocol.TField RC_BASIC_META_FIELD_DESC = new libthrift091.protocol.TField("rcBasicMeta", libthrift091.protocol.TType.STRUCT, (short)3); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new SLFileMetaStandardSchemeFactory()); schemes.put(TupleScheme.class, new SLFileMetaTupleSchemeFactory()); } /** * * @see SLFileType */ public SLFileType type; // optional public DatumMapMeta datumMapMeta; // optional public RCBasicMeta rcBasicMeta; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements libthrift091.TFieldIdEnum { /** * * @see SLFileType */ TYPE((short)1, "type"), DATUM_MAP_META((short)2, "datumMapMeta"), RC_BASIC_META((short)3, "rcBasicMeta"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // TYPE return TYPE; case 2: // DATUM_MAP_META return DATUM_MAP_META; case 3: // RC_BASIC_META return RC_BASIC_META; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.TYPE,_Fields.DATUM_MAP_META,_Fields.RC_BASIC_META}; public static final Map<_Fields, libthrift091.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, libthrift091.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, libthrift091.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.TYPE, new libthrift091.meta_data.FieldMetaData("type", libthrift091.TFieldRequirementType.OPTIONAL, new libthrift091.meta_data.EnumMetaData(libthrift091.protocol.TType.ENUM, SLFileType.class))); tmpMap.put(_Fields.DATUM_MAP_META, new libthrift091.meta_data.FieldMetaData("datumMapMeta", libthrift091.TFieldRequirementType.OPTIONAL, new libthrift091.meta_data.StructMetaData(libthrift091.protocol.TType.STRUCT, DatumMapMeta.class))); tmpMap.put(_Fields.RC_BASIC_META, new libthrift091.meta_data.FieldMetaData("rcBasicMeta", libthrift091.TFieldRequirementType.OPTIONAL, new libthrift091.meta_data.StructMetaData(libthrift091.protocol.TType.STRUCT, RCBasicMeta.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); libthrift091.meta_data.FieldMetaData.addStructMetaDataMap(SLFileMeta.class, metaDataMap); } public SLFileMeta() { } /** * Performs a deep copy on <i>other</i>. */ public SLFileMeta(SLFileMeta other) { if (other.isSetType()) { this.type = other.type; } if (other.isSetDatumMapMeta()) { this.datumMapMeta = new DatumMapMeta(other.datumMapMeta); } if (other.isSetRcBasicMeta()) { this.rcBasicMeta = new RCBasicMeta(other.rcBasicMeta); } } public SLFileMeta deepCopy() { return new SLFileMeta(this); } @Override public void clear() { this.type = null; this.datumMapMeta = null; this.rcBasicMeta = null; } /** * * @see SLFileType */ public SLFileType getType() { return this.type; } /** * * @see SLFileType */ public SLFileMeta setType(SLFileType type) { this.type = type; return this; } public void unsetType() { this.type = null; } /** Returns true if field type is set (has been assigned a value) and false otherwise */ public boolean isSetType() { return this.type != null; } public void setTypeIsSet(boolean value) { if (!value) { this.type = null; } } public DatumMapMeta getDatumMapMeta() { return this.datumMapMeta; } public SLFileMeta setDatumMapMeta(DatumMapMeta datumMapMeta) { this.datumMapMeta = datumMapMeta; return this; } public void unsetDatumMapMeta() { this.datumMapMeta = null; } /** Returns true if field datumMapMeta is set (has been assigned a value) and false otherwise */ public boolean isSetDatumMapMeta() { return this.datumMapMeta != null; } public void setDatumMapMetaIsSet(boolean value) { if (!value) { this.datumMapMeta = null; } } public RCBasicMeta getRcBasicMeta() { return this.rcBasicMeta; } public SLFileMeta setRcBasicMeta(RCBasicMeta rcBasicMeta) { this.rcBasicMeta = rcBasicMeta; return this; } public void unsetRcBasicMeta() { this.rcBasicMeta = null; } /** Returns true if field rcBasicMeta is set (has been assigned a value) and false otherwise */ public boolean isSetRcBasicMeta() { return this.rcBasicMeta != null; } public void setRcBasicMetaIsSet(boolean value) { if (!value) { this.rcBasicMeta = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case TYPE: if (value == null) { unsetType(); } else { setType((SLFileType)value); } break; case DATUM_MAP_META: if (value == null) { unsetDatumMapMeta(); } else { setDatumMapMeta((DatumMapMeta)value); } break; case RC_BASIC_META: if (value == null) { unsetRcBasicMeta(); } else { setRcBasicMeta((RCBasicMeta)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case TYPE: return getType(); case DATUM_MAP_META: return getDatumMapMeta(); case RC_BASIC_META: return getRcBasicMeta(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case TYPE: return isSetType(); case DATUM_MAP_META: return isSetDatumMapMeta(); case RC_BASIC_META: return isSetRcBasicMeta(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof SLFileMeta) return this.equals((SLFileMeta)that); return false; } public boolean equals(SLFileMeta that) { if (that == null) return false; boolean this_present_type = true && this.isSetType(); boolean that_present_type = true && that.isSetType(); if (this_present_type || that_present_type) { if (!(this_present_type && that_present_type)) return false; if (!this.type.equals(that.type)) return false; } boolean this_present_datumMapMeta = true && this.isSetDatumMapMeta(); boolean that_present_datumMapMeta = true && that.isSetDatumMapMeta(); if (this_present_datumMapMeta || that_present_datumMapMeta) { if (!(this_present_datumMapMeta && that_present_datumMapMeta)) return false; if (!this.datumMapMeta.equals(that.datumMapMeta)) return false; } boolean this_present_rcBasicMeta = true && this.isSetRcBasicMeta(); boolean that_present_rcBasicMeta = true && that.isSetRcBasicMeta(); if (this_present_rcBasicMeta || that_present_rcBasicMeta) { if (!(this_present_rcBasicMeta && that_present_rcBasicMeta)) return false; if (!this.rcBasicMeta.equals(that.rcBasicMeta)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_type = true && (isSetType()); list.add(present_type); if (present_type) list.add(type.getValue()); boolean present_datumMapMeta = true && (isSetDatumMapMeta()); list.add(present_datumMapMeta); if (present_datumMapMeta) list.add(datumMapMeta); boolean present_rcBasicMeta = true && (isSetRcBasicMeta()); list.add(present_rcBasicMeta); if (present_rcBasicMeta) list.add(rcBasicMeta); return list.hashCode(); } @Override public int compareTo(SLFileMeta other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetType()).compareTo(other.isSetType()); if (lastComparison != 0) { return lastComparison; } if (isSetType()) { lastComparison = libthrift091.TBaseHelper.compareTo(this.type, other.type); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDatumMapMeta()).compareTo(other.isSetDatumMapMeta()); if (lastComparison != 0) { return lastComparison; } if (isSetDatumMapMeta()) { lastComparison = libthrift091.TBaseHelper.compareTo(this.datumMapMeta, other.datumMapMeta); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetRcBasicMeta()).compareTo(other.isSetRcBasicMeta()); if (lastComparison != 0) { return lastComparison; } if (isSetRcBasicMeta()) { lastComparison = libthrift091.TBaseHelper.compareTo(this.rcBasicMeta, other.rcBasicMeta); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(libthrift091.protocol.TProtocol iprot) throws libthrift091.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(libthrift091.protocol.TProtocol oprot) throws libthrift091.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("SLFileMeta("); boolean first = true; if (isSetType()) { sb.append("type:"); if (this.type == null) { sb.append("null"); } else { sb.append(this.type); } first = false; } if (isSetDatumMapMeta()) { if (!first) sb.append(", "); sb.append("datumMapMeta:"); if (this.datumMapMeta == null) { sb.append("null"); } else { sb.append(this.datumMapMeta); } first = false; } if (isSetRcBasicMeta()) { if (!first) sb.append(", "); sb.append("rcBasicMeta:"); if (this.rcBasicMeta == null) { sb.append("null"); } else { sb.append(this.rcBasicMeta); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws libthrift091.TException { // check for required fields // check for sub-struct validity if (datumMapMeta != null) { datumMapMeta.validate(); } if (rcBasicMeta != null) { rcBasicMeta.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(out))); } catch (libthrift091.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(in))); } catch (libthrift091.TException te) { throw new java.io.IOException(te); } } private static class SLFileMetaStandardSchemeFactory implements SchemeFactory { public SLFileMetaStandardScheme getScheme() { return new SLFileMetaStandardScheme(); } } private static class SLFileMetaStandardScheme extends StandardScheme<SLFileMeta> { public void read(libthrift091.protocol.TProtocol iprot, SLFileMeta struct) throws libthrift091.TException { libthrift091.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == libthrift091.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // TYPE if (schemeField.type == libthrift091.protocol.TType.I32) { struct.type = com.xiaomi.infra.galaxy.sds.thrift.SLFileType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } else { libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DATUM_MAP_META if (schemeField.type == libthrift091.protocol.TType.STRUCT) { struct.datumMapMeta = new DatumMapMeta(); struct.datumMapMeta.read(iprot); struct.setDatumMapMetaIsSet(true); } else { libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // RC_BASIC_META if (schemeField.type == libthrift091.protocol.TType.STRUCT) { struct.rcBasicMeta = new RCBasicMeta(); struct.rcBasicMeta.read(iprot); struct.setRcBasicMetaIsSet(true); } else { libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(libthrift091.protocol.TProtocol oprot, SLFileMeta struct) throws libthrift091.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.type != null) { if (struct.isSetType()) { oprot.writeFieldBegin(TYPE_FIELD_DESC); oprot.writeI32(struct.type.getValue()); oprot.writeFieldEnd(); } } if (struct.datumMapMeta != null) { if (struct.isSetDatumMapMeta()) { oprot.writeFieldBegin(DATUM_MAP_META_FIELD_DESC); struct.datumMapMeta.write(oprot); oprot.writeFieldEnd(); } } if (struct.rcBasicMeta != null) { if (struct.isSetRcBasicMeta()) { oprot.writeFieldBegin(RC_BASIC_META_FIELD_DESC); struct.rcBasicMeta.write(oprot); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class SLFileMetaTupleSchemeFactory implements SchemeFactory { public SLFileMetaTupleScheme getScheme() { return new SLFileMetaTupleScheme(); } } private static class SLFileMetaTupleScheme extends TupleScheme<SLFileMeta> { @Override public void write(libthrift091.protocol.TProtocol prot, SLFileMeta struct) throws libthrift091.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetType()) { optionals.set(0); } if (struct.isSetDatumMapMeta()) { optionals.set(1); } if (struct.isSetRcBasicMeta()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetType()) { oprot.writeI32(struct.type.getValue()); } if (struct.isSetDatumMapMeta()) { struct.datumMapMeta.write(oprot); } if (struct.isSetRcBasicMeta()) { struct.rcBasicMeta.write(oprot); } } @Override public void read(libthrift091.protocol.TProtocol prot, SLFileMeta struct) throws libthrift091.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.type = com.xiaomi.infra.galaxy.sds.thrift.SLFileType.findByValue(iprot.readI32()); struct.setTypeIsSet(true); } if (incoming.get(1)) { struct.datumMapMeta = new DatumMapMeta(); struct.datumMapMeta.read(iprot); struct.setDatumMapMetaIsSet(true); } if (incoming.get(2)) { struct.rcBasicMeta = new RCBasicMeta(); struct.rcBasicMeta.read(iprot); struct.setRcBasicMetaIsSet(true); } } } }
apache-2.0
killbill/killbill-api
src/main/java/org/killbill/billing/catalog/api/Usage.java
1965
/* * Copyright 2014 The Billing Project, LLC * * The Billing Project 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.killbill.billing.catalog.api; public interface Usage extends CatalogEntity { public StaticCatalog getCatalog(); /** * @return the {@code BillingMode} */ public BillingMode getBillingMode(); /** * @return the {@code UsageType} */ public UsageType getUsageType(); /** * * @return the {@code TierBlockPolicy} */ public TierBlockPolicy getTierBlockPolicy(); /** * @return @return the {@code BillingPeriod} */ public BillingPeriod getBillingPeriod(); /** * @return compliance boolean */ public boolean compliesWithLimits(String unit, double value); /** * @return the {@code Limit} associated with that usage section */ public Limit[] getLimits(); /** * @return the {@code Tier} associated with that usage section */ public Tier[] getTiers(); /** * @return the {@code Block} associated with that usage section */ public Block[] getBlocks(); /** * @return the fixed {@code InternationalPrice} for that {@code Usage} section. */ public InternationalPrice getFixedPrice(); /** * @return the recurring {@code InternationalPrice} for that {@code Usage} section. */ public InternationalPrice getRecurringPrice(); }
apache-2.0
spring-projects/spring-framework
spring-context/src/test/java/org/springframework/context/annotation/Spr16217Tests.java
3577
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.core.type.AnnotatedTypeMetadata; /** * @author Andy Wilkinson * @author Juergen Hoeller */ public class Spr16217Tests { @Test @Disabled("TODO") public void baseConfigurationIsIncludedWhenFirstSuperclassReferenceIsSkippedInRegisterBeanPhase() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RegisterBeanPhaseImportingConfiguration.class)) { context.getBean("someBean"); } } @Test public void baseConfigurationIsIncludedWhenFirstSuperclassReferenceIsSkippedInParseConfigurationPhase() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ParseConfigurationPhaseImportingConfiguration.class)) { context.getBean("someBean"); } } @Test public void baseConfigurationIsIncludedOnceWhenBothConfigurationClassesAreActive() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.setAllowBeanDefinitionOverriding(false); context.register(UnconditionalImportingConfiguration.class); context.refresh(); try { context.getBean("someBean"); } finally { context.close(); } } public static class RegisterBeanPhaseCondition implements ConfigurationCondition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return false; } @Override public ConfigurationPhase getConfigurationPhase() { return ConfigurationPhase.REGISTER_BEAN; } } public static class ParseConfigurationPhaseCondition implements ConfigurationCondition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return false; } @Override public ConfigurationPhase getConfigurationPhase() { return ConfigurationPhase.PARSE_CONFIGURATION; } } @Import({RegisterBeanPhaseConditionConfiguration.class, BarConfiguration.class}) public static class RegisterBeanPhaseImportingConfiguration { } @Import({ParseConfigurationPhaseConditionConfiguration.class, BarConfiguration.class}) public static class ParseConfigurationPhaseImportingConfiguration { } @Import({UnconditionalConfiguration.class, BarConfiguration.class}) public static class UnconditionalImportingConfiguration { } public static class BaseConfiguration { @Bean public String someBean() { return "foo"; } } @Conditional(RegisterBeanPhaseCondition.class) public static class RegisterBeanPhaseConditionConfiguration extends BaseConfiguration { } @Conditional(ParseConfigurationPhaseCondition.class) public static class ParseConfigurationPhaseConditionConfiguration extends BaseConfiguration { } public static class UnconditionalConfiguration extends BaseConfiguration { } public static class BarConfiguration extends BaseConfiguration { } }
apache-2.0
KAMP-Research/KAMP4APS
edu.kit.ipd.sdq.kamp4aps.aps/src/edu/kit/ipd/sdq/kamp4aps/model/aPS/InterfaceRepository/TransportConnection.java
458
/** */ package edu.kit.ipd.sdq.kamp4aps.model.aPS.InterfaceRepository; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Transport Connection</b></em>'. * <!-- end-user-doc --> * * * @see edu.kit.ipd.sdq.kamp4aps.model.aPS.InterfaceRepository.InterfaceRepositoryPackage#getTransportConnection() * @model * @generated */ public interface TransportConnection extends Interface { } // TransportConnection
apache-2.0
gawkermedia/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201601/cm/CampaignAdExtensionOperation.java
1707
package com.google.api.ads.adwords.jaxws.v201601.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * CampaignAdExtension service operation. <b>Note:</b> The {@code SET} operator * is not supported. * * * <p>Java class for CampaignAdExtensionOperation complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CampaignAdExtensionOperation"> * &lt;complexContent> * &lt;extension base="{https://adwords.google.com/api/adwords/cm/v201601}Operation"> * &lt;sequence> * &lt;element name="operand" type="{https://adwords.google.com/api/adwords/cm/v201601}CampaignAdExtension" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CampaignAdExtensionOperation", propOrder = { "operand" }) public class CampaignAdExtensionOperation extends Operation { protected CampaignAdExtension operand; /** * Gets the value of the operand property. * * @return * possible object is * {@link CampaignAdExtension } * */ public CampaignAdExtension getOperand() { return operand; } /** * Sets the value of the operand property. * * @param value * allowed object is * {@link CampaignAdExtension } * */ public void setOperand(CampaignAdExtension value) { this.operand = value; } }
apache-2.0
bsmedberg/pig
src/org/apache/pig/data/TypeAwareTuple.java
2535
/* * 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.pig.data; import java.util.Map; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.impl.logicalLayer.schema.Schema; public interface TypeAwareTuple extends Tuple { public void setInt(int idx, int val) throws ExecException; public void setFloat(int idx, float val) throws ExecException; public void setDouble(int idx, double val) throws ExecException; public void setLong(int idx, long val) throws ExecException; public void setString(int idx, String val) throws ExecException; public void setBoolean(int idx, boolean val) throws ExecException; public void setBytes(int idx, byte[] val) throws ExecException; public void setTuple(int idx, Tuple val) throws ExecException; public void setDataBag(int idx, DataBag val) throws ExecException; public void setMap(int idx, Map<String,Object> val) throws ExecException; public int getInt(int idx) throws ExecException, FieldIsNullException; public float getFloat(int idx) throws ExecException, FieldIsNullException; public double getDouble(int idx) throws ExecException, FieldIsNullException; public long getLong(int idx) throws ExecException, FieldIsNullException; public String getString(int idx) throws ExecException, FieldIsNullException; public boolean getBoolean(int idx) throws ExecException, FieldIsNullException; public byte[] getBytes(int idx) throws ExecException, FieldIsNullException; public Tuple getTuple(int idx) throws ExecException; public DataBag getDataBag(int idx) throws ExecException, FieldIsNullException; public Map<String,Object> getMap(int idx) throws ExecException, FieldIsNullException; public Schema getSchema(); }
apache-2.0
tomwhite/set-game
src/main/java/com/tom_e_white/set_game/preprocess/CardImage.java
697
package com.tom_e_white.set_game.preprocess; import georegression.struct.shapes.Quadrilateral_F64; import java.awt.image.BufferedImage; /** * The image of an individual card, along with some geometric information. */ public class CardImage { private final BufferedImage image; private final Quadrilateral_F64 externalQuadrilateral; public CardImage(BufferedImage image, Quadrilateral_F64 externalQuadrilateral) { this.image = image; this.externalQuadrilateral = externalQuadrilateral; } public BufferedImage getImage() { return image; } public Quadrilateral_F64 getExternalQuadrilateral() { return externalQuadrilateral; } }
apache-2.0
wuxinshui/spring-boot-samples
spring-boot-sample-amqp/src/main/java/com/wxs/amqp/AmqpApplication.java
643
package com.wxs.amqp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * Created with IntelliJ IDEA. * User: FujiRen * Date: 2017/9/14 * Time: 10:55 * To change this template use File | Settings | File Templates. */ @SpringBootApplication @ComponentScan(basePackages = "com.wxs.amqp") public class AmqpApplication { public static void main(String[] args) { SpringApplication.run(AmqpApplication.class,args); } }
apache-2.0
LightSun/data-mediator
Data-mediator-demo/app/src/main/java/com/heaven7/data/mediator/demo/testpackage/TestInterface2.java
2702
package com.heaven7.data.mediator.demo.testpackage; import android.os.Parcelable; import com.heaven7.java.data.mediator.Field; import com.heaven7.java.data.mediator.Fields; import com.heaven7.java.data.mediator.ListPropertyEditor; import com.heaven7.java.data.mediator.Property; import com.heaven7.java.data.mediator.internal.SharedProperties; import java.util.List; import static com.heaven7.java.data.mediator.FieldFlags.COMPLEX_ARRAY; import static com.heaven7.java.data.mediator.FieldFlags.COMPLEX_LIST; import static com.heaven7.java.data.mediator.FieldFlags.FLAGS_ALL_SCOPES; /** * Created by heaven7 on 2017/8/29 0029. */ @Fields({ @Field(propName = "student", seriaName = "class_1", type = TestBind.class, flags = FLAGS_ALL_SCOPES), @Field(propName = "student2", seriaName = "class_2", type = TestBind.class, complexType = COMPLEX_LIST, flags = FLAGS_ALL_SCOPES), @Field(propName = "student3", seriaName = "class_3", type = TestBind.class, complexType = COMPLEX_ARRAY, flags = FLAGS_ALL_SCOPES), @Field(propName = "student4", seriaName = "class_4", type = TestBind.class, flags = FLAGS_ALL_SCOPES) }) public interface TestInterface2 extends StudentBind, Parcelable { Property PROP_student = SharedProperties.get("com.heaven7.data.mediator.demo.testpackage.TestBind", "student", 0); Property PROP_student2 = SharedProperties.get("com.heaven7.data.mediator.demo.testpackage.TestBind", "student2", 2); Property PROP_student3 = SharedProperties.get("com.heaven7.data.mediator.demo.testpackage.TestBind", "student3", 1); Property PROP_student4 = SharedProperties.get("com.heaven7.data.mediator.demo.testpackage.TestBind", "student4", 0); TestInterface2 setStudent(TestBind student1); TestBind getStudent(); TestInterface2 setStudent2(List<TestBind> student21); List<TestBind> getStudent2(); ListPropertyEditor<? extends TestInterface2, TestBind> beginStudent2Editor(); TestInterface2 setStudent3(TestBind[] student31); TestBind[] getStudent3(); TestInterface2 setStudent4(TestBind student41); TestBind getStudent4();/* ================== start methods from super properties =============== ======================================================================= */ TestInterface2 setName(String name1); TestInterface2 setTest_object(Object test_object1); TestInterface2 setTest_Format(Double test_Format1); TestInterface2 setTest_int(int test_int1); TestInterface2 setTest_list(List<Long> test_list1); ListPropertyEditor<? extends TestInterface2, Long> beginTest_listEditor(); TestInterface2 setTest_array(String[] test_array1); }
apache-2.0
gmargari/apache-cassandra-1.1.0-src
src/java/org/apache/cassandra/cql3/CFDefinition.java
10967
/* * 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.cassandra.cql3; import java.nio.ByteBuffer; import java.util.*; import com.google.common.collect.AbstractIterator; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.marshal.CompositeType; import org.apache.cassandra.db.marshal.UTF8Type; import org.apache.cassandra.thrift.InvalidRequestException; import org.apache.cassandra.utils.ByteBufferUtil; /** * Holds metadata on a CF preprocessed for use by CQL queries. */ public class CFDefinition implements Iterable<CFDefinition.Name> { public static final AbstractType<?> definitionType = UTF8Type.instance; private static final String DEFAULT_KEY_ALIAS = "key"; private static final String DEFAULT_COLUMN_ALIAS = "column"; private static final String DEFAULT_VALUE_ALIAS = "value"; public final CFMetaData cfm; public final Name key; // LinkedHashMap because the order does matter (it is the order in the composite type) public final LinkedHashMap<ColumnIdentifier, Name> columns = new LinkedHashMap<ColumnIdentifier, Name>(); public final Name value; // Keep metadata lexicographically ordered so that wildcard expansion have a deterministic order public final Map<ColumnIdentifier, Name> metadata = new TreeMap<ColumnIdentifier, Name>(); public final boolean isComposite; public final boolean isCompact; public CFDefinition(CFMetaData cfm) { this.cfm = cfm; this.key = new Name(getKeyId(cfm), Name.Kind.KEY_ALIAS, cfm.getKeyValidator()); if (cfm.comparator instanceof CompositeType) { this.isComposite = true; CompositeType composite = (CompositeType)cfm.comparator; if (cfm.getColumn_metadata().isEmpty()) { // "dense" composite this.isCompact = true; for (int i = 0; i < composite.types.size(); i++) { ColumnIdentifier id = getColumnId(cfm, i); this.columns.put(id, new Name(id, Name.Kind.COLUMN_ALIAS, i, composite.types.get(i))); } this.value = new Name(getValueId(cfm), Name.Kind.VALUE_ALIAS, cfm.getDefaultValidator()); } else { // "sparse" composite this.isCompact = false; this.value = null; assert cfm.getValueAlias() == null; for (int i = 0; i < composite.types.size() - 1; i++) { ColumnIdentifier id = getColumnId(cfm, i); this.columns.put(id, new Name(id, Name.Kind.COLUMN_ALIAS, i, composite.types.get(i))); } for (Map.Entry<ByteBuffer, ColumnDefinition> def : cfm.getColumn_metadata().entrySet()) { ColumnIdentifier id = new ColumnIdentifier(def.getKey()); this.metadata.put(id, new Name(id, Name.Kind.COLUMN_METADATA, def.getValue().getValidator())); } } } else { this.isComposite = false; if (cfm.getColumn_metadata().isEmpty()) { // dynamic CF this.isCompact = true; ColumnIdentifier id = getColumnId(cfm, 0); Name name = new Name(id, Name.Kind.COLUMN_ALIAS, 0, cfm.comparator); this.columns.put(id, name); this.value = new Name(getValueId(cfm), Name.Kind.VALUE_ALIAS, cfm.getDefaultValidator()); } else { // static CF this.isCompact = false; this.value = null; assert cfm.getValueAlias() == null; assert cfm.getColumnAliases() == null || cfm.getColumnAliases().isEmpty(); for (Map.Entry<ByteBuffer, ColumnDefinition> def : cfm.getColumn_metadata().entrySet()) { ColumnIdentifier id = new ColumnIdentifier(def.getKey()); this.metadata.put(id, new Name(id, Name.Kind.COLUMN_METADATA, def.getValue().getValidator())); } } } assert value == null || metadata.isEmpty(); } private static ColumnIdentifier getKeyId(CFMetaData cfm) { return cfm.getKeyAlias() == null ? new ColumnIdentifier(DEFAULT_KEY_ALIAS, false) : new ColumnIdentifier(cfm.getKeyAlias()); } private static ColumnIdentifier getColumnId(CFMetaData cfm, int i) { List<ByteBuffer> definedNames = cfm.getColumnAliases(); return definedNames == null || i >= definedNames.size() ? new ColumnIdentifier(DEFAULT_COLUMN_ALIAS + (i + 1), false) : new ColumnIdentifier(cfm.getColumnAliases().get(i)); } private static ColumnIdentifier getValueId(CFMetaData cfm) { return cfm.getValueAlias() == null ? new ColumnIdentifier(DEFAULT_VALUE_ALIAS, false) : new ColumnIdentifier(cfm.getValueAlias()); } public Name get(ColumnIdentifier name) { if (name.equals(key.name)) return key; if (value != null && name.equals(value.name)) return value; CFDefinition.Name def = columns.get(name); if (def != null) return def; return metadata.get(name); } public Iterator<Name> iterator() { return new AbstractIterator<Name>() { private boolean keyDone; private final Iterator<Name> columnIter = columns.values().iterator(); private boolean valueDone; private final Iterator<Name> metadataIter = metadata.values().iterator(); protected Name computeNext() { if (!keyDone) { keyDone = true; return key; } if (columnIter.hasNext()) return columnIter.next(); if (value != null && !valueDone) { valueDone = true; return value; } if (metadataIter.hasNext()) return metadataIter.next(); return endOfData(); } }; } public ColumnNameBuilder getColumnNameBuilder() { return isComposite ? new CompositeType.Builder((CompositeType)cfm.comparator) : new NonCompositeBuilder(cfm.comparator); } public AbstractType<?> getNameComparatorForResultSet(Name name) { // In the resultSet, a name should always be UTF8. However, for // backward compatibility sake, this method allows to support non UTF8 // names for static CF column names. if (!isCompact && !isComposite) return cfm.comparator; else return definitionType; } public static class Name { public static enum Kind { KEY_ALIAS, COLUMN_ALIAS, VALUE_ALIAS, COLUMN_METADATA } private Name(ColumnIdentifier name, Kind kind, AbstractType<?> type) { this(name, kind, -1, type); } private Name(ColumnIdentifier name, Kind kind, int position, AbstractType<?> type) { this.kind = kind; this.name = name; this.position = position; this.type = type; } public final Kind kind; public final ColumnIdentifier name; public final int position; // only make sense for COLUMN_ALIAS public final AbstractType<?> type; @Override public String toString() { // It is not fully conventional, but it is convenient for error messages to the user return name.toString(); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(key.name); for (Name name : columns.values()) sb.append(", ").append(name.name); sb.append(" => "); if (value != null) sb.append(value.name); if (!metadata.isEmpty()) { sb.append("{"); for (Name name : metadata.values()) sb.append(" ").append(name.name); sb.append(" }"); } sb.append("]"); return sb.toString(); } private static class NonCompositeBuilder implements ColumnNameBuilder { private final AbstractType<?> type; private ByteBuffer columnName; private NonCompositeBuilder(AbstractType<?> type) { this.type = type; } public NonCompositeBuilder add(ByteBuffer bb) { if (columnName != null) throw new IllegalStateException("Column name is already constructed"); columnName = bb; return this; } public NonCompositeBuilder add(Term t, Relation.Type op, List<ByteBuffer> variables) throws InvalidRequestException { if (columnName != null) throw new IllegalStateException("Column name is already constructed"); // We don't support the relation type yet, i.e., there is no distinction between x > 3 and x >= 3. columnName = t.getByteBuffer(type, variables); return this; } public int componentCount() { return columnName == null ? 0 : 1; } public ByteBuffer build() { return columnName == null ? ByteBufferUtil.EMPTY_BYTE_BUFFER : columnName; } public ByteBuffer buildAsEndOfRange() { throw new IllegalStateException(); } public NonCompositeBuilder copy() { NonCompositeBuilder newBuilder = new NonCompositeBuilder(type); newBuilder.columnName = columnName; return newBuilder; } } }
apache-2.0
qobel/esoguproject
spring-framework/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java
2711
/* * Copyright 2002-2013 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.springframework.beans.factory.support; import java.util.Arrays; import junit.framework.TestCase; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson * @author Juergen Hoeller */ public class BeanDefinitionBuilderTests extends TestCase { public void testBeanClassWithSimpleProperty() { String[] dependsOn = new String[] { "A", "B", "C" }; BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class); bdb.setScope(BeanDefinition.SCOPE_PROTOTYPE); bdb.addPropertyReference("age", "15"); for (int i = 0; i < dependsOn.length; i++) { bdb.addDependsOn(dependsOn[i]); } RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); assertFalse(rbd.isSingleton()); assertEquals(TestBean.class, rbd.getBeanClass()); assertTrue("Depends on was added", Arrays.equals(dependsOn, rbd.getDependsOn())); assertTrue(rbd.getPropertyValues().contains("age")); } public void testBeanClassWithFactoryMethod() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class, "create"); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); assertTrue(rbd.hasBeanClass()); assertEquals(TestBean.class, rbd.getBeanClass()); assertEquals("create", rbd.getFactoryMethodName()); } public void testBeanClassName() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName()); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); assertFalse(rbd.hasBeanClass()); assertEquals(TestBean.class.getName(), rbd.getBeanClassName()); } public void testBeanClassNameWithFactoryMethod() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName(), "create"); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); assertFalse(rbd.hasBeanClass()); assertEquals(TestBean.class.getName(), rbd.getBeanClassName()); assertEquals("create", rbd.getFactoryMethodName()); } }
apache-2.0