text
stringlengths
7
1.01M
package com.revature.beans; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "CAT") public class Cat implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "catSequence") @SequenceGenerator(allocationSize = 1, name = "catSequence", sequenceName = "SQ_CAT_PK") @Column(name = "CAT_ID") private int id; @Column(name = "CAT_NAME") private String catName; @Column(name = "CAT_PIC") private String catPic; @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="BREED_ID") private Breed breed; public Cat(int id, String catName, String catPic, Breed breed) { super(); this.id = id; this.catName = catName; this.catPic = catPic; this.breed = breed; } public Cat(String catName, String catPic, Breed breed) { super(); this.catName = catName; this.catPic = catPic; this.breed = breed; } public Cat() { super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } public String getCatPic() { return catPic; } public void setCatPic(String catPic) { this.catPic = catPic; } public Breed getBreed() { return breed; } public void setBreed(Breed breed) { this.breed = breed; } public static long getSerialversionuid() { return serialVersionUID; } @Override public String toString() { return "Cat [id=" + id + ", catName=" + catName + ", catPic=" + catPic + ", breed=" + breed + "]"; } }
/* * Copyright (c) 2014, Yahoo!, 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. See accompanying * LICENSE file. */ package com.yahoo.ycsb.db; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeNoException; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.util.Collections; import java.util.HashMap; import java.util.Set; import java.util.Vector; import org.junit.BeforeClass; import org.junit.Test; import com.yahoo.ycsb.ByteArrayByteIterator; import com.yahoo.ycsb.ByteIterator; import com.yahoo.ycsb.DB; /** * MongoDbClientTest provides runs the basic DB test cases. * <p> * The tests will be skipped if MongoDB is not running on port 27017 on the * local machine. See the README.md for how to get MongoDB running. * </p> */ @SuppressWarnings("boxing") public abstract class AbstractDBTestCases { /** The default port for MongoDB. */ private static final int MONGODB_DEFAULT_PORT = 27017; /** * Verifies the mongod process (or some process) is running on port 27017, * if not the tests are skipped. */ @BeforeClass public static void setUpBeforeClass() { // Test if we can connect. Socket socket = null; try { // Connect socket = new Socket(InetAddress.getLocalHost(), MONGODB_DEFAULT_PORT); assertThat("Socket is not bound.", socket.getLocalPort(), not(-1)); } catch (IOException connectFailed) { assumeNoException("MongoDB is not running. Skipping tests.", connectFailed); } finally { if (socket != null) { try { socket.close(); } catch (IOException ignore) { // Ignore. } } socket = null; } } /** * Test method for {@link DB#insert}, {@link DB#read}, and {@link DB#delete} * . */ @Test public void testInsertReadDelete() { final DB client = getDB(); final String table = "test"; final String id = "delete"; HashMap<String, ByteIterator> inserted = new HashMap<String, ByteIterator>(); inserted.put("a", new ByteArrayByteIterator(new byte[] { 1, 2, 3, 4 })); int result = client.insert(table, id, inserted); assertThat("Insert did not return success (0).", result, is(0)); HashMap<String, ByteIterator> read = new HashMap<String, ByteIterator>(); Set<String> keys = Collections.singleton("a"); result = client.read(table, id, keys, read); assertThat("Read did not return success (0).", result, is(0)); for (String key : keys) { ByteIterator iter = read.get(key); assertThat("Did not read the inserted field: " + key, iter, notNullValue()); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 1))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 2))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 3))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 4))); assertFalse(iter.hasNext()); } result = client.delete(table, id); assertThat("Delete did not return success (0).", result, is(0)); read.clear(); result = client.read(table, id, null, read); assertThat("Read, after delete, did not return not found (1).", result, is(1)); assertThat("Found the deleted fields.", read.size(), is(0)); result = client.delete(table, id); assertThat("Delete did not return not found (1).", result, is(1)); } /** * Test method for {@link DB#insert}, {@link DB#read}, and {@link DB#update} * . */ @Test public void testInsertReadUpdate() { DB client = getDB(); final String table = "test"; final String id = "update"; HashMap<String, ByteIterator> inserted = new HashMap<String, ByteIterator>(); inserted.put("a", new ByteArrayByteIterator(new byte[] { 1, 2, 3, 4 })); int result = client.insert(table, id, inserted); assertThat("Insert did not return success (0).", result, is(0)); HashMap<String, ByteIterator> read = new HashMap<String, ByteIterator>(); Set<String> keys = Collections.singleton("a"); result = client.read(table, id, keys, read); assertThat("Read did not return success (0).", result, is(0)); for (String key : keys) { ByteIterator iter = read.get(key); assertThat("Did not read the inserted field: " + key, iter, notNullValue()); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 1))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 2))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 3))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 4))); assertFalse(iter.hasNext()); } HashMap<String, ByteIterator> updated = new HashMap<String, ByteIterator>(); updated.put("a", new ByteArrayByteIterator(new byte[] { 5, 6, 7, 8 })); result = client.update(table, id, updated); assertThat("Update did not return success (0).", result, is(0)); read.clear(); result = client.read(table, id, null, read); assertThat("Read, after update, did not return success (0).", result, is(0)); for (String key : keys) { ByteIterator iter = read.get(key); assertThat("Did not read the inserted field: " + key, iter, notNullValue()); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 5))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 6))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 7))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) 8))); assertFalse(iter.hasNext()); } } /** * Test method for {@link DB#scan}. */ @Test public void testScan() { final DB client = getDB(); final String table = "test"; // Insert a bunch of documents. for (int i = 0; i < 100; ++i) { HashMap<String, ByteIterator> inserted = new HashMap<String, ByteIterator>(); inserted.put("a", new ByteArrayByteIterator(new byte[] { (byte) (i & 0xFF), (byte) (i >> 8 & 0xFF), (byte) (i >> 16 & 0xFF), (byte) (i >> 24 & 0xFF) })); int result = client.insert(table, padded(i), inserted); assertThat("Insert did not return success (0).", result, is(0)); } Set<String> keys = Collections.singleton("a"); Vector<HashMap<String, ByteIterator>> results = new Vector<HashMap<String, ByteIterator>>(); int result = client.scan(table, "00050", 5, null, results); assertThat("Read did not return success (0).", result, is(0)); assertThat(results.size(), is(5)); for (int i = 0; i < 5; ++i) { HashMap<String, ByteIterator> read = results.get(i); for (String key : keys) { ByteIterator iter = read.get(key); assertThat("Did not read the inserted field: " + key, iter, notNullValue()); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) ((i + 50) & 0xFF)))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) ((i + 50) >> 8 & 0xFF)))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) ((i + 50) >> 16 & 0xFF)))); assertTrue(iter.hasNext()); assertThat(iter.nextByte(), is(Byte.valueOf((byte) ((i + 50) >> 24 & 0xFF)))); assertFalse(iter.hasNext()); } } } /** * Gets the test DB. * * @return The test DB. */ protected abstract DB getDB(); /** * Creates a zero padded integer. * * @param i * The integer to padd. * @return The padded integer. */ private String padded(int i) { String result = String.valueOf(i); while (result.length() < 5) { result = "0" + result; } return result; } }
/** * */ package spelling; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; /** * @author UC San Diego Intermediate MOOC team * */ public class NearbyWords implements SpellingSuggest { // THRESHOLD to determine how many words to look through when looking // for spelling suggestions (stops prohibitively long searching) // For use in the Optional Optimization in Part 2. private static final int THRESHOLD = 1000; Dictionary dict; public NearbyWords (Dictionary dict) { this.dict = dict; } /** Return the list of Strings that are one modification away * from the input string. * @param s The original String * @param wordsOnly controls whether to return only words or any String * @return list of Strings which are nearby the original string */ public List<String> distanceOne(String s, boolean wordsOnly ) { List<String> retList = new ArrayList<String>(); insertions(s, retList, wordsOnly); substitution(s, retList, wordsOnly); deletions(s, retList, wordsOnly); return retList; } /** Add to the currentList Strings that are one character mutation away * from the input string. * @param s The original String * @param currentList is the list of words to append modified words * @param wordsOnly controls whether to return only words or any String * @return */ public void substitution(String s, List<String> currentList, boolean wordsOnly) { // for each letter in the s and for all possible replacement characters for(int index = 0; index < s.length(); index++){ for(int charCode = (int)'a'; charCode <= (int)'z'; charCode++) { // use StringBuffer for an easy interface to permuting the // letters in the String StringBuffer sb = new StringBuffer(s); sb.setCharAt(index, (char)charCode); // if the item isn't in the list, isn't the original string, and // (if wordsOnly is true) is a real word, add to the list if(!currentList.contains(sb.toString()) && (!wordsOnly||dict.isWord(sb.toString())) && !s.equals(sb.toString())) { currentList.add(sb.toString()); } } } } /** Add to the currentList Strings that are one character insertion away * from the input string. * @param s The original String * @param currentList is the list of words to append modified words * @param wordsOnly controls whether to return only words or any String * @return */ public void insertions(String s, List<String> currentList, boolean wordsOnly ) { // TODO: Implement this method for (int index = 0; index <= s.length(); index++) { for (int charCode = (int) 'a'; charCode <= (int) 'z'; charCode++) { // use StringBuffer for an easy interface to permuting the // letters in the String StringBuilder sb = new StringBuilder(s); sb.insert(index, (char) charCode); // if the item isn't in the list, isn't the original string, and // (if wordsOnly is true) is a real word, add to the list if (!currentList.contains(sb.toString()) && (!wordsOnly || dict.isWord(sb.toString())) && !s.equals(sb.toString())) { currentList.add(sb.toString()); } } } } /** Add to the currentList Strings that are one character deletion away * from the input string. * @param s The original String * @param currentList is the list of words to append modified words * @param wordsOnly controls whether to return only words or any String * @return */ public void deletions(String s, List<String> currentList, boolean wordsOnly ) { // TODO: Implement this method for (int index = 0; index < s.length(); index++) { for (int charCode = (int) 'a'; charCode <= (int) 'z'; charCode++) { // use StringBuffer for an easy interface to permuting the // letters in the String StringBuilder sb = new StringBuilder(s); sb.deleteCharAt(index); // if the item isn't in the list, isn't the original string, and // (if wordsOnly is true) is a real word, add to the list if (!currentList.contains(sb.toString()) && (!wordsOnly || dict.isWord(sb.toString())) && !s.equals(sb.toString())) { currentList.add(sb.toString()); } } } } /** Add to the currentList Strings that are one character deletion away * from the input string. * @param word The misspelled word * @param numSuggestions is the maximum number of suggestions to return * @return the list of spelling suggestions */ @Override public List<String> suggestions(String word, int numSuggestions) { // initial variables List<String> queue = new LinkedList<String>(); // String to explore HashSet<String> visited = new HashSet<String>(); // to avoid exploring the same // string multiple times List<String> retList = new LinkedList<String>(); // words to return // insert first node queue.add(word); visited.add(word); // TODO: Implement the remainder of this method, see assignment for algorithm int wordCount = 0; while(!queue.isEmpty() && numSuggestions>0) { String curr = queue.remove(0); List<String> neighbours = distanceOne(curr,true); if((wordCount+=neighbours.size())>THRESHOLD) { break; } wordCount += neighbours.size(); for(String neighbour: neighbours) { if(!visited.contains(neighbour)) { visited.add(neighbour); queue.add(neighbour); if(dict.isWord(neighbour)) { retList.add(neighbour); numSuggestions--; } } } } return retList; } public static void main(String[] args) { /* basic testing code to get started String word = "i"; // Pass NearbyWords any Dictionary implementation you prefer Dictionary d = new DictionaryHashSet(); DictionaryLoader.loadDictionary(d, "data/dict.txt"); NearbyWords w = new NearbyWords(d); List<String> l = w.distanceOne(word, true); System.out.println("One away word Strings for for \""+word+"\" are:"); System.out.println(l+"\n"); word = "tailo"; List<String> suggest = w.suggestions(word, 10); System.out.println("Spelling Suggestions for \""+word+"\" are:"); System.out.println(suggest); */ } }
package com.batiaev.provisioner.model.user; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class PhoneNumberTest { @Test void should_create_phone_number() { //given String numberString = "+447555555555"; //when PhoneNumber number = new PhoneNumber(numberString); //then assertThat(number).hasToString(numberString); } }
/* * 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.accumulo.harness; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Random; import org.apache.accumulo.cluster.ClusterUser; import org.apache.accumulo.cluster.ClusterUsers; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.security.tokens.AuthenticationToken; import org.apache.accumulo.core.client.security.tokens.KerberosToken; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.security.TablePermission; import org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.security.UserGroupInformation; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Convenience class which starts a single MAC instance for a test to leverage. * * There isn't a good way to build this off of the {@link AccumuloClusterHarness} (as would be the logical place) because we need to start the * MiniAccumuloCluster in a static BeforeClass-annotated method. Because it is static and invoked before any other BeforeClass methods in the implementation, * the actual test classes can't expose any information to tell the base class that it is to perform the one-MAC-per-class semantics. */ public abstract class SharedMiniClusterBase extends AccumuloITBase implements ClusterUsers { private static final Logger log = LoggerFactory.getLogger(SharedMiniClusterBase.class); public static final String TRUE = Boolean.toString(true); private static String principal = "root"; private static String rootPassword; private static AuthenticationToken token; private static MiniAccumuloClusterImpl cluster; private static TestingKdc krb; @BeforeClass public static void startMiniCluster() throws Exception { File baseDir = new File(System.getProperty("user.dir") + "/target/mini-tests"); assertTrue(baseDir.mkdirs() || baseDir.isDirectory()); // Make a shared MAC instance instead of spinning up one per test method MiniClusterHarness harness = new MiniClusterHarness(); if (TRUE.equals(System.getProperty(MiniClusterHarness.USE_KERBEROS_FOR_IT_OPTION))) { krb = new TestingKdc(); krb.start(); // Enabled krb auth Configuration conf = new Configuration(false); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); // Login as the client ClusterUser rootUser = krb.getRootUser(); // Get the krb token principal = rootUser.getPrincipal(); token = new KerberosToken(principal, rootUser.getKeytab(), true); } else { rootPassword = "rootPasswordShared1"; token = new PasswordToken(rootPassword); } cluster = harness.create(SharedMiniClusterBase.class.getName(), System.currentTimeMillis() + "_" + new Random().nextInt(Short.MAX_VALUE), token, krb); cluster.start(); if (null != krb) { final String traceTable = Property.TRACE_TABLE.getDefaultValue(); final ClusterUser systemUser = krb.getAccumuloServerUser(), rootUser = krb.getRootUser(); // Login as the trace user // Open a connector as the system user (ensures the user will exist for us to assign permissions to) Connector conn = cluster.getConnector(systemUser.getPrincipal(), new KerberosToken(systemUser.getPrincipal(), systemUser.getKeytab(), true)); // Then, log back in as the "root" user and do the grant UserGroupInformation.loginUserFromKeytab(rootUser.getPrincipal(), rootUser.getKeytab().getAbsolutePath()); conn = cluster.getConnector(principal, token); // Create the trace table conn.tableOperations().create(traceTable); // Trace user (which is the same kerberos principal as the system user, but using a normal KerberosToken) needs // to have the ability to read, write and alter the trace table conn.securityOperations().grantTablePermission(systemUser.getPrincipal(), traceTable, TablePermission.READ); conn.securityOperations().grantTablePermission(systemUser.getPrincipal(), traceTable, TablePermission.WRITE); conn.securityOperations().grantTablePermission(systemUser.getPrincipal(), traceTable, TablePermission.ALTER_TABLE); } } @AfterClass public static void stopMiniCluster() throws Exception { if (null != cluster) { try { cluster.stop(); } catch (Exception e) { log.error("Failed to stop minicluster", e); } } if (null != krb) { try { krb.stop(); } catch (Exception e) { log.error("Failed to stop KDC", e); } } } public static String getRootPassword() { return rootPassword; } public static AuthenticationToken getToken() { if (token instanceof KerberosToken) { try { UserGroupInformation.loginUserFromKeytab(getPrincipal(), krb.getRootUser().getKeytab().getAbsolutePath()); } catch (IOException e) { throw new RuntimeException("Failed to login", e); } } return token; } public static String getPrincipal() { return principal; } public static MiniAccumuloClusterImpl getCluster() { return cluster; } public static File getMiniClusterDir() { return cluster.getConfig().getDir(); } public static Connector getConnector() { try { return getCluster().getConnector(principal, getToken()); } catch (Exception e) { throw new RuntimeException(e); } } public static TestingKdc getKdc() { return krb; } @Override public ClusterUser getAdminUser() { if (null == krb) { return new ClusterUser(getPrincipal(), getRootPassword()); } else { return krb.getRootUser(); } } @Override public ClusterUser getUser(int offset) { if (null == krb) { String user = SharedMiniClusterBase.class.getName() + "_" + testName.getMethodName() + "_" + offset; // Password is the username return new ClusterUser(user, user); } else { return krb.getClientPrincipal(offset); } } }
/* * FunctionDescriptor.java * Copyright © 1993-2018, The Avail Foundation, LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the copyright holder nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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. */ package com.avail.descriptor; import com.avail.annotations.AvailMethod; import com.avail.annotations.ThreadSafe; import com.avail.descriptor.MethodDescriptor.SpecialMethodAtom; import com.avail.interpreter.levelOne.L1InstructionWriter; import com.avail.interpreter.levelOne.L1Operation; import com.avail.optimizer.jvm.ReferencedInGeneratedCode; import com.avail.serialization.SerializerOperation; import com.avail.utility.json.JSONWriter; import java.util.IdentityHashMap; import static com.avail.descriptor.BlockPhraseDescriptor.newBlockNode; import static com.avail.descriptor.BottomTypeDescriptor.bottom; import static com.avail.descriptor.FunctionDescriptor.ObjectSlots.CODE; import static com.avail.descriptor.FunctionDescriptor.ObjectSlots.OUTER_VAR_AT_; import static com.avail.descriptor.NilDescriptor.nil; import static com.avail.descriptor.ObjectTupleDescriptor.tuple; import static com.avail.descriptor.SetDescriptor.emptySet; import static com.avail.descriptor.StringDescriptor.stringFrom; import static com.avail.descriptor.TupleDescriptor.emptyTuple; import static com.avail.descriptor.TypeDescriptor.Types.TOP; import static com.avail.interpreter.levelOne.L1Decompiler.decompile; /** * A function associates {@linkplain CompiledCodeDescriptor compiled code} with * a referencing environment that binds the code's free variables to variables * defined in an outer lexical scope. In this way, a function constitutes a * proper closure. * * @author Mark van Gulik &lt;mark@availlang.org&gt; * @author Todd L Smith &lt;todd@availlang.org&gt; */ public final class FunctionDescriptor extends Descriptor { /** * The layout of object slots for my instances. */ public enum ObjectSlots implements ObjectSlotsEnum { /** The {@linkplain CompiledCodeDescriptor compiled code}. */ CODE, /** The outer variables. */ OUTER_VAR_AT_; } @Override public void printObjectOnAvoidingIndent ( final AvailObject object, final StringBuilder aStream, final IdentityHashMap<A_BasicObject, Void> recursionMap, final int indent) { final A_RawFunction code = object.code(); A_Phrase phrase = code.originatingPhrase(); if (phrase.equalsNil()) { phrase = decompile(object.code()); } phrase.printOnAvoidingIndent(aStream, recursionMap, indent + 1); } @Override A_RawFunction o_Code (final AvailObject object) { return object.slot(CODE); } @Override boolean o_Equals (final AvailObject object, final A_BasicObject another) { return another.equalsFunction(object); } @Override boolean o_EqualsFunction ( final AvailObject object, final A_Function aFunction) { if (!object.code().equals(aFunction.code())) { return false; } if (object.numOuterVars() != aFunction.numOuterVars()) { return false; } for (int i = 1, end = object.numOuterVars(); i <= end; i++) { if (!object.outerVarAt(i).equals(aFunction.outerVarAt(i))) { return false; } } // They're equal, but occupy disjoint storage. If possible, then replace // one with an indirection to the other to reduce storage costs and the // frequency of detailed comparisons. if (!isShared()) { aFunction.makeImmutable(); object.becomeIndirectionTo(aFunction); } else if (!aFunction.descriptor().isShared()) { object.makeImmutable(); aFunction.becomeIndirectionTo(object); } return true; } @Override int o_Hash (final AvailObject object) { // Answer a 32-bit hash value. If outer vars of mutable functions can // peel away when executed (last use of an outer var of a mutable // function can clobber that var and replace the OUTER_VAR_AT_ entry // with 0 or something), it's ok because nobody could know what the hash // value *used to be* for this function. // In case the last reference to the object is being added to a set, but // subsequent execution might nil out a captured value. object.makeImmutable(); final A_BasicObject code = object.slot(CODE); int hash = code.hash() ^ 0x1386D4F6; for (int i = 1, end = object.numOuterVars(); i <= end; i++) { hash = hash * 13 + object.outerVarAt(i).hash(); } return hash; } @Override boolean o_IsFunction (final AvailObject object) { return true; } /** * Answer the object's type. Simply asks the {@linkplain * CompiledCodeDescriptor compiled code} for the {@linkplain * FunctionTypeDescriptor function type}. */ @Override A_Type o_Kind (final AvailObject object) { return object.slot(CODE).functionType(); } @Override String o_NameForDebugger (final AvailObject object) { return super.o_NameForDebugger(object) + " /* " + object.code().methodName().asNativeString() + " */"; } /** * Answer how many outer vars I've copied. */ @Override int o_NumOuterVars (final AvailObject object) { return object.variableObjectSlotsCount(); } @Override boolean o_OptionallyNilOuterVar ( final AvailObject object, final int index) { if (isMutable()) { object.setSlot(OUTER_VAR_AT_, index, nil); return true; } return false; } @Override AvailObject o_OuterVarAt (final AvailObject object, final int subscript) { return object.slot(OUTER_VAR_AT_, subscript); } @Override void o_OuterVarAtPut ( final AvailObject object, final int subscript, final AvailObject value) { object.setSlot(OUTER_VAR_AT_, subscript, value); } @Override @AvailMethod @ThreadSafe SerializerOperation o_SerializerOperation (final AvailObject object) { if (object.numOuterVars() == 0) { return SerializerOperation.CLEAN_FUNCTION; } return SerializerOperation.GENERAL_FUNCTION; } @Override public boolean o_ShowValueInNameForDebugger (final AvailObject object) { return true; } @Override void o_WriteSummaryTo (final AvailObject object, final JSONWriter writer) { writer.startObject(); writer.write("kind"); writer.write("function"); writer.write("function implementation"); object.slot(CODE).writeSummaryTo(writer); writer.write("outers"); writer.startArray(); for (int i = 1, limit = object.variableObjectSlotsCount(); i <= limit; i++) { object.slot(OUTER_VAR_AT_, i).writeSummaryTo(writer); } writer.endArray(); writer.endObject(); } @Override void o_WriteTo (final AvailObject object, final JSONWriter writer) { writer.startObject(); writer.write("kind"); writer.write("function"); writer.write("function implementation"); object.slot(CODE).writeTo(writer); writer.write("outers"); writer.startArray(); for (int i = 1, limit = object.variableObjectSlotsCount(); i <= limit; i++) { object.slot(OUTER_VAR_AT_, i).writeSummaryTo(writer); } writer.endArray(); writer.endObject(); } /** * Create a function that takes arguments of the specified types, then turns * around and calls the function invocation method with the given function * and the passed arguments assembled into a tuple. * * @param functionType * The type to which the resultant function should conform. * @param function * The function which the new function should invoke when itself * invoked. * @return An appropriate function with the given signature. */ public static A_Function createStubWithSignature ( final A_Type functionType, final A_Function function) { final A_Type argTypes = functionType.argsTupleType(); final int numArgs = argTypes.sizeRange().lowerBound().extractInt(); final A_Type[] argTypesArray = new AvailObject[numArgs]; for (int i = 1; i <= numArgs; i++) { argTypesArray[i - 1] = argTypes.typeAtIndex(i); } final A_Type returnType = functionType.returnType(); final L1InstructionWriter writer = new L1InstructionWriter(nil, 0, nil); writer.argumentTypes(argTypesArray); writer.returnType(returnType); writer.write( 0, L1Operation.L1_doPushLiteral, writer.addLiteral(function)); for (int i = 1; i <= numArgs; i++) { writer.write(0, L1Operation.L1_doPushLastLocal, i); } writer.write(0, L1Operation.L1_doMakeTuple, numArgs); writer.write( 0, L1Operation.L1_doCall, writer.addLiteral(SpecialMethodAtom.APPLY.bundle), writer.addLiteral(returnType)); final AvailObject code = writer.compiledCode(); final A_Function newFunction = createFunction(code, emptyTuple()); newFunction.makeImmutable(); return newFunction; } /** * Create a function that takes arguments of the specified types, then calls * the {@link A_Method} for the {@link A_Bundle} of the given {@link A_Atom} * with those arguments. * * @param functionType * The type to which the resultant function should conform. * @param atom * The {@link A_Atom} which names the {@link A_Method} to be invoked * by the new function. * @return An appropriate function. * @throws IllegalArgumentException * If the atom has no associated bundle/method, or the function * signature is inconsistent with the available method definitions. */ @SuppressWarnings("unused") public static A_Function createStubToCallMethod ( final A_Type functionType, final A_Atom atom) { final A_Bundle bundle = atom.bundleOrNil(); if (bundle.equalsNil()) { throw new IllegalArgumentException("Atom to invoke has no method"); } final A_Method method = bundle.bundleMethod(); final A_Type argTypes = functionType.argsTupleType(); // Check that there's a definition, even abstract, that will catch all // invocations for the given function type's argument types. final boolean ok = method.definitionsTuple().stream() .anyMatch(definition -> !definition.isMacroDefinition() && definition.bodySignature().isSubtypeOf(functionType)); if (!ok) { throw new IllegalArgumentException( "Function signature is not strong enough to call method " + "safely"); } final int numArgs = argTypes.sizeRange().lowerBound().extractInt(); final A_Type[] argTypesArray = new AvailObject[numArgs]; for (int i = 1; i <= numArgs; i++) { argTypesArray[i - 1] = argTypes.typeAtIndex(i); } final A_Type returnType = functionType.returnType(); final L1InstructionWriter writer = new L1InstructionWriter(nil, 0, nil); writer.argumentTypes(argTypesArray); writer.returnType(returnType); for (int i = 1; i <= numArgs; i++) { writer.write(0, L1Operation.L1_doPushLastLocal, i); } writer.write( 0, L1Operation.L1_doCall, writer.addLiteral(bundle), writer.addLiteral(returnType)); final AvailObject code = writer.compiledCode(); final A_Function newFunction = createFunction(code, emptyTuple()); newFunction.makeImmutable(); return newFunction; } /** * Construct a function with the given code and tuple of copied variables. * * @param code The code with which to build the function. * @param copiedTuple The outer variables and constants to enclose. * @return A function. */ public static A_Function createFunction ( final A_BasicObject code, final A_Tuple copiedTuple) { final int copiedSize = copiedTuple.tupleSize(); final AvailObject object = mutable.create(copiedSize); object.setSlot(CODE, code); if (copiedSize > 0) { object.setSlotsFromTuple( OUTER_VAR_AT_, 1, copiedTuple, 1, copiedSize); } return object; } /** * Construct a function with the given code and room for the given number of * outer variables. Do not initialize any outer variable slots. * * @param code The code with which to build the function. * @param outersCount The number of outer variables that will be enclosed. * @return A function without its outer variables initialized. */ @ReferencedInGeneratedCode public static AvailObject createExceptOuters ( final A_RawFunction code, final int outersCount) { assert code.numOuters() == outersCount; final AvailObject object = mutable.create(outersCount); object.setSlot(CODE, code); return object; } /** * Construct a function with the given code and one outer variable. * * @param code The code with which to build the function. * @param outer1 The sole outer variable that will be enclosed. * @return A function with its outer variable initialized. */ @ReferencedInGeneratedCode public static AvailObject createWithOuters1 ( final A_RawFunction code, final AvailObject outer1) { final AvailObject function = createExceptOuters(code, 1); function.setSlot(OUTER_VAR_AT_, 1, outer1); return function; } /** * Construct a function with the given code and two outer variables. * * @param code The code with which to build the function. * @param outer1 The first outer variable that will be enclosed. * @param outer2 The second outer variable that will be enclosed. * @return A function with its outer variables initialized. */ @ReferencedInGeneratedCode public static AvailObject createWithOuters2 ( final A_RawFunction code, final AvailObject outer1, final AvailObject outer2) { final AvailObject function = createExceptOuters(code, 2); function.setSlot(OUTER_VAR_AT_, 1, outer1); function.setSlot(OUTER_VAR_AT_, 2, outer2); return function; } /** * Construct a function with the given code and three outer variables. * * @param code The code with which to build the function. * @param outer1 The first outer variable that will be enclosed. * @param outer2 The second outer variable that will be enclosed. * @param outer3 The first outer variable that will be enclosed. * @return A function with its outer variables initialized. */ @ReferencedInGeneratedCode public static AvailObject createWithOuters3 ( final A_RawFunction code, final AvailObject outer1, final AvailObject outer2, final AvailObject outer3) { final AvailObject function = createExceptOuters(code, 3); function.setSlot(OUTER_VAR_AT_, 1, outer1); function.setSlot(OUTER_VAR_AT_, 2, outer2); function.setSlot(OUTER_VAR_AT_, 3, outer3); return function; } /** * Convert a {@link PhraseDescriptor phrase} into a zero-argument * {@link A_Function}. * * @param phrase * The phrase to compile to a function. * @param module * The {@linkplain ModuleDescriptor module} that is the context for * the phrase and function, or {@linkplain NilDescriptor#nil nil} * if there is no context. * @param lineNumber * The line number to attach to the new function, or {@code 0} if no * meaningful line number is available. * @return A zero-argument function. */ public static A_Function createFunctionForPhrase ( final A_Phrase phrase, final A_Module module, final int lineNumber) { final A_Phrase block = newBlockNode( emptyTuple(), 0, tuple(phrase), TOP.o(), emptySet(), lineNumber, phrase.tokens()); BlockPhraseDescriptor.recursivelyValidate(block); final A_RawFunction compiledBlock = block.generateInModule(module); // The block is guaranteed context-free (because imported // variables/values are embedded directly as constants in the generated // code), so build a function with no copied data. assert compiledBlock.numOuters() == 0; final A_Function function = createFunction(compiledBlock, emptyTuple()); function.makeImmutable(); return function; } /** * Construct a bootstrap {@code FunctionDescriptor function} that * crashes when invoked. * * @param messageString * The message string to prepend to the list of arguments, indicating * the basic nature of the failure. * @param paramTypes * The {@linkplain TupleDescriptor tuple} of parameter {@linkplain * TypeDescriptor types}. * @return The requested crash function. * @see SpecialMethodAtom#CRASH */ public static A_Function newCrashFunction ( final String messageString, final A_Tuple paramTypes) { final L1InstructionWriter writer = new L1InstructionWriter( nil, 0, nil); writer.argumentTypesTuple(paramTypes); writer.returnType(bottom()); writer.write( 0, L1Operation.L1_doPushLiteral, writer.addLiteral(stringFrom(messageString))); final int numArgs = paramTypes.tupleSize(); for (int i = 1; i <= numArgs; i++) { writer.write(0, L1Operation.L1_doPushLastLocal, i); } // Put the error message and arguments into a tuple. writer.write(0, L1Operation.L1_doMakeTuple, numArgs + 1); writer.write( 0, L1Operation.L1_doCall, writer.addLiteral(SpecialMethodAtom.CRASH.bundle), writer.addLiteral(bottom())); final A_RawFunction code = writer.compiledCode(); code.setMethodName(stringFrom("VM crash function: " + messageString)); final A_Function function = createFunction(code, emptyTuple()); function.makeShared(); return function; } /** * Construct a new {@code FunctionDescriptor}. * * @param mutability * The {@linkplain Mutability mutability} of the new descriptor. */ private FunctionDescriptor (final Mutability mutability) { super(mutability, TypeTag.FUNCTION_TAG, ObjectSlots.class, null); } /** The mutable {@link FunctionDescriptor}. */ public static final FunctionDescriptor mutable = new FunctionDescriptor(Mutability.MUTABLE); @Override FunctionDescriptor mutable () { return mutable; } /** The immutable {@link FunctionDescriptor}. */ private static final FunctionDescriptor immutable = new FunctionDescriptor(Mutability.IMMUTABLE); @Override FunctionDescriptor immutable () { return immutable; } /** The shared {@link FunctionDescriptor}. */ private static final FunctionDescriptor shared = new FunctionDescriptor(Mutability.SHARED); @Override FunctionDescriptor shared () { return shared; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.search; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.util.concurrent.AtomicArray; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.InnerHitBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.SearchPhaseResult; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.collapse.CollapseBuilder; import org.elasticsearch.search.internal.InternalSearchResponse; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * This search phase is an optional phase that will be executed once all hits are fetched from the shards that executes * field-collapsing on the inner hits. This phase only executes if field collapsing is requested in the search request and otherwise * forwards to the next phase immediately. */ final class ExpandSearchPhase extends SearchPhase { private final SearchPhaseContext context; private final InternalSearchResponse searchResponse; private final AtomicArray<SearchPhaseResult> queryResults; ExpandSearchPhase(SearchPhaseContext context, InternalSearchResponse searchResponse, AtomicArray<SearchPhaseResult> queryResults) { super("expand"); this.context = context; this.searchResponse = searchResponse; this.queryResults = queryResults; } /** * Returns <code>true</code> iff the search request has inner hits and needs field collapsing */ private boolean isCollapseRequest() { final SearchRequest searchRequest = context.getRequest(); return searchRequest.source() != null && searchRequest.source().collapse() != null && searchRequest.source().collapse().getInnerHits().isEmpty() == false; } @Override public void run() { if (isCollapseRequest() && searchResponse.hits().getHits().length > 0) { SearchRequest searchRequest = context.getRequest(); CollapseBuilder collapseBuilder = searchRequest.source().collapse(); final List<InnerHitBuilder> innerHitBuilders = collapseBuilder.getInnerHits(); MultiSearchRequest multiRequest = new MultiSearchRequest(); if (collapseBuilder.getMaxConcurrentGroupRequests() > 0) { multiRequest.maxConcurrentSearchRequests(collapseBuilder.getMaxConcurrentGroupRequests()); } for (SearchHit hit : searchResponse.hits().getHits()) { BoolQueryBuilder groupQuery = new BoolQueryBuilder(); Object collapseValue = hit.field(collapseBuilder.getField()).getValue(); if (collapseValue != null) { groupQuery.filter(QueryBuilders.matchQuery(collapseBuilder.getField(), collapseValue)); } else { groupQuery.mustNot(QueryBuilders.existsQuery(collapseBuilder.getField())); } QueryBuilder origQuery = searchRequest.source().query(); if (origQuery != null) { groupQuery.must(origQuery); } for (InnerHitBuilder innerHitBuilder : innerHitBuilders) { CollapseBuilder innerCollapseBuilder = innerHitBuilder.getInnerCollapseBuilder(); SearchSourceBuilder sourceBuilder = buildExpandSearchSourceBuilder(innerHitBuilder, innerCollapseBuilder) .query(groupQuery) .postFilter(searchRequest.source().postFilter()) .runtimeMappings(searchRequest.source().runtimeMappings()); SearchRequest groupRequest = new SearchRequest(searchRequest); groupRequest.source(sourceBuilder); multiRequest.add(groupRequest); } } context.getSearchTransport().sendExecuteMultiSearch(multiRequest, context.getTask(), ActionListener.wrap(response -> { Iterator<MultiSearchResponse.Item> it = response.iterator(); for (SearchHit hit : searchResponse.hits.getHits()) { for (InnerHitBuilder innerHitBuilder : innerHitBuilders) { MultiSearchResponse.Item item = it.next(); if (item.isFailure()) { context.onPhaseFailure(this, "failed to expand hits", item.getFailure()); return; } SearchHits innerHits = item.getResponse().getHits(); if (hit.getInnerHits() == null) { hit.setInnerHits(new HashMap<>(innerHitBuilders.size())); } hit.getInnerHits().put(innerHitBuilder.getName(), innerHits); } } context.sendSearchResponse(searchResponse, queryResults); }, context::onFailure) ); } else { context.sendSearchResponse(searchResponse, queryResults); } } private SearchSourceBuilder buildExpandSearchSourceBuilder(InnerHitBuilder options, CollapseBuilder innerCollapseBuilder) { SearchSourceBuilder groupSource = new SearchSourceBuilder(); groupSource.from(options.getFrom()); groupSource.size(options.getSize()); if (options.getSorts() != null) { options.getSorts().forEach(groupSource::sort); } if (options.getFetchSourceContext() != null) { if (options.getFetchSourceContext().includes().length == 0 && options.getFetchSourceContext().excludes().length == 0) { groupSource.fetchSource(options.getFetchSourceContext().fetchSource()); } else { groupSource.fetchSource(options.getFetchSourceContext().includes(), options.getFetchSourceContext().excludes()); } } if (options.getFetchFields() != null) { options.getFetchFields().forEach(ff -> groupSource.fetchField(ff)); } if (options.getDocValueFields() != null) { options.getDocValueFields().forEach(ff -> groupSource.docValueField(ff.field, ff.format)); } if (options.getStoredFieldsContext() != null && options.getStoredFieldsContext().fieldNames() != null) { options.getStoredFieldsContext().fieldNames().forEach(groupSource::storedField); } if (options.getScriptFields() != null) { for (SearchSourceBuilder.ScriptField field : options.getScriptFields()) { groupSource.scriptField(field.fieldName(), field.script()); } } if (options.getHighlightBuilder() != null) { groupSource.highlighter(options.getHighlightBuilder()); } groupSource.explain(options.isExplain()); groupSource.trackScores(options.isTrackScores()); groupSource.version(options.isVersion()); groupSource.seqNoAndPrimaryTerm(options.isSeqNoAndPrimaryTerm()); if (innerCollapseBuilder != null) { groupSource.collapse(innerCollapseBuilder); } return groupSource; } }
/** * Copyright 2008-2017 Qualogy Solutions B.V. * * 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.qualogy.qafe.gwt.client.vo.functions; public abstract class InternalBuiltInFunctionGVO extends BuiltInFunctionGVO { }
package com.avaje.ebeaninternal.util; import com.avaje.ebeaninternal.util.SortByClause.Property; public final class SortByClauseParser { private final String rawSortBy; public static SortByClause parse(String rawSortByClause){ return new SortByClauseParser(rawSortByClause).parse(); } private SortByClauseParser(String rawSortByClause) { this.rawSortBy = rawSortByClause.trim(); } private SortByClause parse(){ SortByClause sortBy = new SortByClause(); String[] sections = rawSortBy.split(","); for (int i = 0; i < sections.length; i++) { Property p = parseSection(sections[i].trim()); if (p == null){ break; } else { sortBy.add(p); } } return sortBy; } private Property parseSection(String section){ if (section.length() == 0){ return null; } String[] words = section.split(" "); if (words.length < 1 || words.length > 3){ throw new RuntimeException("Expecting 1 to 3 words in ["+section+"] but got ["+words.length+"]"); } Boolean nullsHigh = null; boolean ascending = true; String propName = words[0]; if (words.length > 1){ if (words[1].startsWith("nulls")){ nullsHigh = isNullsHigh(words[1]); } else { ascending = isAscending(words[1]); } } if (words.length > 2){ if (words[2].startsWith("nulls")){ nullsHigh = isNullsHigh(words[2]); } else { ascending = isAscending(words[2]); } } return new Property(propName, ascending, nullsHigh); } private Boolean isNullsHigh(String word){ if (SortByClause.NULLSHIGH.equalsIgnoreCase(word)){ return Boolean.TRUE; } if (SortByClause.NULLSLOW.equalsIgnoreCase(word)){ return Boolean.FALSE; } String m = "Expecting nullsHigh or nullsLow but got ["+word+"] in ["+rawSortBy+"]"; throw new RuntimeException(m); } private boolean isAscending(String word){ if (SortByClause.ASC.equalsIgnoreCase(word)){ return true; } if (SortByClause.DESC.equalsIgnoreCase(word)){ return false; } String m = "Expection ASC or DESC but got ["+word+"] in ["+rawSortBy+"]"; throw new RuntimeException(m); } }
package org.uma.jmetal.util.ranking.impl; import org.uma.jmetal.util.ranking.Ranking; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.solution.util.attribute.util.attributecomparator.AttributeComparator; import org.uma.jmetal.solution.util.attribute.util.attributecomparator.impl.IntegerValueAttributeComparator; import org.uma.jmetal.util.JMetalException; import org.uma.jmetal.util.comparator.DominanceComparator; import org.uma.jmetal.util.comparator.impl.OverallConstraintViolationComparator; import java.util.*; /** * This class implements a solution list ranking based on dominance ranking. Given a collection of solutions, they * are ranked according to scheme similar to the one proposed in NSGA-II. As an output, a set of subsets are obtained. * The subsets are numbered starting from 0 (in NSGA-II, the numbering starts from 1); thus, subset 0 contains the * non-dominated solutions, subset 1 contains the non-dominated population after removing those belonging to subset * 0, and so on. * * @author Antonio J. Nebro <antonio@lcc.uma.es> */ public class FastNonDominatedSortRanking<S extends Solution<?>> implements Ranking<S> { private String attributeId = getClass().getName() ; private Comparator<S> dominanceComparator ; private Comparator<S> solutionComparator; private static final Comparator<Solution<?>> CONSTRAINT_VIOLATION_COMPARATOR = new OverallConstraintViolationComparator<Solution<?>>(); private List<ArrayList<S>> rankedSubPopulations; /** * Constructor */ public FastNonDominatedSortRanking(Comparator<S> comparator) { this.dominanceComparator = comparator ; rankedSubPopulations = new ArrayList<>(); this.solutionComparator = new IntegerValueAttributeComparator<>(attributeId, AttributeComparator.Ordering.ASCENDING) ; } /** * Constructor */ public FastNonDominatedSortRanking() { this(new DominanceComparator<>()) ; } @Override public Ranking<S> computeRanking(List<S> solutionList) { List<S> population = solutionList; // dominateMe[i] contains the number of population dominating i int[] dominateMe = new int[population.size()]; // iDominate[k] contains the list of population dominated by k List<List<Integer>> iDominate = new ArrayList<>(population.size()); // front[i] contains the list of individuals belonging to the front i ArrayList<List<Integer>> front = new ArrayList<>(population.size() + 1); // Initialize the fronts for (int i = 0; i < population.size() + 1; i++) { front.add(new LinkedList<Integer>()); } // Fast non dominated sorting algorithm // Contribution of Guillaume Jacquenot for (int p = 0; p < population.size(); p++) { // Initialize the list of individuals that i dominate and the number // of individuals that dominate me iDominate.add(new LinkedList<Integer>()); dominateMe[p] = 0; } int flagDominate; for (int p = 0; p < (population.size() - 1); p++) { // For all q individuals , calculate if p dominates q or vice versa for (int q = p + 1; q < population.size(); q++) { flagDominate = CONSTRAINT_VIOLATION_COMPARATOR.compare(solutionList.get(p), solutionList.get(q)); if (flagDominate == 0) { flagDominate = dominanceComparator.compare(solutionList.get(p), solutionList.get(q)); } if (flagDominate == -1) { iDominate.get(p).add(q); dominateMe[q]++; } else if (flagDominate == 1) { iDominate.get(q).add(p); dominateMe[p]++; } } } for (int i = 0; i < population.size(); i++) { if (dominateMe[i] == 0) { front.get(0).add(i); solutionList.get(i).setAttribute(attributeId, 0); } } //Obtain the rest of fronts int i = 0; Iterator<Integer> it1, it2; // Iterators while (front.get(i).size() != 0) { i++; it1 = front.get(i - 1).iterator(); while (it1.hasNext()) { it2 = iDominate.get(it1.next()).iterator(); while (it2.hasNext()) { int index = it2.next(); dominateMe[index]--; if (dominateMe[index] == 0) { front.get(i).add(index); solutionList.get(index).setAttribute(attributeId, i); } } } } rankedSubPopulations = new ArrayList<>(); //0,1,2,....,i-1 are fronts, then i fronts for (int j = 0; j < i; j++) { rankedSubPopulations.add(j, new ArrayList<S>(front.get(j).size())); it1 = front.get(j).iterator(); while (it1.hasNext()) { rankedSubPopulations.get(j).add(solutionList.get(it1.next())); } } return this; } @Override public List<S> getSubFront(int rank) { if (rank >= rankedSubPopulations.size()) { throw new JMetalException("Invalid rank: " + rank + ". Max rank = " + (rankedSubPopulations.size() -1)) ; } return rankedSubPopulations.get(rank); } @Override public int getNumberOfSubFronts() { return rankedSubPopulations.size(); } @Override public Comparator<S> getSolutionComparator() { return solutionComparator; } @Override public String getAttributeId() { return attributeId ; } }
package org.nd4j.linalg.profiler.data; import org.nd4j.linalg.profiler.data.primitives.ComparableAtomicLong; import org.nd4j.linalg.util.ArrayUtil; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; /** * Simple key-value counter * * @author raver119@gmail.com */ public class StringCounter { private Map<String, ComparableAtomicLong> counter = new ConcurrentHashMap<>(); private AtomicLong totals = new AtomicLong(0); public StringCounter() { } public void reset() { for (String key : counter.keySet()) { // counter.remove(key); counter.put(key, new ComparableAtomicLong(0)); } totals.set(0); } public long incrementCount(String key) { if (!counter.containsKey(key)) { counter.put(key, new ComparableAtomicLong(0)); } ArrayUtil.allUnique(new int[] {}); totals.incrementAndGet(); return counter.get(key).incrementAndGet(); } public long getCount(String key) { if (!counter.containsKey(key)) return 0; return counter.get(key).get(); } public void totalsIncrement() { totals.incrementAndGet(); } public String asString() { StringBuilder builder = new StringBuilder(); Map<String, ComparableAtomicLong> sortedCounter = ArrayUtil.sortMapByValue(counter); for (String key : sortedCounter.keySet()) { long currentCnt = sortedCounter.get(key).get(); long totalCnt = totals.get(); if (totalCnt == 0) continue; float perc = currentCnt * 100 / totalCnt; builder.append(key).append(" >>> [").append(currentCnt).append("]").append(" perc: [").append(perc) .append("]").append("\n"); } return builder.toString(); } }
/* * Copyright (c) 2020 * Author: xiaoweixiang */ package test; import lombok.Builder; import lombok.Data; @Data @Builder public class Phone{ private int number; private int card; // private Phone(int number, int card) { // this.number = number; // this.card = card; // } // // public static Phone of(int number, int card) { // Preconditions.checkArgument(number > 30); // Preconditions.checkArgument(card > 30); // // return new Phone(number, card); // } // // @Override // public String toString() { // return "Phone{" + // "number=" + number + // ", card=" + card + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Phone phone = (Phone) o; // return number == phone.number && // card == phone.card; // } // // @Override // public int hashCode() { // return Objects.hash(number, card); // } // public static void main(String[] args) { // Phone phone = Phone.builder().card(123).number(456).build(); // Phone phone1 = Phone.of(50, 50); // System.out.println("phone.toString() = " + phone.toString()); // System.out.println("phone.compareTo(phone1) = " + phone.compareTo(phone1)); // ArrayList<Phone> list = Lists.newArrayList(phone1, phone); // Collections.sort(list); // list.forEach(System.out::println); } // // // @Override // public int compareTo(@Nullable Phone o) { // return Comparator.comparingInt((Phone p) -> p.number).thenComparing(p -> p.card).compare(o, this); // } }
/** * Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.pods.web; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; /** * * @author carcassi */ @WebFilter(filterName = "SocketFilter", urlPatterns = {"/socket"}) public class SocketFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; httpRequest.getSession().setAttribute("remoteHost", httpRequest.getRemoteHost()); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { // Nothing to do } @Override public void destroy() { // Nothing to do } }
package com.guysfromusa.carsgame; import com.guysfromusa.carsgame.v1.model.Point; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class GameMapUtilsTest { @Test public void shouldNormalizeCarAvailableFieldsToOne() { //given String content = "3,2\nx,0"; //when Integer[][] map = GameMapUtils.getMapMatrixFromContent(content); //then assertThat(map).isEqualTo(new Integer[][]{{1, 1}, {1, 0}}); } @Test public void shouldConvertStringContentToIntegerArray() { //given String content = "1,1\n1,0"; //when Integer[][] map = GameMapUtils.getMapMatrixFromContent(content); //then assertThat(map).isEqualTo(new Integer[][]{{1, 1}, {1, 0}}); } @Test public void isReachable() { assertThat(GameMapUtils.isReachable(new Integer[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}})).isTrue(); assertThat(GameMapUtils.isReachable(new Integer[][]{{1, 1}, {1, 1}})).isTrue(); assertThat(GameMapUtils.isReachable(new Integer[][]{{1}})).isTrue(); assertThat(GameMapUtils.isReachable(new Integer[][]{})).isFalse(); assertThat(GameMapUtils.isReachable(new Integer[][]{{0}})).isFalse(); assertThat(GameMapUtils.isReachable(new Integer[][]{{0, 0}, {0, 0}})).isFalse(); assertThat(GameMapUtils.isReachable(new Integer[][]{{0, 1}, {1, 0}})).isFalse(); assertThat(GameMapUtils.isReachable(new Integer[][]{{0, 1, 1}, {0, 1, 1}, {1, 0, 0}})).isFalse(); assertThat(GameMapUtils.isReachable(new Integer[][]{{1, 1, 1}, {}, {1, 1, 1}})).isFalse(); } @Test public void shouldPositionBeValidOnGameMapWhenCarOnRoad(){ //given Integer[][] gameMapContent = {{1,1}, {1,0}, {1,0}, {1,1}}; Point startingPoint = new Point(1, 3); //when boolean positionValidOnGameMap = GameMapUtils.isPointOnRoad(gameMapContent, startingPoint); //then assertTrue(positionValidOnGameMap); } @Test public void shouldNotBeOnRoadGameMap(){ //given Integer[][] gameMapContent = {{1,1}, {1,0}, {1,0}, {1,1}}; Point startingPoint = new Point(5, 3); //when boolean positionValidOnGameMap = GameMapUtils.isPointOnRoad(gameMapContent, startingPoint); //then assertFalse(positionValidOnGameMap); } }
package com.dbjgb.advent.fifteen.puzzle.eight; import com.dbjgb.advent.Utility; import java.io.BufferedReader; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Solution { private static final Pattern HEX_ESCAPE_PATTERN = Pattern.compile("\\\\x[0-9a-f]{2}"); private static final Pattern ESCAPED_CHARACTER = Pattern.compile("\\\\[\"\\\\]"); private static final Pattern BACKSLASH_CHARACTER = Pattern.compile("\\\\"); private static final Pattern QUOTED_CHARACTER = Pattern.compile("\""); public static void main(String... args) throws Exception { try (BufferedReader inputReader = Utility.openInputFile("fifteen/puzzle/eight/input.txt")) { int rawNumberOfCharacters = 0; int numberUnescapedOfCharacters = 0; int numberOfOverEscapedCharacter = 0; String line; while ((line = inputReader.readLine()) != null) { rawNumberOfCharacters += line.length(); numberUnescapedOfCharacters += countUnescapedCharacters(line); numberOfOverEscapedCharacter += countEscapedCharacters(line); } System.out.printf( "Difference in characters: %d\n", rawNumberOfCharacters - numberUnescapedOfCharacters); System.out.printf( "Difference in characters: %d\n", numberOfOverEscapedCharacter - rawNumberOfCharacters); } } private static int countUnescapedCharacters(String line) { Matcher escapedCharacterMatcher = ESCAPED_CHARACTER.matcher(line); Matcher hexMatcher = HEX_ESCAPE_PATTERN.matcher(escapedCharacterMatcher.replaceAll("-")); String unescapedQuotedString = hexMatcher.replaceAll("-"); // account for removing the two double quotes surrounding the string without actually removing // them. return unescapedQuotedString.length() - 2; } private static int countEscapedCharacters(String line) { Matcher backslashMatcher = BACKSLASH_CHARACTER.matcher(line); Matcher quoteMatcher = QUOTED_CHARACTER.matcher(backslashMatcher.replaceAll("\\\\\\\\")); String escapedString = quoteMatcher.replaceAll("\\\\\""); // account for adding the two double quotes surrounding the string without actually adding them. return escapedString.length() + 2; } }
// Targeted by JavaCPP version 1.5.4: DO NOT EDIT THIS FILE package org.bytedeco.arrow; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.arrow.global.arrow.*; @Namespace("arrow") @Properties(inherit = org.bytedeco.arrow.presets.arrow.class) public class ListScalar extends BaseListScalar { static { Loader.load(); } public ListScalar(@SharedPtr @Cast({"", "std::shared_ptr<arrow::DataType>"}) DataType type) { super((Pointer)null); allocate(type); } private native void allocate(@SharedPtr @Cast({"", "std::shared_ptr<arrow::DataType>"}) DataType type); public ListScalar(@SharedPtr @Cast({"", "std::shared_ptr<arrow::Array>"}) Array value, @SharedPtr @Cast({"", "std::shared_ptr<arrow::DataType>"}) DataType type) { super((Pointer)null); allocate(value, type); } private native void allocate(@SharedPtr @Cast({"", "std::shared_ptr<arrow::Array>"}) Array value, @SharedPtr @Cast({"", "std::shared_ptr<arrow::DataType>"}) DataType type); /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public ListScalar(Pointer p) { super(p); } public ListScalar(@SharedPtr @Cast({"", "std::shared_ptr<arrow::Array>"}) Array value) { super((Pointer)null); allocate(value); } private native void allocate(@SharedPtr @Cast({"", "std::shared_ptr<arrow::Array>"}) Array value); }
/* * 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.syncope.core.persistence.jpa.dao; import java.util.Collections; import java.util.List; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.apache.syncope.core.persistence.api.dao.ReportDAO; import org.apache.syncope.core.persistence.api.dao.search.OrderByClause; import org.apache.syncope.core.persistence.api.entity.Report; import org.apache.syncope.core.persistence.jpa.entity.JPAReport; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public class JPAReportDAO extends AbstractDAO<Report, Long> implements ReportDAO { @Override @Transactional(readOnly = true) public Report find(final Long key) { return entityManager.find(JPAReport.class, key); } @Override public List<Report> findAll() { return findAll(-1, -1, Collections.<OrderByClause>emptyList()); } @Override public List<Report> findAll(final int page, final int itemsPerPage, final List<OrderByClause> orderByClauses) { final TypedQuery<Report> query = entityManager.createQuery( "SELECT e FROM " + JPAReport.class.getSimpleName() + " e " + toOrderByStatement(Report.class, "e", orderByClauses), Report.class); query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1)); if (itemsPerPage > 0) { query.setMaxResults(itemsPerPage); } return query.getResultList(); } @Override public int count() { Query countQuery = entityManager.createNativeQuery("SELECT COUNT(id) FROM " + JPAReport.TABLE); return ((Number) countQuery.getSingleResult()).intValue(); } @Override @Transactional(rollbackFor = Throwable.class) public Report save(final Report report) { return entityManager.merge(report); } @Override public void delete(final Long key) { Report report = find(key); if (report == null) { return; } delete(report); } @Override public void delete(final Report report) { entityManager.remove(report); } }
/** * Copyright (c) 2019-present Acrolinx GmbH */ package com.acrolinx.client.sdk.check; import java.util.List; import com.google.gson.Gson; /** * Only supported with Acrolinx Platform 2019.10 and newer. */ public class ExternalContent { private final List<ExternalContentField> textReplacements; private final List<ExternalContentField> entities; private final List<ExternalContentField> ditaReferences; public ExternalContent(List<ExternalContentField> textReplacements, List<ExternalContentField> entities, List<ExternalContentField> ditaReferences) { this.textReplacements = textReplacements; this.entities = entities; this.ditaReferences = ditaReferences; } public List<ExternalContentField> getTextReplacements() { return textReplacements; } public List<ExternalContentField> getEntities() { return entities; } public List<ExternalContentField> getDitaReferences() { return ditaReferences; } @Override public String toString() { return new Gson().toJson(this); } }
package com.inferno.projectx.assigntask; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.os.Parcelable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.inferno.projectx.BaseFragment; import com.inferno.projectx.ChooseItem; import com.inferno.projectx.R; import com.inferno.projectx.model.ContractorModel; import com.inferno.projectx.model.MaterialModel; import com.inferno.projectx.model.WorkerModel; import com.inferno.projectx.toolbox.AppConstants; import com.inferno.projectx.toolbox.NetworkService; import com.inferno.projectx.toolbox.ServerConstants; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; public class ChooseMaterial extends BaseFragment { private View rootView; private Context context; private RecyclerView materialListView; private RecyclerView.LayoutManager mLayoutManager; private ChooseMaterialAdapter mAdapter; private ProgressDialog progressDialog; Retrofit retrofit; NetworkService networkService; private ArrayList<MaterialModel> materialArrayList; private ContractorModel selectedContractor; private ArrayList<WorkerModel> selectedWorkers; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { Log.i("WorkerModel",""+((ContractorModel)getArguments().get(AppConstants.EXTRA_CONTRACTOR)).getContractorName());//test log Log.i("WorkerModel",""+((ArrayList<WorkerModel>)getArguments().get(AppConstants.EXTRA_WORKER_LIST)).get(0).getWorkerName());//test log } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.choose_material, container, false); context = getActivity(); setHasOptionsMenu(true); progressDialog = new ProgressDialog(context); selectedContractor = getArguments().getParcelable(AppConstants.EXTRA_CONTRACTOR); selectedWorkers = getArguments().getParcelableArrayList(AppConstants.EXTRA_WORKER_LIST); retrofit = new Retrofit.Builder() .baseUrl(ServerConstants.SERVER_BASEURL) .build(); networkService = retrofit.create(NetworkService.class); materialListView = (RecyclerView) rootView.findViewById(R.id.addmaterialsList); mLayoutManager = new LinearLayoutManager(context); materialListView.setLayoutManager(mLayoutManager); return rootView; } @Override public void onResume() { super.onResume(); getMaterialList(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.chooseworker, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.done: /*Bundle extras = new Bundle(); extras.putParcelableArrayList(AppConstants.EXTRA_WORKER_LIST,getSelectedMaterials(materialArrayList)); extras.putParcelable(AppConstants.EXTRA_CONTRACTOR, (Parcelable) getArguments().get(AppConstants.EXTRA_CONTRACTOR)); startFrgament(getFragmentManager(),new ChooseMaterial(),false,extras);*/ try{ networkService.getAssignWork(formJson().toString()).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.isSuccessful()){ Snackbar.make(rootView,"Work Assigned successfully",Snackbar.LENGTH_LONG).show(); getActivity().finish(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Snackbar.make(rootView,"Error",Snackbar.LENGTH_LONG).show(); } }); }catch (Exception e){ e.printStackTrace(); } break; } return true; } void getMaterialList(){ progressDialog.show(); try{ networkService.getAllResources().enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { JSONObject reponseBody = new JSONObject(response.body().string()); if(reponseBody.has("materials")){ JSONArray materials = reponseBody.getJSONArray("materials"); materialArrayList = new ArrayList<>(); for(int i=0;i<materials.length();i++) { JSONObject materialObject = materials.getJSONObject(i); materialArrayList.add(new MaterialModel(materialObject.getInt("mid"),materialObject.getString("material_name"), materialObject.getString("material_unit"), materialObject.getString("material_price"), materialObject.getString("picture"),"0",false)); } mAdapter = new ChooseMaterialAdapter(context, materialArrayList, new ChooseItem() { @Override public void onItemClicked(int position, boolean isSelected) { materialArrayList.get(position).setMaterialSelected(isSelected); Toast.makeText(context, "" + materialArrayList.get(position).getMaterialName(), Toast.LENGTH_LONG).show(); } }, new ChooseMaterialAdapter.OnEditTextChanged() { @Override public void onTextChanged(int position, String charSeq) { materialArrayList.get(position).setSelectedUnits(charSeq); } }); materialListView.setAdapter(mAdapter); progressDialog.dismiss(); } } catch (IOException e) { e.printStackTrace(); }catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); }catch(Exception e){ e.printStackTrace(); } } ArrayList<MaterialModel> getSelectedMaterials(ArrayList<MaterialModel> materialArrayList){ ArrayList<MaterialModel> selectedMaterialsList = new ArrayList<>(); for(MaterialModel workerModel:materialArrayList){ if (workerModel.isMaterialSelected()) selectedMaterialsList.add(workerModel); } return selectedMaterialsList; } JSONObject formJson(){ JSONObject formData = new JSONObject(); try { formData.put("cid",selectedContractor.getNid()); JSONArray workers = new JSONArray(); for(int i=0;i<selectedWorkers.size();i++){ workers.put(i,selectedWorkers.get(i).getUid()); } JSONArray materials = new JSONArray(); for(int i=0;i<getSelectedMaterials(materialArrayList).size();i++){ JSONObject materialObject = new JSONObject(); materialObject.put("id",getSelectedMaterials(materialArrayList).get(i).getMid()); materialObject.put("qty",getSelectedMaterials(materialArrayList).get(i).getSelectedUnits()); materialObject.put("unit",getSelectedMaterials(materialArrayList).get(i).getMaterialUnit()); materials.put(i,materialObject); } formData.put("who",workers); formData.put("material",materials); Calendar c = Calendar.getInstance(); System.out.println("Current time => " + c.getTime()); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); String formattedDate = df.format(c.getTime()); formData.put("date",formattedDate); formData.put("submit","Create new Assigment name"); Log.i("json",""+formData); } catch (JSONException e) { e.printStackTrace(); } return formData; } }
import javax.swing.*; import java.awt.*; // 颜色选择列表 public class Colorlist extends JPanel { static final long serialVersionUID = 1471001741; public Colorlist() { // 得到监听器实例 EventListener el = EventListener.getInstance(); // 为列表使用二行四列的栅格布局 this.setLayout(new GridLayout(2, 4, 2, 2)); // 通过颜色数组快速构建前七个按钮 Color[] colorArray = { Color.BLACK, Color.BLUE, Color.YELLOW, Color.GREEN, Color.PINK, Color.RED, Color.CYAN }; for (Color item : colorArray) { JButton tmp = new JButton(); tmp.setBackground(item); // 为该按钮添加点击监听,详见EventListener->actionPerformed tmp.addActionListener(el); this.add(tmp); } // 最后一个按钮是自定义颜色 JButton customColor = new JButton(); customColor.setBackground(Color.WHITE); // 为该按钮加入与其它按钮相同的监听 customColor.addActionListener(el); // 点击弹出颜色对话框,将选中颜色设置为背景色 // 注意:经过测试,多个ActionListener的情况下会优先执行后添加的 customColor.addActionListener(e -> { Color selectedColor = JColorChooser.showDialog(null, "自定义颜色", Color.BLACK); if (selectedColor == null) { selectedColor = Color.WHITE; } customColor.setBackground(selectedColor); }); this.add(customColor); } }
/** * Copyright 2014 Internet2 * * 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. */ /** * @author mchyzer * $Id: GrouperSetEnum.java,v 1.5 2009-10-26 02:26:07 mchyzer Exp $ */ package edu.internet2.middleware.grouper.grouperSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import edu.internet2.middleware.grouper.attr.AttributeDefAssignmentType; import edu.internet2.middleware.grouper.attr.AttributeDefNameSet; import edu.internet2.middleware.grouper.attr.assign.AttributeAssignActionSet; import edu.internet2.middleware.grouper.attr.assign.AttributeAssignActionType; import edu.internet2.middleware.grouper.internal.util.GrouperUuid; import edu.internet2.middleware.grouper.misc.GrouperDAOFactory; import edu.internet2.middleware.grouper.permissions.role.RoleHierarchyType; import edu.internet2.middleware.grouper.permissions.role.RoleSet; import edu.internet2.middleware.grouper.util.GrouperUtil; /** * */ public enum GrouperSetEnum { /** attribute set grouper set */ ATTRIBUTE_SET { /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfThenImmediate(java.lang.String, java.lang.String, boolean) */ @Override public GrouperSet findByIfThenImmediate(String idIf, String idThen, boolean exceptionIfNotFound) { //lets see if this one already exists AttributeDefNameSet existingAttributeDefNameSet = GrouperDAOFactory.getFactory() .getAttributeDefNameSet().findByIfThenImmediate(idIf, idThen, exceptionIfNotFound); return existingAttributeDefNameSet; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfHasElementId(java.lang.String) */ @Override public Set<? extends GrouperSet> findByIfHasElementId(String idIf) { Set<AttributeDefNameSet> existingAttributeDefNameSetList = GrouperDAOFactory.getFactory().getAttributeDefNameSet().findByIfHasAttributeDefNameId(idIf); return existingAttributeDefNameSetList; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfThenHasElementId(java.lang.String, java.lang.String) */ @Override public Set<? extends GrouperSet> findByIfThenHasElementId(String idForThens, String idForIfs) { Set<AttributeDefNameSet> candidateAttributeDefNameSetToRemove = GrouperDAOFactory.getFactory().getAttributeDefNameSet().findByIfThenHasAttributeDefNameId( idForThens, idForIfs); return candidateAttributeDefNameSetToRemove; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByThenHasElementId(java.lang.String) */ @Override public Set<? extends GrouperSet> findByThenHasElementId(String idThen) { Set<AttributeDefNameSet> existingAttributeDefNameSetList = GrouperDAOFactory.getFactory().getAttributeDefNameSet().findByThenHasAttributeDefNameId(idThen); return existingAttributeDefNameSetList; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#newInstance(String, String, int, String) */ @Override public GrouperSet newInstance(String ifHasId, String thenHasId, int depth, String uuid) { AttributeDefNameSet attributeDefNameSet = new AttributeDefNameSet(); attributeDefNameSet.setId(StringUtils.isBlank(uuid) ? GrouperUuid.getUuid() : uuid ); attributeDefNameSet.setDepth(depth); attributeDefNameSet.setIfHasAttributeDefNameId(ifHasId); attributeDefNameSet.setThenHasAttributeDefNameId(thenHasId); attributeDefNameSet.setType(depth == 1 ? AttributeDefAssignmentType.immediate : AttributeDefAssignmentType.effective); return attributeDefNameSet; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findById(java.lang.String, boolean) */ @Override public GrouperSet findById(String id, boolean exceptionIfNull) { return GrouperDAOFactory.getFactory() .getAttributeDefNameSet().findById(id, exceptionIfNull); } }, /** role set grouper set */ ROLE_SET { /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfThenImmediate(java.lang.String, java.lang.String, boolean) */ @Override public GrouperSet findByIfThenImmediate(String idIf, String idThen, boolean exceptionIfNotFound) { //lets see if this one already exists RoleSet existingRoleSet = GrouperDAOFactory.getFactory() .getRoleSet().findByIfThenImmediate(idIf, idThen, exceptionIfNotFound); return existingRoleSet; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfHasElementId(java.lang.String) */ @Override public Set<? extends GrouperSet> findByIfHasElementId(String idIf) { Set<RoleSet> existingRoleSetList = GrouperDAOFactory.getFactory().getRoleSet().findByIfHasRoleId(idIf); return existingRoleSetList; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfThenHasElementId(java.lang.String, java.lang.String) */ @Override public Set<? extends GrouperSet> findByIfThenHasElementId(String idForThens, String idForIfs) { Set<RoleSet> candidateRoleSetToRemove = GrouperDAOFactory.getFactory().getRoleSet().findByIfThenHasRoleId( idForThens, idForIfs); return candidateRoleSetToRemove; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByThenHasElementId(java.lang.String) */ @Override public Set<? extends GrouperSet> findByThenHasElementId(String idThen) { Set<RoleSet> existingRoleSetList = GrouperDAOFactory.getFactory().getRoleSet().findByThenHasRoleId(idThen); return existingRoleSetList; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#newInstance(String, String, int, String) */ @Override public GrouperSet newInstance(String ifHasId, String thenHasId, int depth, String uuid) { RoleSet roleSet = new RoleSet(); roleSet.setId(StringUtils.isBlank(uuid) ? GrouperUuid.getUuid() : uuid); roleSet.setDepth(depth); roleSet.setIfHasRoleId(ifHasId); roleSet.setThenHasRoleId(thenHasId); roleSet.setType(depth == 1 ? RoleHierarchyType.immediate : RoleHierarchyType.effective); return roleSet; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findById(java.lang.String, boolean) */ @Override public GrouperSet findById(String id, boolean exceptionIfNull) { return GrouperDAOFactory.getFactory() .getAttributeDefNameSet().findById(id, exceptionIfNull); } }, /** attribute assign action set grouper set */ ATTRIBUTE_ASSIGN_ACTION_SET { /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfThenImmediate(java.lang.String, java.lang.String, boolean) */ @Override public GrouperSet findByIfThenImmediate(String idIf, String idThen, boolean exceptionIfNotFound) { //lets see if this one already exists AttributeAssignActionSet existingAttributeAssignActionSet = GrouperDAOFactory.getFactory() .getAttributeAssignActionSet().findByIfThenImmediate(idIf, idThen, exceptionIfNotFound); return existingAttributeAssignActionSet; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfHasElementId(java.lang.String) */ @Override public Set<? extends GrouperSet> findByIfHasElementId(String idIf) { Set<AttributeAssignActionSet> existingAttributeAssignActionSetList = GrouperDAOFactory.getFactory().getAttributeAssignActionSet().findByIfHasAttributeAssignActionId(idIf); return existingAttributeAssignActionSetList; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByIfThenHasElementId(java.lang.String, java.lang.String) */ @Override public Set<? extends GrouperSet> findByIfThenHasElementId(String idForThens, String idForIfs) { Set<AttributeAssignActionSet> candidateAttributeAssignActionSetToRemove = GrouperDAOFactory.getFactory().getAttributeAssignActionSet().findByIfThenHasAttributeAssignActionId( idForThens, idForIfs); return candidateAttributeAssignActionSetToRemove; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findByThenHasElementId(java.lang.String) */ @Override public Set<? extends GrouperSet> findByThenHasElementId(String idThen) { Set<AttributeAssignActionSet> existingAttributeAssignActionSetList = GrouperDAOFactory.getFactory().getAttributeAssignActionSet().findByThenHasAttributeAssignActionId(idThen); return existingAttributeAssignActionSetList; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#newInstance(String, String, int, String) */ @Override public GrouperSet newInstance(String ifHasId, String thenHasId, int depth, String uuid) { AttributeAssignActionSet attributeAssignActionSet = new AttributeAssignActionSet(); attributeAssignActionSet.setId(StringUtils.isBlank(uuid) ? GrouperUuid.getUuid() : uuid); attributeAssignActionSet.setDepth(depth); attributeAssignActionSet.setIfHasAttrAssignActionId(ifHasId); attributeAssignActionSet.setThenHasAttrAssignActionId(thenHasId); attributeAssignActionSet.setType(depth == 1 ? AttributeAssignActionType.immediate : AttributeAssignActionType.effective); return attributeAssignActionSet; } /** * * @see edu.internet2.middleware.grouper.grouperSet.GrouperSetEnum#findById(java.lang.String, boolean) */ @Override public GrouperSet findById(String id, boolean exceptionIfNull) { return GrouperDAOFactory.getFactory() .getAttributeAssignActionSet().findById(id, exceptionIfNull); } } ; /** * parent child set for calulcating */ private static class GrouperSetPair implements Comparable { /** parent */ private GrouperSet parent; /** child */ private GrouperSet child; /** number of hops from one to another */ private int depth; /** * sort these by depth so we create the path as we go * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { return ((Integer)this.depth).compareTo(((GrouperSetPair)o).depth); } } /** * find an grouper set, better be here * @param grouperSetPairs * @param grouperSets * @param id to find * @return the def name set */ private GrouperSet find(List<GrouperSetPair> grouperSetPairs, List<GrouperSet> grouperSets, String id) { for (GrouperSetPair grouperSetPair : grouperSetPairs) { if (StringUtils.equals(id, grouperSetPair.parent.__getId())) { return grouperSetPair.parent; } if (StringUtils.equals(id, grouperSetPair.child.__getId())) { return grouperSetPair.child; } } for (GrouperSet grouperSet : GrouperUtil.nonNull(grouperSets)) { if (StringUtils.equals(id, grouperSet.__getId())) { return grouperSet; } } String grouperElementIfName = "<unknown>"; String grouperElementThenName = "<unknown>"; try { GrouperSet grouperSet = GrouperDAOFactory.getFactory() .getAttributeDefNameSet().findById(id, true); grouperElementIfName = grouperSet.__getIfHasElement().__getName(); grouperElementThenName = grouperSet.__getThenHasElement().__getName(); } catch (Exception e) { grouperElementIfName = "<exception: " + e.getMessage() + ">"; grouperElementThenName = "<exception: " + e.getMessage() + ">"; } throw new RuntimeException("Cant find grouper set with id: " + id + " ifName: " + grouperElementIfName + ", thenName: " + grouperElementThenName); } /** * find an attribute def name set, better be here * @param grouperSetPairs * @param grouperSets * @param ifHasId * @param thenHasId * @param depth is the depth expecting * @return the def name set */ private GrouperSet find(List<GrouperSetPair> grouperSetPairs, List<GrouperSet> grouperSets, String ifHasId, String thenHasId, int depth) { //are we sure we are getting the right one here??? for (GrouperSetPair attributeDefNameSetPair : grouperSetPairs) { if (StringUtils.equals(ifHasId, attributeDefNameSetPair.parent.__getIfHasElementId()) && StringUtils.equals(thenHasId, attributeDefNameSetPair.parent.__getThenHasElementId()) && depth == attributeDefNameSetPair.parent.__getDepth()) { return attributeDefNameSetPair.parent; } if (StringUtils.equals(ifHasId, attributeDefNameSetPair.child.__getIfHasElementId()) && StringUtils.equals(thenHasId, attributeDefNameSetPair.child.__getThenHasElementId()) && depth == attributeDefNameSetPair.child.__getDepth()) { return attributeDefNameSetPair.child; } } for (GrouperSet grouperSet : GrouperUtil.nonNull(grouperSets)) { if (StringUtils.equals(ifHasId, grouperSet.__getIfHasElementId()) && StringUtils.equals(thenHasId, grouperSet.__getThenHasElementId()) && depth == grouperSet.__getDepth()) { return grouperSet; } } throw new RuntimeException("Cant find grouper set with ifHasId: " + ifHasId + ", thenHasId: " + thenHasId + ", depth: " + depth); } /** * find an element by if then immediate (or null * @param idIf * @param idThen * @param exceptionIfNotFound true if exception if not found * @return the element if found */ public abstract GrouperSet findByIfThenImmediate(String idIf, String idThen, boolean exceptionIfNotFound); /** * find set of sets which have a then as a certain value * @param idThen * @return the set */ public abstract Set<? extends GrouperSet> findByThenHasElementId(String idThen); /** * find set of sets which have an if as a certain value * @param idIf * @return the set */ public abstract Set<? extends GrouperSet> findByIfHasElementId(String idIf); /** * find by id if has id * @param id * @param exceptionIfNull * @return the grouper set */ public abstract GrouperSet findById(String id, boolean exceptionIfNull); /** * new instance of the grouper set object * @param ifHasId * @param thenHasId * @param depth * @param uuid is uuid or null if generate one * @return the grouper set */ public abstract GrouperSet newInstance(String ifHasId, String thenHasId, int depth, String uuid); /** * find canidates to delete by if and then * @param idForThens * @param idForIfs * @return the canidate set to delete */ public abstract Set<? extends GrouperSet> findByIfThenHasElementId(String idForThens, String idForIfs); /** logger */ @SuppressWarnings("unused") private static final Log LOG = GrouperUtil.getLog(GrouperSetEnum.class); /** * * @param containerSetElement * @param newElement * @param uuid is the uuid or null to generate * @return true if added, false if already there */ public boolean addToGrouperSet(GrouperSetElement containerSetElement, GrouperSetElement newElement, String uuid) { //TODO, if doesnt point to itself, add a self referential record if (LOG.isDebugEnabled()) { LOG.debug("Adding to grouper set " + this.name() + ": " + containerSetElement.__getName() + "\n (" + containerSetElement.__getId() + ")" + " this attribute: " + newElement.__getName() + " (" + newElement.__getId() + ")"); } //lets see if this one already exists GrouperSet existingSet = this.findByIfThenImmediate(containerSetElement.__getId(), newElement.__getId(), false); if (existingSet != null) { return false; } //lets see what implies having this existing def name Set<? extends GrouperSet> existingGrouperSetList = this.findByThenHasElementId(containerSetElement.__getId()); //lets see what having this new def name implies Set<? extends GrouperSet> newGrouperSetList = this.findByIfHasElementId(newElement.__getId()); List<GrouperSetPair> grouperSetPairs = new ArrayList<GrouperSetPair>(); List<GrouperSet> newSets = new ArrayList<GrouperSet>(); //now lets merge the two lists //they each must have one member for (GrouperSet parent : existingGrouperSetList) { for (GrouperSet child : newGrouperSetList) { GrouperSetPair grouperSetPair = new GrouperSetPair(); grouperSetPair.depth = 1 + parent.__getDepth() + child.__getDepth(); grouperSetPair.parent = parent; grouperSetPair.child = child; grouperSetPairs.add(grouperSetPair); if (LOG.isDebugEnabled()) { GrouperSetElement ifHasElement = parent.__getIfHasElement(); GrouperSetElement thenHasElement = child.__getThenHasElement(); LOG.debug("Found pair to manage " + this.name() + ": " + ifHasElement.__getName() + "\n (parent set: " + parent.__getId() + ", ifHasNameId: " + ifHasElement.__getId() + ")" + "\n to: " + thenHasElement.__getName() + "(child set: " + child.__getId() + ", thenHasNameId: " + thenHasElement.__getId() + ")" + "\n depth: " + grouperSetPair.depth ); } } } //sort by depth so we process correctly Collections.sort(grouperSetPairs); //if has circular, then do more queries to be sure boolean hasCircularReference = false; OUTER: for (GrouperSetPair grouperSetPair : grouperSetPairs) { //check for circular reference if (StringUtils.equals(grouperSetPair.parent.__getIfHasElementId(), grouperSetPair.child.__getThenHasElementId()) && grouperSetPair.depth > 0) { if (LOG.isDebugEnabled()) { GrouperSetElement grouperSetElement = grouperSetPair.parent.__getIfHasElement(); LOG.debug("Found circular reference, skipping " + this.name() + ": " + grouperSetElement.__getName() + "\n (" + grouperSetPair.parent.__getIfHasElementId() + ", depth: " + grouperSetPair.depth + ")"); } hasCircularReference = true; //dont want to point to ourselves, circular reference, skip it continue; } // if one is passed in, and this is the one depth 1 set, then use whats passed in, otherwise null // means generate String theUuid = (grouperSetPair.depth == 1 && !StringUtils.isBlank(uuid)) ? uuid : null; GrouperSet grouperSet = this.newInstance(grouperSetPair.parent.__getIfHasElementId(), grouperSetPair.child.__getThenHasElementId(), grouperSetPair.depth, theUuid); if (LOG.isDebugEnabled()) { GrouperSetElement ifHasElement = grouperSetPair.parent.__getIfHasElement(); GrouperSetElement thenHasElement = grouperSetPair.child.__getThenHasElement(); LOG.debug("Adding pair " + this.name() + ": " + grouperSet.__getId() + ",\n ifHas: " + ifHasElement.__getName() + "(" + ifHasElement.__getId() + "),\n thenHas: " + thenHasElement.__getName() + "(" + thenHasElement.__getId() + ")\n depth: " + grouperSetPair.depth); } //if a->a, parent is a //if a->b, parent is a //if a->b->c->d, then parent of a->d is a->c if (grouperSetPair.child.__getDepth() == 0) { grouperSet.__setParentGrouperSetId(grouperSetPair.parent.__getId()); } else { //check for same destination circular reference if (StringUtils.equals(grouperSetPair.parent.__getThenHasElementId(), grouperSetPair.child.__getThenHasElementId()) && grouperSetPair.parent.__getDepth() > 0 && grouperSetPair.child.__getDepth() > 0) { if (LOG.isDebugEnabled()) { GrouperSetElement ifGrouperSetElement = grouperSetPair.parent.__getIfHasElement(); GrouperSetElement thenGrouperSetElement = grouperSetPair.child.__getThenHasElement(); LOG.debug("Found same destination circular reference, skipping " + this.name() + ": " + grouperSet.__getId() + ",\n ifHas: " + ifGrouperSetElement.__getName() + "(" + ifGrouperSetElement.__getId() + "),\n thenHas: " + thenGrouperSetElement.__getName() + "(" + thenGrouperSetElement.__getId() + ")\n depth: " + grouperSetPair.depth); } hasCircularReference = true; //dont want to point to ourselves, circular reference, skip it continue; } } //if we found a circular reference in the lower levels, see if we are circling in on ourselves if (hasCircularReference) { int timeToLive = 1000; //loop through parents and children and look for overlap GrouperSet currentParentParent = grouperSetPair.parent; while(timeToLive-- > 0) { GrouperSet currentChildParent = grouperSetPair.child; while(timeToLive-- > 0) { if (StringUtils.equals(currentChildParent.__getThenHasElementId(), currentParentParent.__getThenHasElementId())) { if (LOG.isDebugEnabled()) { GrouperSetElement grouperSetElement = grouperSetPair.parent.__getIfHasElement(); LOG.debug("Found inner circular reference, skipping " + this.name() + ": " + grouperSetElement.__getName() + "\n (" + grouperSetPair.parent.__getIfHasElementId() + ", depth: " + grouperSetPair.depth + ")"); } //dont want to point to in a circle, circular reference, skip it continue OUTER; } GrouperSet previousChildParent = currentChildParent; currentChildParent = currentChildParent.__getParentGrouperSet(); //all the way up the chain if (currentChildParent == previousChildParent) { break; } } GrouperSet previousParentParent = currentParentParent; currentParentParent = currentParentParent.__getParentGrouperSet(); //all the way up the chain if (currentParentParent == previousParentParent) { break; } } if (timeToLive <= 0) { throw new RuntimeException("TimeToLive too low! " + timeToLive); } } //if we still need to do this if (StringUtils.isBlank(grouperSet.__getParentGrouperSetId())) { //find the parent of the child GrouperSet parentOfChild = this.find(grouperSetPairs, newSets, grouperSetPair.child.__getParentGrouperSetId()); //check for circular reference if (StringUtils.equals(grouperSetPair.parent.__getIfHasElementId(), parentOfChild.__getThenHasElementId()) && grouperSetPair.depth > 1) { if (LOG.isDebugEnabled()) { GrouperSetElement grouperSetElement = grouperSetPair.parent.__getIfHasElement(); LOG.debug("Found parent circular reference, skipping " + this.name() + ": " + grouperSetElement.__getName() + "\n (" + grouperSetPair.parent.__getIfHasElementId() + ", depth: " + grouperSetPair.depth + ")"); } hasCircularReference = true; //dont want to point to ourselves, circular reference, skip it continue; } //find the set for the parent start to child parent end GrouperSet parent = this.find(grouperSetPairs, newSets, grouperSetPair.parent.__getIfHasElementId(), parentOfChild.__getThenHasElementId(), grouperSetPair.depth-1); grouperSet.__setParentGrouperSetId(parent.__getId()); } if (LOG.isDebugEnabled()) { GrouperSetElement ifHasAttributeDefName = grouperSetPair.parent.__getIfHasElement(); GrouperSetElement thenHasAttributeDefName = grouperSetPair.child.__getThenHasElement(); GrouperSet parent = grouperSet.__getParentGrouperSet(); GrouperSetElement parentIfHasAttributeDefName = parent.__getIfHasElement(); GrouperSetElement parentThenHasAttributeDefName = parent.__getThenHasElement(); LOG.debug("Added pair " + this.name() + ": " + grouperSet.__getId() + ",\n ifHas: " + ifHasAttributeDefName.__getName() + "(" + ifHasAttributeDefName.__getId() + "),\n thenHas: " + thenHasAttributeDefName.__getName() + "(" + thenHasAttributeDefName.__getId() + "), parent: " + grouperSet.__getParentGrouperSetId() + ",\n parentIfHas: " + parentIfHasAttributeDefName.__getName() + "(" + parentIfHasAttributeDefName.__getId() + "),\n parentThenHas: " + parentThenHasAttributeDefName.__getName() + "(" + parentThenHasAttributeDefName.__getId() + ")"); } grouperSet.saveOrUpdate(); newSets.add(grouperSet); } return true; } /** * find a grouper set, better be here * @param grouperSets * @param ifHasId * @param thenHasId * @param depth is the depth expecting * @param exceptionIfNull * @return the def name set */ private GrouperSet findInCollection( Collection<? extends GrouperSet> grouperSets, String ifHasId, String thenHasId, int depth, boolean exceptionIfNull) { //are we sure we are getting the right one here??? for (GrouperSet grouperSet : GrouperUtil.nonNull(grouperSets)) { if (StringUtils.equals(ifHasId, grouperSet.__getIfHasElementId()) && StringUtils.equals(thenHasId, grouperSet.__getThenHasElementId()) && depth == grouperSet.__getDepth()) { return grouperSet; } } if (exceptionIfNull) { throw new RuntimeException("Cant find grouper set with id: " + ifHasId + ", " + thenHasId + ", " + depth); } return null; } /** * @param setToRemoveFrom * @param elementToRemove * @return true if removed, false if already removed */ public boolean removeFromGrouperSet(GrouperSetElement setToRemoveFrom, GrouperSetElement elementToRemove) { if (LOG.isDebugEnabled()) { LOG.debug("Removing from attribute set " + this.name() + ": " + setToRemoveFrom.__getName() + "\n (" + setToRemoveFrom.__getId() + ")" + " this attribute: " + elementToRemove.__getName() + " (" + elementToRemove.__getId() + ")"); } //lets see what implies having this existing def name Set<? extends GrouperSet> candidateGrouperSetToRemove = this.findByIfThenHasElementId(setToRemoveFrom.__getId(), elementToRemove.__getId()); Set<GrouperSet> grouperSetWillRemove = new HashSet<GrouperSet>(); Set<String> attributeDefNameSetIdsWillRemove = new HashSet<String>(); GrouperSet setToRemove = findInCollection( candidateGrouperSetToRemove, setToRemoveFrom.__getId(), elementToRemove.__getId(), 1, false); if (setToRemove == null) { return false; } grouperSetWillRemove.add(setToRemove); attributeDefNameSetIdsWillRemove.add(setToRemove.__getId()); candidateGrouperSetToRemove.remove(setToRemove); Iterator<? extends GrouperSet> iterator = candidateGrouperSetToRemove.iterator(); //get the records whose parent ends on the node being cut, and who ends on the other node being cut. //e.g. if A -> B -> C, and B -> C is being cut, then delete A -> C while (iterator.hasNext()) { GrouperSet grouperSet = iterator.next(); // if (LOG.isDebugEnabled()) { // AttributeDefName ifHasAttributeDefName = attributeDefNameSet.getIfHasAttributeDefName(); // AttributeDefName thenHasAttributeDefName = attributeDefNameSet.getThenHasAttributeDefName(); // LOG.debug("Initial check " + attributeDefNameSet.getId() + ",\n ifHas: " // + ifHasAttributeDefName.getName() + "(" + ifHasAttributeDefName.getId() + "),\n thenHas: " // + thenHasAttributeDefName.getName() + "(" + thenHasAttributeDefName.getId() + ")\n depth: " // + attributeDefNameSet.getDepth()); // } // String logPrefix = "Skipping initial set to remove "; if (StringUtils.equals(grouperSet.__getThenHasElementId(), elementToRemove.__getId())) { GrouperSet parentSet = grouperSet.__getParentGrouperSet(); if (StringUtils.equals(parentSet.__getThenHasElementId(), setToRemoveFrom.__getId())) { grouperSetWillRemove.add(grouperSet); attributeDefNameSetIdsWillRemove.add(grouperSet.__getId()); iterator.remove(); // logPrefix = "Found initial set to remove "; } } // if (LOG.isDebugEnabled()) { // AttributeDefName ifHasAttributeDefName = attributeDefNameSet.getIfHasAttributeDefName(); // AttributeDefName thenHasAttributeDefName = attributeDefNameSet.getThenHasAttributeDefName(); // LOG.debug(logPrefix + attributeDefNameSet.getId() + ",\n ifHas: " // + ifHasAttributeDefName.getName() + "(" + ifHasAttributeDefName.getId() + "),\n thenHas: " // + thenHasAttributeDefName.getName() + "(" + thenHasAttributeDefName.getId() + ")\n depth: " // + attributeDefNameSet.getDepth()); // } } int setToRemoveSize = grouperSetWillRemove.size(); int timeToLive = 100; while (timeToLive-- > 0) { iterator = candidateGrouperSetToRemove.iterator(); //see if any parents destroyed while (iterator.hasNext()) { GrouperSet grouperSet = iterator.next(); //if the parent is there, it is gone // String logPrefix = "Skipping set to remove "; if (attributeDefNameSetIdsWillRemove.contains(grouperSet.__getParentGrouperSetId())) { grouperSetWillRemove.add(grouperSet); attributeDefNameSetIdsWillRemove.add(grouperSet.__getId()); iterator.remove(); // logPrefix = "Found set to remove "; } // if (LOG.isDebugEnabled()) { // AttributeDefName ifHasAttributeDefName = attributeDefNameSet.getIfHasAttributeDefName(); // AttributeDefName thenHasAttributeDefName = attributeDefNameSet.getThenHasAttributeDefName(); // LOG.debug(logPrefix + attributeDefNameSet.getId() + ",\n ifHas: " // + ifHasAttributeDefName.getName() + "(" + ifHasAttributeDefName.getId() + "),\n thenHas: " // + thenHasAttributeDefName.getName() + "(" + thenHasAttributeDefName.getId() + ")\n depth: " // + attributeDefNameSet.getDepth()); // } } //if we didnt make progress, we are done if(setToRemoveSize == grouperSetWillRemove.size()) { break; } setToRemoveSize = grouperSetWillRemove.size(); } if (timeToLive <= 0) { throw new RuntimeException("TimeToLive is under 0"); } //reverse sort by depth List<GrouperSet> setsToRemove = new ArrayList<GrouperSet>(grouperSetWillRemove); Collections.sort(setsToRemove, new Comparator<GrouperSet>() { public int compare(GrouperSet o1, GrouperSet o2) { return ((Integer)o1.__getDepth()).compareTo(o2.__getDepth()); } }); Collections.reverse(setsToRemove); for (GrouperSet grouperSet : setsToRemove) { if (LOG.isDebugEnabled()) { GrouperSetElement ifHasElement = grouperSet.__getIfHasElement(); GrouperSetElement thenHasElement = grouperSet.__getThenHasElement(); LOG.debug("Deleting set " + this.name() + ": " + grouperSet.__getId() + ",\n ifHas: " + ifHasElement.__getName() + "(" + ifHasElement.__getId() + "),\n thenHas: " + thenHasElement.__getName() + "(" + thenHasElement.__getId() + ")\n depth: " + grouperSet.__getDepth()); } grouperSet.delete(); } // for (AttributeDefNameSet attributeDefNameSet : candidateAttributeDefNameSetToRemove) { // if (LOG.isDebugEnabled()) { // AttributeDefName ifHasAttributeDefName = attributeDefNameSet.getIfHasAttributeDefName(); // AttributeDefName thenHasAttributeDefName = attributeDefNameSet.getThenHasAttributeDefName(); // LOG.debug("Not deleting set " + attributeDefNameSet.getId() + ",\n ifHas: " // + ifHasAttributeDefName.getName() + "(" + ifHasAttributeDefName.getId() + "),\n thenHas: " // + thenHasAttributeDefName.getName() + "(" + thenHasAttributeDefName.getId() + ")\n depth: " // + attributeDefNameSet.getDepth()); // } // } //now, if there is A -> B -> C, and you cut B -> C, then you need to remove A -> C return true; } }
package DrzewoRB; public interface Sortowania { Object[] sort(Object[] Lists); }
package com.blossomproject.core.user; /** * Created by Maël Gargadennnec on 04/05/2017. */ public interface UserMailService { void sendAccountCreationEmail(UserDTO user, String token) throws Exception; void sendChangePasswordEmail(UserDTO user, String token) throws Exception; }
package io.evercam.network.onvif; import io.evercam.network.EvercamDiscover; import io.evercam.network.discovery.DiscoveredCamera; import io.evercam.network.discovery.IpTranslator; import java.io.StringReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Locale; import java.util.UUID; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.stream.InputNode; import org.simpleframework.xml.stream.NodeBuilder; public abstract class OnvifDiscovery { private static final int SOCKET_TIMEOUT = 4000; private static final String PROBE_MESSAGE = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><s:Header><a:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</a:Action><a:MessageID>uuid:21859bf9-6193-4c8a-ad50-d082e6d296ab</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><a:To s:mustUnderstand=\"1\">urn:schemas-xmlsoap-org:ws:2005:04:discovery</a:To></s:Header><s:Body><Probe xmlns=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\"><d:Types xmlns:d=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:dp0=\"http://www.onvif.org/ver10/network/wsdl\">dp0:NetworkVideoTransmitter</d:Types></Probe></s:Body></s:Envelope>"; private static final String PROBE_IP = "239.255.255.250"; private static final int PROBE_PORT = 3702; private static final String SCOPE_NAME = "onvif://www.onvif.org/name/"; private static final String SCOPE_HARDWARE = "onvif://www.onvif.org/hardware/"; public OnvifDiscovery() { } public ArrayList<DiscoveredCamera> probe() { ArrayList<DiscoveredCamera> cameraList = new ArrayList<DiscoveredCamera>(); try { DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.setSoTimeout(SOCKET_TIMEOUT); InetAddress multicastAddress = InetAddress.getByName(PROBE_IP); if (multicastAddress == null) { // System.out.println("InetAddress.getByName() for multicast returns null"); return cameraList; } // Send the UDP probe message String soapMessage = getProbeSoapMessage(); // System.out.println(soapMessage); byte[] soapMessageByteArray = soapMessage.getBytes(); DatagramPacket datagramPacketSend = new DatagramPacket(soapMessageByteArray, soapMessageByteArray.length, multicastAddress, PROBE_PORT); datagramSocket.send(datagramPacketSend); ArrayList<String> uuidArrayList = new ArrayList<String>(); while (true) { // System.out.println("Receiving..."); byte[] responseMessageByteArray = new byte[4000]; DatagramPacket datagramPacketRecieve = new DatagramPacket(responseMessageByteArray, responseMessageByteArray.length); datagramSocket.receive(datagramPacketRecieve); String responseMessage = new String(datagramPacketRecieve.getData()); EvercamDiscover.printLogMessage("\nResponse Message:\n" + responseMessage); StringReader stringReader = new StringReader(responseMessage); InputNode localInputNode = NodeBuilder.read(stringReader); EnvelopeProbeMatches localEnvelopeProbeMatches = new Persister().read( EnvelopeProbeMatches.class, localInputNode); if (localEnvelopeProbeMatches.BodyProbeMatches.ProbeMatches.listProbeMatches.size() <= 0) { continue; } ProbeMatch localProbeMatch = localEnvelopeProbeMatches.BodyProbeMatches.ProbeMatches.listProbeMatches .get(0); // EvercamDiscover.printLogMessage("Probe matches with UUID:\n" + // localProbeMatch.EndpointReference.Address + " URL: " + // localProbeMatch.XAddrs); if (uuidArrayList.contains(localProbeMatch.EndpointReference.Address)) { EvercamDiscover.printLogMessage("ONVIFDiscovery: Address " + localProbeMatch.EndpointReference.Address + " already added"); continue; } uuidArrayList.add(localProbeMatch.EndpointReference.Address); DiscoveredCamera discoveredCamera = getCameraFromProbeMatch(localProbeMatch); if(discoveredCamera.hasValidIpv4Address()) { onActiveOnvifDevice(discoveredCamera); cameraList.add(discoveredCamera); } } } catch (Exception e) { // ONVIF timeout. Don't print anything. } return cameraList; } private static String getProbeSoapMessage() { return PROBE_MESSAGE.replaceFirst("<a:MessageID>uuid:.+?</a:MessageID>", "<a:MessageID>uuid:" + UUID.randomUUID().toString() + "</a:MessageID>"); } private static DiscoveredCamera getCameraFromProbeMatch(ProbeMatch probeMatch) { DiscoveredCamera discoveredCamera = null; try { String[] urlArray = probeMatch.XAddrs.split("\\s"); String[] scopeArray = probeMatch.Scopes.split("\\s"); String scopeModel = ""; String scopeVendor = ""; for (String scope : scopeArray) { final String URL_SPACE = "%20"; if (scope.contains(SCOPE_NAME)) { scopeVendor = scope.replace(SCOPE_NAME, "").replace(URL_SPACE, " "); } if (scope.contains(SCOPE_HARDWARE)) { scopeModel = scope.replace(SCOPE_HARDWARE, "").replace(URL_SPACE, " "); } } //Make the ONVIF scopes match vendor + model pattern if(scopeVendor.contains(scopeModel)) { scopeVendor = scopeVendor.replace(scopeModel, "").replace(" ", ""); } try { String ipAddressString = ""; int httpPort = 0; for(String urlString : urlArray) { URL localURL = new URL(urlString); String urlHost = localURL.getHost(); //Make sure it's a valid local IPv4 address if(IpTranslator.isLocalIpv4(urlHost)) { ipAddressString = urlHost; httpPort = localURL.getPort(); if (httpPort == -1) { httpPort = 80; } break; //Only break when it gets a valid address } else { EvercamDiscover.printLogMessage("Discarded a ONVIF IP: " + urlHost); } } discoveredCamera = new DiscoveredCamera(ipAddressString); discoveredCamera.setHttp(httpPort); if (!scopeVendor.isEmpty()) { discoveredCamera.setVendor(scopeVendor.toLowerCase(Locale.UK)); } if (!scopeModel.isEmpty()) { discoveredCamera.setModel(scopeModel.toLowerCase(Locale.UK)); } } catch (MalformedURLException localMalformedURLException) { EvercamDiscover.printLogMessage("Cannot parse xAddr: " + probeMatch.XAddrs); } } catch (Exception e) { EvercamDiscover.printLogMessage("Parse ONVIF search result error: " + e.getMessage()); } EvercamDiscover.printLogMessage("ONVIF camera: " + discoveredCamera.toString()); return discoveredCamera; } public abstract void onActiveOnvifDevice(DiscoveredCamera discoveredCamera); }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.mobility.jsr172.wizard; import java.util.HashSet; import java.util.Set; import java.awt.Component; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openide.WizardDescriptor; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.netbeans.api.project.Project; import org.netbeans.spi.project.ui.templates.support.Templates; /** * */ public class WebServiceClientWizardDescriptor implements WizardDescriptor.FinishablePanel, WizardDescriptor.ValidatingPanel { private WizardDescriptor wizardDescriptor; private ClientInfo component = null; private String projectPath; private Project project; public static final HelpCtx HELP_CTX = new HelpCtx( "me.wcb_clientinformation" ); // NOI18N public boolean isFinishPanel(){ return true; } private final Set<ChangeListener> listeners = new HashSet<ChangeListener>(1); public final void addChangeListener(final ChangeListener l) { synchronized (listeners) { listeners.add(l); } } public final void removeChangeListener(final ChangeListener l) { synchronized (listeners) { listeners.remove(l); } } protected final void fireChangeEvent() { ChangeListener[] lst; synchronized (listeners) { lst = listeners.toArray(new ChangeListener[listeners.size()]); } final ChangeEvent ev = new ChangeEvent(this); for ( ChangeListener cl : lst ) cl.stateChanged(ev); } public Component getComponent() { if(component == null) { component = new ClientInfo(this); } return component; } public HelpCtx getHelp() { return WebServiceClientWizardDescriptor.HELP_CTX; } public boolean isValid() { boolean projectDirValid=true; String illegalChar = null; if (projectPath.indexOf('%')>=0) { projectDirValid=false; illegalChar="%"; } else if (projectPath.indexOf('&')>=0) { projectDirValid=false; illegalChar="&"; } else if (projectPath.indexOf('?')>=0) { projectDirValid=false; illegalChar="?"; } if (!projectDirValid) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(WebServiceClientWizardDescriptor.class,"MSG_InvalidProjectPath",projectPath,illegalChar)); return false; } else if (!testClassPath() ) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(WebServiceClientWizardDescriptor.class,"MSG_MissingXMLJars")); return false; } else { return component.valid(wizardDescriptor); } } public void readSettings(final Object settings) { wizardDescriptor = (WizardDescriptor) settings; component.read(wizardDescriptor); project = Templates.getProject(wizardDescriptor); projectPath = project.getProjectDirectory().getPath(); // XXX hack, TemplateWizard in final setTemplateImpl() forces new wizard's title // this name is used in NewFileWizard to modify the title wizardDescriptor.putProperty("NewFileWizard_Title", //NOI18N NbBundle.getMessage(WebServiceClientWizardDescriptor.class, "LBL_WebServiceClient"));// NOI18N } public void storeSettings(final Object settings) { final WizardDescriptor d = (WizardDescriptor) settings; component.store(d); d.putProperty("NewFileWizard_Title", null); // NOI18N } @SuppressWarnings("unused") public void validate() throws org.openide.WizardValidationException { } private boolean testClassPath() { // SourceGroup[] sgs = WebServiceClientWizardIterator.getJavaSourceGroups(project); // ClassPath classPath = ClassPath.getClassPath(sgs[0].getRootFolder(),ClassPath.COMPILE); // WebServicesClientSupport clientSupport = WebServicesClientSupport.getWebServicesClientSupport(project.getProjectDirectory()); // if (clientSupport==null) { // String mes = NbBundle.getMessage(WebServiceClientWizardDescriptor.class, "ERR_NoWebServiceClientSupport"); // NOI18N // NotifyDescriptor desc = new NotifyDescriptor.Message(mes, NotifyDescriptor.Message.ERROR_MESSAGE); // DialogDisplayer.getDefault().notify(desc); // return true; // } // if (clientSupport.getDeploymentDescriptor()==null) { // testing java project type // // test for the platform // String javaVersion = System.getProperty("java.version"); //NOI18N // if (javaVersion!=null && javaVersion.startsWith("1.4")) { //NOI18N // FileObject documentRangeFO = classPath.findResource("org/w3c/dom/ranges/DocumentRange.class"); //NOI18N // FileObject saxParserFO = classPath.findResource("com/sun/org/apache/xerces/internal/jaxp/SAXParserFactoryImpl.class"); //NOI18N // if (documentRangeFO == null || saxParserFO == null) { // ProjectClassPathExtender pce = (ProjectClassPathExtender)project.getLookup().lookup(ProjectClassPathExtender.class); // Library jaxrpclib_ext = LibraryManager.getDefault().getLibrary("jaxrpc16_xml"); //NOI18N // if (pce==null || jaxrpclib_ext == null) { // return false; // } // } // } // } return true; } }
package tech.peller.mrblackandroidwatch.api.services; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import tech.peller.mrblackandroidwatch.models.event.EventsList; /** * Created by Sam (salyasov@gmail.com) on 13.04.2018 */ public interface EventsService { @GET("/api/v1/events") Call<EventsList> getEvents(@Query("api_key") String apiKey, @Query("date") String date, @Query("venueId") Long venueId); }
/* * 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/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Model definition for NodeTemplateAggregatedList. * * <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 Compute Engine API. 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 NodeTemplateAggregatedList extends com.google.api.client.json.GenericJson { /** * [Output Only] Unique identifier for the resource; defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * A list of NodeTemplatesScopedList resources. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, NodeTemplatesScopedList> items; /** * [Output Only] Type of resource.Always compute#nodeTemplateAggregatedList for aggregated lists * of node templates. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String nextPageToken; /** * [Output Only] Server-defined URL for this resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] Informational warning message. * The value may be {@code null}. */ @com.google.api.client.util.Key private Warning warning; /** * [Output Only] Unique identifier for the resource; defined by the server. * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * [Output Only] Unique identifier for the resource; defined by the server. * @param id id or {@code null} for none */ public NodeTemplateAggregatedList setId(java.lang.String id) { this.id = id; return this; } /** * A list of NodeTemplatesScopedList resources. * @return value or {@code null} for none */ public java.util.Map<String, NodeTemplatesScopedList> getItems() { return items; } /** * A list of NodeTemplatesScopedList resources. * @param items items or {@code null} for none */ public NodeTemplateAggregatedList setItems(java.util.Map<String, NodeTemplatesScopedList> items) { this.items = items; return this; } /** * [Output Only] Type of resource.Always compute#nodeTemplateAggregatedList for aggregated lists * of node templates. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of resource.Always compute#nodeTemplateAggregatedList for aggregated lists * of node templates. * @param kind kind or {@code null} for none */ public NodeTemplateAggregatedList setKind(java.lang.String kind) { this.kind = kind; return this; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. * @return value or {@code null} for none */ public java.lang.String getNextPageToken() { return nextPageToken; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. * @param nextPageToken nextPageToken or {@code null} for none */ public NodeTemplateAggregatedList setNextPageToken(java.lang.String nextPageToken) { this.nextPageToken = nextPageToken; return this; } /** * [Output Only] Server-defined URL for this resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for this resource. * @param selfLink selfLink or {@code null} for none */ public NodeTemplateAggregatedList setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] Informational warning message. * @return value or {@code null} for none */ public Warning getWarning() { return warning; } /** * [Output Only] Informational warning message. * @param warning warning or {@code null} for none */ public NodeTemplateAggregatedList setWarning(Warning warning) { this.warning = warning; return this; } @Override public NodeTemplateAggregatedList set(String fieldName, Object value) { return (NodeTemplateAggregatedList) super.set(fieldName, value); } @Override public NodeTemplateAggregatedList clone() { return (NodeTemplateAggregatedList) super.clone(); } /** * [Output Only] Informational warning message. */ public static final class Warning extends com.google.api.client.json.GenericJson { /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Data> data; static { // hack to force ProGuard to consider Data used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Data.class); } /** * [Output Only] A human-readable description of the warning code. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @param code code or {@code null} for none */ public Warning setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @return value or {@code null} for none */ public java.util.List<Data> getData() { return data; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @param data data or {@code null} for none */ public Warning setData(java.util.List<Data> data) { this.data = data; return this; } /** * [Output Only] A human-readable description of the warning code. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] A human-readable description of the warning code. * @param message message or {@code null} for none */ public Warning setMessage(java.lang.String message) { this.message = message; return this; } @Override public Warning set(String fieldName, Object value) { return (Warning) super.set(fieldName, value); } @Override public Warning clone() { return (Warning) super.clone(); } /** * Model definition for NodeTemplateAggregatedListWarningData. */ public static final class Data extends com.google.api.client.json.GenericJson { /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String key; /** * [Output Only] A warning data value corresponding to the key. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String value; /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @return value or {@code null} for none */ public java.lang.String getKey() { return key; } /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @param key key or {@code null} for none */ public Data setKey(java.lang.String key) { this.key = key; return this; } /** * [Output Only] A warning data value corresponding to the key. * @return value or {@code null} for none */ public java.lang.String getValue() { return value; } /** * [Output Only] A warning data value corresponding to the key. * @param value value or {@code null} for none */ public Data setValue(java.lang.String value) { this.value = value; return this; } @Override public Data set(String fieldName, Object value) { return (Data) super.set(fieldName, value); } @Override public Data clone() { return (Data) super.clone(); } } } }
package cgeo.geocaching.filters.gui; import cgeo.geocaching.R; import cgeo.geocaching.filters.core.LogsCountGeocacheFilter; import cgeo.geocaching.log.LogType; import cgeo.geocaching.ui.ContinuousRangeSlider; import cgeo.geocaching.ui.TextSpinner; import cgeo.geocaching.ui.ViewUtils; import static cgeo.geocaching.log.LogType.UNKNOWN; import static cgeo.geocaching.ui.ViewUtils.dpToPixel; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.Arrays; import org.apache.commons.lang3.tuple.ImmutablePair; public class LogsCountFilterViewHolder extends BaseFilterViewHolder<LogsCountGeocacheFilter> { private ContinuousRangeSlider slider; private final TextSpinner<LogType> selectSpinner = new TextSpinner<>(); @Override public View createView() { final LinearLayout ll = new LinearLayout(getActivity()); ll.setOrientation(LinearLayout.VERTICAL); final TextView spinnerView = ViewUtils.createTextSpinnerView(getActivity(), ll); selectSpinner.setTextView(spinnerView); selectSpinner .setDisplayMapper(v -> v == UNKNOWN ? getActivity().getString(R.string.all_types_short) : v.getL10n()) .setValues(Arrays.asList(LogType.FOUND_IT, LogType.DIDNT_FIND_IT, UNKNOWN)) .set(LogType.FOUND_IT); LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); llp.setMargins(0, dpToPixel(5), 0, dpToPixel(5)); ll.addView(spinnerView, llp); slider = new ContinuousRangeSlider(getActivity()); resetSliderScale(); llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); llp.setMargins(0, dpToPixel(5), 0, dpToPixel(5)); ll.addView(slider, llp); return ll; } private void resetSliderScale() { slider.setScale(-0.2f, 1000.2f, f -> { if (f <= 0) { return "0"; } if (f > 1000) { return ">1000"; } return "" + Math.round(f); }, 6); slider.setRange(-0.2f, 1000.2f); } @Override public void setViewFromFilter(final LogsCountGeocacheFilter filter) { selectSpinner.set(filter.getLogType() == null ? UNKNOWN : filter.getLogType()); slider.setRange(filter.getMinRangeValue() == null ? -10f : filter.getMinRangeValue(), filter.getMaxRangeValue() == null ? 1500f : filter.getMaxRangeValue()); } @Override public LogsCountGeocacheFilter createFilterFromView() { final LogsCountGeocacheFilter filter = createFilter(); final ImmutablePair<Float, Float> range = slider.getRange(); filter.setMinMaxRange( range.left < 0 ? null : Math.round(range.left), range.right > 1000 ? null : Math.round(range.right)); filter.setLogType(selectSpinner.get() == UNKNOWN ? null : selectSpinner.get()); return filter; } }
package mil.nga.dice.report.tests; import android.net.Uri; import android.webkit.MimeTypeMap; import junit.framework.TestCase; /** * Created by stjohnr on 3/27/15. */ public class MimeTypeTest extends TestCase { public void testGetFileExtension() { String url = "file:///spaces in url/more spaces.html?ner1=1&ner2=2#fragment"; String ext = MimeTypeMap.getFileExtensionFromUrl(Uri.encode(Uri.parse(url).getEncodedPath())); assertEquals("html", ext); } }
/* * Copyright 2019 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * 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.ukp.clarin.webanno.agreement.measures.krippendorffalphaunitizing; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Feature; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.fit.util.FSUtil; import org.dkpro.statistics.agreement.IAgreementMeasure; import org.dkpro.statistics.agreement.unitizing.KrippendorffAlphaUnitizingAgreement; import org.dkpro.statistics.agreement.unitizing.UnitizingAnnotationStudy; import de.tudarmstadt.ukp.clarin.webanno.agreement.PairwiseAnnotationResult; import de.tudarmstadt.ukp.clarin.webanno.agreement.measures.AggreementMeasure_ImplBase; import de.tudarmstadt.ukp.clarin.webanno.agreement.results.unitizing.UnitizingAgreementResult; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature; public class KrippendorffAlphaUnitizingAgreementMeasure extends AggreementMeasure_ImplBase<// PairwiseAnnotationResult<UnitizingAgreementResult>, // KrippendorffAlphaUnitizingAgreementTraits> { private final AnnotationSchemaService annotationService; public KrippendorffAlphaUnitizingAgreementMeasure(AnnotationFeature aFeature, KrippendorffAlphaUnitizingAgreementTraits aTraits, AnnotationSchemaService aAnnotationService) { super(aFeature, aTraits); annotationService = aAnnotationService; } @Override public PairwiseAnnotationResult<UnitizingAgreementResult> getAgreement( Map<String, List<CAS>> aCasMap) { PairwiseAnnotationResult<UnitizingAgreementResult> result = new PairwiseAnnotationResult<>( getFeature(), getTraits()); List<Entry<String, List<CAS>>> entryList = new ArrayList<>(aCasMap.entrySet()); for (int m = 0; m < entryList.size(); m++) { for (int n = 0; n < entryList.size(); n++) { // Triangle matrix mirrored if (n < m) { Map<String, List<CAS>> pairwiseCasMap = new LinkedHashMap<>(); pairwiseCasMap.put(entryList.get(m).getKey(), entryList.get(m).getValue()); pairwiseCasMap.put(entryList.get(n).getKey(), entryList.get(n).getValue()); UnitizingAgreementResult res = calculatePairAgreement(pairwiseCasMap); result.add(entryList.get(m).getKey(), entryList.get(n).getKey(), res); } } } return result; } public UnitizingAgreementResult calculatePairAgreement(Map<String, List<CAS>> aCasMap) { String typeName = getFeature().getLayer().getName(); // Calculate a character offset continuum over all CASses. We assume here that the documents // all have the same size - since the users cannot change the document sizes, this should be // an universally true assumption. List<CAS> firstUserCasses = aCasMap.values().stream().findFirst().get(); int docCount = firstUserCasses.size(); int[] docSizes = new int[docCount]; Arrays.fill(docSizes, 0); for (Entry<String, List<CAS>> set : aCasMap.entrySet()) { int i = 0; for (CAS cas : set.getValue()) { if (cas != null) { assert docSizes[i] == 0 || docSizes[i] == cas.getDocumentText().length(); docSizes[i] = cas.getDocumentText().length(); } i++; } } int continuumSize = Arrays.stream(docSizes).sum(); // Create a unitizing study for that continuum. UnitizingAnnotationStudy study = new UnitizingAnnotationStudy(continuumSize); // For each annotator, extract the feature values from all the annotator's CASses and add // them to the unitizing study based on character offsets. for (Entry<String, List<CAS>> set : aCasMap.entrySet()) { int raterIdx = study.addRater(set.getKey()); nextCas: for (CAS cas : set.getValue()) { if (cas == null) { // If a user has never worked on a source document, its CAS is null here - we // skip it. continue nextCas; } Type t = cas.getTypeSystem().getType(typeName); Feature f = t.getFeatureByBaseName(getFeature().getName()); cas.select(t).map(fs -> (AnnotationFS) fs).forEach(fs -> { study.addUnit(fs.getBegin(), fs.getEnd() - fs.getBegin(), raterIdx, FSUtil.getFeature(fs, f, Object.class)); }); } } UnitizingAgreementResult result = new UnitizingAgreementResult(typeName, getFeature().getName(), study, new ArrayList<>(aCasMap.keySet()), getTraits().isExcludeIncomplete()); IAgreementMeasure agreement = new KrippendorffAlphaUnitizingAgreement(study); if (result.getStudy().getUnitCount() > 0) { result.setAgreement(agreement.calculateAgreement()); } else { result.setAgreement(Double.NaN); } return result; } }
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.jaxrsclient.v2_0; import static io.opentelemetry.javaagent.tooling.ClassLoaderMatcher.hasClassesNamed; import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.extendsClass; import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.hasInterface; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.returns; import com.google.auto.service.AutoService; import io.opentelemetry.javaagent.tooling.InstrumentationModule; import io.opentelemetry.javaagent.tooling.TypeInstrumentation; import java.util.List; import java.util.Map; import javax.ws.rs.client.Client; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.matcher.ElementMatcher; @AutoService(InstrumentationModule.class) public class JaxRsClientInstrumentationModule extends InstrumentationModule { public JaxRsClientInstrumentationModule() { super("jaxrs-client", "jaxrs-client-2.0"); } @Override public List<TypeInstrumentation> typeInstrumentations() { return singletonList(new ClientBuilderInstrumentation()); } public static class ClientBuilderInstrumentation implements TypeInstrumentation { @Override public ElementMatcher<ClassLoader> classLoaderOptimization() { return hasClassesNamed("javax.ws.rs.client.ClientBuilder"); } @Override public ElementMatcher<TypeDescription> typeMatcher() { return extendsClass(named("javax.ws.rs.client.ClientBuilder")); } @Override public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() { return singletonMap( named("build").and(returns(hasInterface(named("javax.ws.rs.client.Client")))), JaxRsClientInstrumentationModule.class.getName() + "$ClientBuilderAdvice"); } } public static class ClientBuilderAdvice { @Advice.OnMethodExit public static void registerFeature( @Advice.Return(typing = Assigner.Typing.DYNAMIC) Client client) { // Register on the generated client instead of the builder // The build() can be called multiple times and is not thread safe // A client is only created once client.register(ClientTracingFeature.class); } } }
package com.u8.server.web.pay.sdk; import com.u8.server.common.UActionSupport; import com.u8.server.constants.PayState; import com.u8.server.data.UChannel; import com.u8.server.data.UOrder; import com.u8.server.log.Log; import com.u8.server.service.UChannelManager; import com.u8.server.service.UOrderManager; import com.u8.server.utils.EncryptUtils; import com.u8.server.utils.StringUtils; import com.u8.server.web.pay.SendAgent; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; /** * 虫虫SDK支付回调 * Created by lizhong on 2017/11/16. */ @Controller @Namespace("/pay/chongchong") public class ChongChongPayCallbackAction extends UActionSupport{ private String transactionNo; //虫虫支付订单号 private String partnerTransactionNo; //商户订单号 private String statusCode; //订单状态 private String productId; //支付商品的Id private String orderPrice; //订单金额 private String packageId; //游戏ID private String productName; //支付商品的名称 private String extParam; //扩展字段 private String userId; //用户ID private String sign; //回调签名,开发者在接收到虫虫游戏回调请求时,先进行验签,再进行自己的业务处理。 @Autowired private UOrderManager orderManager; @Autowired private UChannelManager channelManager; @Action("payCallback") public void payCallback(){ long orderID = Long.parseLong(this.partnerTransactionNo); UOrder order = orderManager.getOrder(orderID); if(order == null){ Log.d("The order is null or the channel is null.orderID:%s", orderID); this.renderState(false); return; } UChannel channel = channelManager.queryChannel(order.getChannelID()); if(channel == null){ Log.d("The channel is not exists of channelID:"+order.getChannelID()); this.renderState(false); return; } if(order.getState() > PayState.STATE_PAYING) { Log.d("The state of the order is complete. orderID:%s;state:%s" , orderID, order.getState()); this.renderState(true); return; } if(!isSignOK(channel)){ Log.d("the sign is not valid. sign:%s;orderID:%s", sign, transactionNo); this.renderState(false); return; } if("0000".equals(statusCode)) { int money = (int) (100 * Float.valueOf(orderPrice));//分为单位 order.setRealMoney(money); order.setSdkOrderTime(""); order.setCompleteTime(new Date()); order.setChannelOrderID(transactionNo); order.setState(PayState.STATE_SUC); orderManager.saveOrder(order); this.renderState(true); SendAgent.sendCallbackToServer(this.orderManager, order); }else if ("0002".equals(statusCode)){ order.setChannelOrderID(transactionNo); order.setState(PayState.STATE_FAILED); orderManager.saveOrder(order); this.renderState(false); } } private boolean isSignOK(UChannel channel){ StringBuilder sb = new StringBuilder(); if(!StringUtils.isEmpty(extParam)){ sb.append("extParam=").append(extParam).append("&"); } if(!StringUtils.isEmpty(orderPrice)){ sb.append("orderPrice=").append(orderPrice).append("&"); } if(!StringUtils.isEmpty(packageId)){ sb.append("packageId=").append(packageId).append("&"); } if(!StringUtils.isEmpty(partnerTransactionNo)){ sb.append("partnerTransactionNo=").append(partnerTransactionNo).append("&"); } if(!StringUtils.isEmpty(productId)){ sb.append("productId=").append(productId).append("&"); } if(!StringUtils.isEmpty(productName)){ sb.append("productName=").append(productName).append("&"); } if(!StringUtils.isEmpty(statusCode)){ sb.append("statusCode=").append(statusCode).append("&"); } if(!StringUtils.isEmpty(transactionNo)){ sb.append("transactionNo=").append(transactionNo).append("&"); } if(!StringUtils.isEmpty(userId)){ sb.append("userId=").append(userId).append("&"); } sb.append(channel.getCpAppSecret()); String md5Local = EncryptUtils.md5(sb.toString()).toLowerCase(); Log.d("cczs check sign orig str:"); Log.d(sb.toString()); return md5Local.equals(this.sign); } private void renderState(boolean suc){ PrintWriter out = null; try { String res = "success"; if(!suc){ res = "fail"; } out = this.response.getWriter(); out.write(res); } catch (IOException e) { e.printStackTrace(); }finally { out.flush(); out.close(); } } public String getTransactionNo() { return transactionNo; } public void setTransactionNo(String transactionNo) { this.transactionNo = transactionNo; } public String getPartnerTransactionNo() { return partnerTransactionNo; } public void setPartnerTransactionNo(String partnerTransactionNo) { this.partnerTransactionNo = partnerTransactionNo; } public String getStatusCode() { return statusCode; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getOrderPrice() { return orderPrice; } public void setOrderPrice(String orderPrice) { this.orderPrice = orderPrice; } public String getPackageId() { return packageId; } public void setPackageId(String packageId) { this.packageId = packageId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getExtParam() { return extParam; } public void setExtParam(String extParam) { this.extParam = extParam; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
/* * 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.i18n; import java.util.Locale; import java.util.TimeZone; import org.springframework.core.NamedInheritableThreadLocal; import org.springframework.core.NamedThreadLocal; import org.springframework.lang.Nullable; /** * Simple holder class that associates a LocaleContext instance * with the current thread. The LocaleContext will be inherited * by any child threads spawned by the current thread if the * {@code inheritable} flag is set to {@code true}. * * <p>Used as a central holder for the current Locale in Spring, * wherever necessary: for example, in MessageSourceAccessor. * DispatcherServlet automatically exposes its current Locale here. * Other applications can expose theirs too, to make classes like * MessageSourceAccessor automatically use that Locale. * * @author Juergen Hoeller * @author Nicholas Williams * @see LocaleContext * @see org.springframework.context.support.MessageSourceAccessor * @see org.springframework.web.servlet.DispatcherServlet * @since 1.2 */ public final class LocaleContextHolder { private static final ThreadLocal<LocaleContext> localeContextHolder = new NamedThreadLocal<>("LocaleContext"); private static final ThreadLocal<LocaleContext> inheritableLocaleContextHolder = new NamedInheritableThreadLocal<>("LocaleContext"); // Shared default locale at the framework level @Nullable private static Locale defaultLocale; // Shared default time zone at the framework level @Nullable private static TimeZone defaultTimeZone; private LocaleContextHolder() { } /** * Reset the LocaleContext for the current thread. */ public static void resetLocaleContext() { localeContextHolder.remove(); inheritableLocaleContextHolder.remove(); } /** * Associate the given LocaleContext with the current thread. * <p>The given LocaleContext may be a {@link TimeZoneAwareLocaleContext}, * containing a locale with associated time zone information. * * @param localeContext the current LocaleContext, * or {@code null} to reset the thread-bound context * @param inheritable whether to expose the LocaleContext as inheritable * for child threads (using an {@link InheritableThreadLocal}) * @see SimpleLocaleContext * @see SimpleTimeZoneAwareLocaleContext */ public static void setLocaleContext(@Nullable LocaleContext localeContext, boolean inheritable) { if (localeContext == null) { resetLocaleContext(); } else { if (inheritable) { inheritableLocaleContextHolder.set(localeContext); localeContextHolder.remove(); } else { localeContextHolder.set(localeContext); inheritableLocaleContextHolder.remove(); } } } /** * Return the LocaleContext associated with the current thread, if any. * * @return the current LocaleContext, or {@code null} if none */ @Nullable public static LocaleContext getLocaleContext() { LocaleContext localeContext = localeContextHolder.get(); if (localeContext == null) { localeContext = inheritableLocaleContextHolder.get(); } return localeContext; } /** * Associate the given LocaleContext with the current thread, * <i>not</i> exposing it as inheritable for child threads. * <p>The given LocaleContext may be a {@link TimeZoneAwareLocaleContext}, * containing a locale with associated time zone information. * * @param localeContext the current LocaleContext, * or {@code null} to reset the thread-bound context * @see SimpleLocaleContext * @see SimpleTimeZoneAwareLocaleContext */ public static void setLocaleContext(@Nullable LocaleContext localeContext) { setLocaleContext(localeContext, false); } /** * Associate the given Locale with the current thread, * preserving any TimeZone that may have been set already. * <p>Will implicitly create a LocaleContext for the given Locale. * * @param locale the current Locale, or {@code null} to reset * the locale part of thread-bound context * @param inheritable whether to expose the LocaleContext as inheritable * for child threads (using an {@link InheritableThreadLocal}) * @see #setTimeZone(TimeZone, boolean) * @see SimpleLocaleContext#SimpleLocaleContext(Locale) */ public static void setLocale(@Nullable Locale locale, boolean inheritable) { LocaleContext localeContext = getLocaleContext(); TimeZone timeZone = (localeContext instanceof TimeZoneAwareLocaleContext ? ((TimeZoneAwareLocaleContext) localeContext).getTimeZone() : null); if (timeZone != null) { localeContext = new SimpleTimeZoneAwareLocaleContext(locale, timeZone); } else if (locale != null) { localeContext = new SimpleLocaleContext(locale); } else { localeContext = null; } setLocaleContext(localeContext, inheritable); } /** * Set a shared default locale at the framework level, * as an alternative to the JVM-wide default locale. * <p><b>NOTE:</b> This can be useful to set an application-level * default locale which differs from the JVM-wide default locale. * However, this requires each such application to operate against * locally deployed Spring Framework jars. Do not deploy Spring * as a shared library at the server level in such a scenario! * * @param locale the default locale (or {@code null} for none, * letting lookups fall back to {@link Locale#getDefault()}) * @see #getLocale() * @see Locale#getDefault() * @since 4.3.5 */ public static void setDefaultLocale(@Nullable Locale locale) { LocaleContextHolder.defaultLocale = locale; } /** * Return the Locale associated with the current thread, if any, * or the system default Locale otherwise. This is effectively a * replacement for {@link java.util.Locale#getDefault()}, * able to optionally respect a user-level Locale setting. * <p>Note: This method has a fallback to the shared default Locale, * either at the framework level or at the JVM-wide system level. * If you'd like to check for the raw LocaleContext content * (which may indicate no specific locale through {@code null}, use * {@link #getLocaleContext()} and call {@link LocaleContext#getLocale()} * * @return the current Locale, or the system default Locale if no * specific Locale has been associated with the current thread * @see #getLocaleContext() * @see LocaleContext#getLocale() * @see #setDefaultLocale(Locale) * @see java.util.Locale#getDefault() */ public static Locale getLocale() { return getLocale(getLocaleContext()); } /** * Associate the given Locale with the current thread, * preserving any TimeZone that may have been set already. * <p>Will implicitly create a LocaleContext for the given Locale, * <i>not</i> exposing it as inheritable for child threads. * * @param locale the current Locale, or {@code null} to reset * the locale part of thread-bound context * @see #setTimeZone(TimeZone) * @see SimpleLocaleContext#SimpleLocaleContext(Locale) */ public static void setLocale(@Nullable Locale locale) { setLocale(locale, false); } /** * Return the Locale associated with the given user context, if any, * or the system default Locale otherwise. This is effectively a * replacement for {@link java.util.Locale#getDefault()}, * able to optionally respect a user-level Locale setting. * * @param localeContext the user-level locale context to check * @return the current Locale, or the system default Locale if no * specific Locale has been associated with the current thread * @see #getLocale() * @see LocaleContext#getLocale() * @see #setDefaultLocale(Locale) * @see java.util.Locale#getDefault() * @since 5.0 */ public static Locale getLocale(@Nullable LocaleContext localeContext) { if (localeContext != null) { Locale locale = localeContext.getLocale(); if (locale != null) { return locale; } } return (defaultLocale != null ? defaultLocale : Locale.getDefault()); } /** * Associate the given TimeZone with the current thread, * preserving any Locale that may have been set already. * <p>Will implicitly create a LocaleContext for the given Locale. * * @param timeZone the current TimeZone, or {@code null} to reset * the time zone part of the thread-bound context * @param inheritable whether to expose the LocaleContext as inheritable * for child threads (using an {@link InheritableThreadLocal}) * @see #setLocale(Locale, boolean) * @see SimpleTimeZoneAwareLocaleContext#SimpleTimeZoneAwareLocaleContext(Locale, TimeZone) */ public static void setTimeZone(@Nullable TimeZone timeZone, boolean inheritable) { LocaleContext localeContext = getLocaleContext(); Locale locale = (localeContext != null ? localeContext.getLocale() : null); if (timeZone != null) { localeContext = new SimpleTimeZoneAwareLocaleContext(locale, timeZone); } else if (locale != null) { localeContext = new SimpleLocaleContext(locale); } else { localeContext = null; } setLocaleContext(localeContext, inheritable); } /** * Set a shared default time zone at the framework level, * as an alternative to the JVM-wide default time zone. * <p><b>NOTE:</b> This can be useful to set an application-level * default time zone which differs from the JVM-wide default time zone. * However, this requires each such application to operate against * locally deployed Spring Framework jars. Do not deploy Spring * as a shared library at the server level in such a scenario! * * @param timeZone the default time zone (or {@code null} for none, * letting lookups fall back to {@link TimeZone#getDefault()}) * @see #getTimeZone() * @see TimeZone#getDefault() * @since 4.3.5 */ public static void setDefaultTimeZone(@Nullable TimeZone timeZone) { defaultTimeZone = timeZone; } /** * Return the TimeZone associated with the current thread, if any, * or the system default TimeZone otherwise. This is effectively a * replacement for {@link java.util.TimeZone#getDefault()}, * able to optionally respect a user-level TimeZone setting. * <p>Note: This method has a fallback to the shared default TimeZone, * either at the framework level or at the JVM-wide system level. * If you'd like to check for the raw LocaleContext content * (which may indicate no specific time zone through {@code null}, use * {@link #getLocaleContext()} and call {@link TimeZoneAwareLocaleContext#getTimeZone()} * after downcasting to {@link TimeZoneAwareLocaleContext}. * * @return the current TimeZone, or the system default TimeZone if no * specific TimeZone has been associated with the current thread * @see #getLocaleContext() * @see TimeZoneAwareLocaleContext#getTimeZone() * @see #setDefaultTimeZone(TimeZone) * @see java.util.TimeZone#getDefault() */ public static TimeZone getTimeZone() { return getTimeZone(getLocaleContext()); } /** * Associate the given TimeZone with the current thread, * preserving any Locale that may have been set already. * <p>Will implicitly create a LocaleContext for the given Locale, * <i>not</i> exposing it as inheritable for child threads. * * @param timeZone the current TimeZone, or {@code null} to reset * the time zone part of the thread-bound context * @see #setLocale(Locale) * @see SimpleTimeZoneAwareLocaleContext#SimpleTimeZoneAwareLocaleContext(Locale, TimeZone) */ public static void setTimeZone(@Nullable TimeZone timeZone) { setTimeZone(timeZone, false); } /** * Return the TimeZone associated with the given user context, if any, * or the system default TimeZone otherwise. This is effectively a * replacement for {@link java.util.TimeZone#getDefault()}, * able to optionally respect a user-level TimeZone setting. * * @param localeContext the user-level locale context to check * @return the current TimeZone, or the system default TimeZone if no * specific TimeZone has been associated with the current thread * @see #getTimeZone() * @see TimeZoneAwareLocaleContext#getTimeZone() * @see #setDefaultTimeZone(TimeZone) * @see java.util.TimeZone#getDefault() * @since 5.0 */ public static TimeZone getTimeZone(@Nullable LocaleContext localeContext) { if (localeContext instanceof TimeZoneAwareLocaleContext) { TimeZone timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); if (timeZone != null) { return timeZone; } } return (defaultTimeZone != null ? defaultTimeZone : TimeZone.getDefault()); } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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. */ /* * Created by IntelliJ IDEA. * User: mike * Date: Aug 22, 2002 * Time: 2:55:23 PM * To change template for new class use * Code Style | Class Templates options (Tools | IDE Options). */ package com.intellij.codeInsight.intention.impl; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.CodeInsightServicesUtil; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction; import consulo.logging.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.controlFlow.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.IncorrectOperationException; import javax.annotation.Nonnull; import java.util.List; public class InvertIfConditionAction extends PsiElementBaseIntentionAction { private static final Logger LOG = Logger.getInstance(InvertIfConditionAction.class); @Override public boolean isAvailable(@Nonnull Project project, Editor editor, @Nonnull PsiElement element) { int offset = editor.getCaretModel().getOffset(); final PsiIfStatement ifStatement = PsiTreeUtil.getParentOfType(element, PsiIfStatement.class); if (ifStatement == null) return false; final PsiExpression condition = ifStatement.getCondition(); if (condition == null) return false; if (ifStatement.getThenBranch() == null) return false; if (element instanceof PsiKeyword) { PsiKeyword keyword = (PsiKeyword) element; if ((keyword.getTokenType() == JavaTokenType.IF_KEYWORD || keyword.getTokenType() == JavaTokenType.ELSE_KEYWORD) && keyword.getParent() == ifStatement) { return true; } } final TextRange condTextRange = condition.getTextRange(); if (condTextRange == null) return false; if (!condTextRange.contains(offset)) return false; PsiElement block = findCodeBlock(ifStatement); return block != null; } @Override @Nonnull public String getText() { return getFamilyName(); } @Override @Nonnull public String getFamilyName() { return CodeInsightBundle.message("intention.invert.if.condition"); } @Override public void invoke(@Nonnull Project project, Editor editor, @Nonnull PsiElement element) throws IncorrectOperationException { if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return; PsiIfStatement ifStatement = PsiTreeUtil.getParentOfType(element, PsiIfStatement.class); LOG.assertTrue(ifStatement != null); PsiElement block = findCodeBlock(ifStatement); ControlFlow controlFlow = buildControlFlow(block); PsiExpression condition = (PsiExpression) ifStatement.getCondition().copy(); setupBranches(ifStatement, controlFlow); if (condition != null) { ifStatement.getCondition().replace(CodeInsightServicesUtil.invertCondition(condition)); } formatIf(ifStatement); } private static void formatIf(PsiIfStatement ifStatement) throws IncorrectOperationException { final Project project = ifStatement.getProject(); PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); PsiElement thenBranch = ifStatement.getThenBranch().copy(); PsiElement elseBranch = ifStatement.getElseBranch() != null ? ifStatement.getElseBranch().copy() : null; PsiElement condition = ifStatement.getCondition().copy(); final CodeStyleManager codeStyle = CodeStyleManager.getInstance(project); PsiBlockStatement codeBlock = (PsiBlockStatement)factory.createStatementFromText("{}", null); codeBlock = (PsiBlockStatement)codeStyle.reformat(codeBlock); ifStatement.getThenBranch().replace(codeBlock); if (elseBranch != null) { ifStatement.getElseBranch().replace(codeBlock); } ifStatement.getCondition().replace(factory.createExpressionFromText("true", null)); ifStatement = (PsiIfStatement)codeStyle.reformat(ifStatement); if (!(thenBranch instanceof PsiBlockStatement)) { PsiBlockStatement codeBlock1 = (PsiBlockStatement)ifStatement.getThenBranch().replace(codeBlock); codeBlock1 = (PsiBlockStatement)codeStyle.reformat(codeBlock1); codeBlock1.getCodeBlock().add(thenBranch); } else { ifStatement.getThenBranch().replace(thenBranch); } if (elseBranch != null) { if (!(elseBranch instanceof PsiBlockStatement)) { PsiBlockStatement codeBlock1 = (PsiBlockStatement)ifStatement.getElseBranch().replace(codeBlock); codeBlock1 = (PsiBlockStatement)codeStyle.reformat(codeBlock1); codeBlock1.getCodeBlock().add(elseBranch); } else { elseBranch = ifStatement.getElseBranch().replace(elseBranch); if (emptyBlock(((PsiBlockStatement)elseBranch).getCodeBlock())) { ifStatement.getElseBranch().delete(); } } } ifStatement.getCondition().replace(condition); } private static boolean emptyBlock (PsiCodeBlock block) { PsiElement[] children = block.getChildren(); for (PsiElement child : children) { if (child instanceof PsiComment) return false; if (!(child instanceof PsiWhiteSpace) && !(child instanceof PsiJavaToken)) return false; } return true; } private static PsiElement findCodeBlock(PsiIfStatement ifStatement) { PsiElement e = PsiTreeUtil.getParentOfType(ifStatement, PsiMethod.class, PsiClassInitializer.class); if (e instanceof PsiMethod) return ((PsiMethod) e).getBody(); if (e instanceof PsiClassInitializer) return ((PsiClassInitializer) e).getBody(); return null; } private static PsiElement findNearestCodeBlock(PsiIfStatement ifStatement) { return PsiTreeUtil.getParentOfType(ifStatement, PsiCodeBlock.class); } private static ControlFlow buildControlFlow(PsiElement element) { try { //return new ControlFlowAnalyzer(element, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(), false, false).buildControlFlow(); return ControlFlowFactory.getInstance(element.getProject()).getControlFlow(element, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(), false); } catch (AnalysisCanceledException e) { return ControlFlow.EMPTY; } } private static void setupBranches(PsiIfStatement ifStatement, ControlFlow flow) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(ifStatement.getProject()).getElementFactory(); Project project = ifStatement.getProject(); PsiStatement thenBranch = ifStatement.getThenBranch(); PsiStatement elseBranch = ifStatement.getElseBranch(); if (elseBranch != null) { elseBranch = (PsiStatement) elseBranch.copy(); setElseBranch(ifStatement, thenBranch, flow); ifStatement.getThenBranch().replace(elseBranch); return; } final CodeStyleManager codeStyle = CodeStyleManager.getInstance(project); if (flow.getSize() == 0) { ifStatement.setElseBranch(thenBranch); PsiStatement statement = factory.createStatementFromText("{}", null); statement = (PsiStatement) codeStyle.reformat(statement); statement = (PsiStatement) ifStatement.getThenBranch().replace(statement); codeStyle.reformat(statement); return; } int endOffset = calcEndOffset(flow, ifStatement); LOG.assertTrue(endOffset >= 0); if (endOffset >= flow.getSize()) { PsiStatement statement = factory.createStatementFromText("return;", null); statement = (PsiStatement) codeStyle.reformat(statement); if (thenBranch instanceof PsiBlockStatement) { PsiStatement[] statements = ((PsiBlockStatement) thenBranch).getCodeBlock().getStatements(); int len = statements.length; if (len > 0) { //if (statements[len - 1] instanceof PsiReturnStatement) len--; if (len > 0) { PsiElement firstElement = statements [0]; while (firstElement.getPrevSibling() instanceof PsiWhiteSpace || firstElement.getPrevSibling() instanceof PsiComment) { firstElement = firstElement.getPrevSibling(); } ifStatement.getParent().addRangeAfter(firstElement, statements[len - 1], ifStatement); } } } else { if (!(thenBranch instanceof PsiReturnStatement)) { addAfter(ifStatement, thenBranch); } } ifStatement.getThenBranch().replace(statement); return; } PsiElement element = flow.getElement(endOffset); while (element != null && !(element instanceof PsiStatement)) element = element.getParent(); if (element != null && element.getParent() instanceof PsiForStatement) { PsiForStatement forStatement = (PsiForStatement) element.getParent(); if (forStatement.getUpdate() == element) { PsiStatement statement = factory.createStatementFromText("continue;", null); statement = (PsiStatement) codeStyle.reformat(statement); addAfter(ifStatement, thenBranch); ifStatement.getThenBranch().replace(statement); return; } } if (element instanceof PsiWhileStatement && flow.getStartOffset(element) == endOffset || element instanceof PsiForeachStatement && flow.getStartOffset(element) + 1 == endOffset // Foreach doesn't loop on it's first instruction // but rather on second. It only accesses collection initially. ) { PsiStatement statement = factory.createStatementFromText("continue;", null); statement = (PsiStatement) codeStyle.reformat(statement); addAfter(ifStatement, thenBranch); ifStatement.getThenBranch().replace(statement); return; } if (element instanceof PsiReturnStatement) { PsiReturnStatement returnStatement = (PsiReturnStatement) element; addAfter(ifStatement, thenBranch); ifStatement.getThenBranch().replace(returnStatement.copy()); ControlFlow flow2 = buildControlFlow(findCodeBlock(ifStatement)); if (!ControlFlowUtil.isInstructionReachable(flow2, flow2.getStartOffset(returnStatement), 0)) returnStatement.delete(); return; } boolean nextUnreachable = flow.getEndOffset(ifStatement) == flow.getSize(); if (!nextUnreachable) { PsiElement nearestCodeBlock = findNearestCodeBlock(ifStatement); if (nearestCodeBlock != null) { ControlFlow flow2 = buildControlFlow(nearestCodeBlock); nextUnreachable = !ControlFlowUtil.isInstructionReachable(flow2, flow2.getEndOffset(ifStatement), getThenOffset(flow2, ifStatement)); } } if (nextUnreachable) { setElseBranch(ifStatement, thenBranch, flow); PsiElement first = ifStatement.getNextSibling(); // while (first instanceof PsiWhiteSpace) first = first.getNextSibling(); if (first != null) { PsiElement last = first; PsiElement next = last.getNextSibling(); while (next != null && !(next instanceof PsiSwitchLabelStatement)) { last = next; next = next.getNextSibling(); } while (first != last && (last instanceof PsiWhiteSpace || last instanceof PsiJavaToken && ((PsiJavaToken) last).getTokenType() == JavaTokenType.RBRACE)) last = last.getPrevSibling(); PsiBlockStatement codeBlock = (PsiBlockStatement) factory.createStatementFromText("{}", null); codeBlock.getCodeBlock().addRange(first, last); first.getParent().deleteChildRange(first, last); ifStatement.getThenBranch().replace(codeBlock); } codeStyle.reformat(ifStatement); return; } setElseBranch(ifStatement, thenBranch, flow); PsiStatement statement = factory.createStatementFromText("{}", null); statement = (PsiStatement) codeStyle.reformat(statement); statement = (PsiStatement) ifStatement.getThenBranch().replace(statement); codeStyle.reformat(statement); } private static void setElseBranch(PsiIfStatement ifStatement, PsiStatement thenBranch, ControlFlow flow) throws IncorrectOperationException { if (flow.getEndOffset(ifStatement) == flow.getEndOffset(thenBranch)) { final PsiLoopStatement loopStmt = PsiTreeUtil.getParentOfType(ifStatement, PsiLoopStatement.class); if (loopStmt != null) { final PsiStatement body = loopStmt.getBody(); if (body instanceof PsiBlockStatement) { final PsiStatement[] statements = ((PsiBlockStatement)body).getCodeBlock().getStatements(); if (statements.length > 0 && !PsiTreeUtil.isAncestor(statements[statements.length - 1], ifStatement, false) && ArrayUtilRt.find(statements, ifStatement) < 0) { ifStatement.setElseBranch(thenBranch); return; } } } if (thenBranch instanceof PsiContinueStatement) { PsiStatement elseBranch = ifStatement.getElseBranch(); if (elseBranch != null) { elseBranch.delete(); } return; } else if (thenBranch instanceof PsiBlockStatement) { PsiStatement[] statements = ((PsiBlockStatement) thenBranch).getCodeBlock().getStatements(); if (statements.length > 0 && statements[statements.length - 1] instanceof PsiContinueStatement) { statements[statements.length - 1].delete(); } } } ifStatement.setElseBranch(thenBranch); } private static void addAfter(PsiIfStatement ifStatement, PsiStatement thenBranch) throws IncorrectOperationException { if (thenBranch instanceof PsiBlockStatement) { PsiBlockStatement blockStatement = (PsiBlockStatement) thenBranch; PsiStatement[] statements = blockStatement.getCodeBlock().getStatements(); if (statements.length > 0) { ifStatement.getParent().addRangeAfter(statements[0], statements[statements.length - 1], ifStatement); } } else { ifStatement.getParent().addAfter(thenBranch, ifStatement); } } private static int getThenOffset(ControlFlow controlFlow, PsiIfStatement ifStatement) { PsiStatement thenBranch = ifStatement.getThenBranch(); for (int i = 0; i < controlFlow.getSize(); i++) { if (PsiTreeUtil.isAncestor(thenBranch, controlFlow.getElement(i), false)) return i; } return -1; } private static int calcEndOffset(ControlFlow controlFlow, PsiIfStatement ifStatement) { int endOffset = -1; List<Instruction> instructions = controlFlow.getInstructions(); for (int i = 0; i < instructions.size(); i++) { Instruction instruction = instructions.get(i); if (controlFlow.getElement(i) != ifStatement) continue; if (instruction instanceof GoToInstruction) { GoToInstruction goToInstruction = (GoToInstruction)instruction; if (goToInstruction.role != BranchingInstruction.Role.END) continue; endOffset = goToInstruction.offset; break; } else if (instruction instanceof ConditionalGoToInstruction) { ConditionalGoToInstruction goToInstruction = (ConditionalGoToInstruction)instruction; if (goToInstruction.role != BranchingInstruction.Role.END) continue; endOffset = goToInstruction.offset; break; } } if (endOffset == -1) { endOffset = controlFlow.getSize(); } while (endOffset < instructions.size() && instructions.get(endOffset) instanceof GoToInstruction && !((GoToInstruction) instructions.get(endOffset)).isReturn) { endOffset = ((BranchingInstruction)instructions.get(endOffset)).offset; } return endOffset; } }
package org.jenkinsci.plugins.gitclient; import static org.junit.Assert.*; import hudson.EnvVars; import hudson.Launcher; import hudson.model.TaskListener; import hudson.util.ArgumentListBuilder; import hudson.util.StreamTaskListener; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; /** * Run a command line git command, return output as array of String, optionally * assert on contents of command output. * * @author Mark Waite */ class CliGitCommand { private final TaskListener listener; private final transient Launcher launcher; private final EnvVars env; private final File dir; private String[] output; private ArgumentListBuilder args; CliGitCommand(GitClient client, String... arguments) { args = new ArgumentListBuilder("git"); args.add(arguments); listener = StreamTaskListener.NULL; launcher = new Launcher.LocalLauncher(listener); env = new EnvVars(); if (client != null) { dir = client.getRepository().getWorkTree(); } else { dir = new File("."); } } String[] run(String... arguments) throws IOException, InterruptedException { args = new ArgumentListBuilder("git"); args.add(arguments); return run(true); } String[] run() throws IOException, InterruptedException { return run(true); } private String[] run(boolean assertProcessStatus) throws IOException, InterruptedException { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteArrayOutputStream bytesErr = new ByteArrayOutputStream(); Launcher.ProcStarter p = launcher.launch().cmds(args).envs(env).stdout(bytesOut).stderr(bytesErr).pwd(dir); int status = p.start().joinWithTimeout(1, TimeUnit.MINUTES, listener); String result = bytesOut.toString("UTF-8"); if (bytesErr.size() > 0) { result = result + "\nstderr not empty:\n" + bytesErr.toString("UTF-8"); } output = result.split("[\\n\\r]"); if (assertProcessStatus) { assertEquals(args.toString() + " command failed and reported '" + Arrays.toString(output) + "'", 0, status); } return output; } void assertOutputContains(String... expectedRegExes) { List<String> notFound = new ArrayList<>(); boolean modified = notFound.addAll(Arrays.asList(expectedRegExes)); assertTrue("Missing regular expressions in assertion", modified); for (String line : output) { notFound.removeIf(line::matches); } if (!notFound.isEmpty()) { fail(Arrays.toString(output) + " did not match all strings in notFound: " + Arrays.toString(expectedRegExes)); } } String[] runWithoutAssert(String... arguments) throws IOException, InterruptedException { args = new ArgumentListBuilder("git"); args.add(arguments); return run(false); } }
/* * Copyright (c) 2007, Swedish Institute of Computer Science. * 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. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS 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 INSTITUTE OR 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. * */ package org.contikios.cooja.mspmote; import java.awt.Container; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.io.File; import java.net.URL; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import org.apache.log4j.Logger; import org.contikios.cooja.AbstractionLevelDescription; import org.contikios.cooja.ClassDescription; import org.contikios.cooja.Cooja; import org.contikios.cooja.MoteInterface; import org.contikios.cooja.MoteType; import org.contikios.cooja.Simulation; import org.contikios.cooja.dialogs.CompileContiki; import org.contikios.cooja.dialogs.MessageList; import org.contikios.cooja.dialogs.MessageList.MessageContainer; import org.contikios.cooja.interfaces.IPAddress; import org.contikios.cooja.interfaces.Mote2MoteRelations; import org.contikios.cooja.interfaces.MoteAttributes; import org.contikios.cooja.interfaces.Position; import org.contikios.cooja.interfaces.RimeAddress; import org.contikios.cooja.mspmote.interfaces.Msp802154Radio; import org.contikios.cooja.mspmote.interfaces.MspClock; import org.contikios.cooja.mspmote.interfaces.MspDebugOutput; import org.contikios.cooja.mspmote.interfaces.MspMoteID; import org.contikios.cooja.mspmote.interfaces.MspSerial; import org.contikios.cooja.mspmote.interfaces.SkyButton; import org.contikios.cooja.mspmote.interfaces.SkyCoffeeFilesystem; import org.contikios.cooja.mspmote.interfaces.SkyFlash; import org.contikios.cooja.mspmote.interfaces.SkyLED; import org.contikios.cooja.mspmote.interfaces.SkyTemperature; @ClassDescription("Sky mote") @AbstractionLevelDescription("Emulated level") public class SkyMoteType extends MspMoteType { private static Logger logger = Logger.getLogger(SkyMoteType.class); protected MspMote createMote(Simulation simulation) { return new SkyMote(this, simulation); } public boolean configureAndInit(Container parentContainer, Simulation simulation, boolean visAvailable) throws MoteTypeCreationException { /* SPECIAL CASE: Cooja started in applet. * Use preconfigured Contiki firmware */ if (Cooja.isVisualizedInApplet()) { String firmware = Cooja.getExternalToolsSetting("SKY_FIRMWARE", ""); if (!firmware.equals("")) { setContikiFirmwareFile(new File(firmware)); JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), "Creating mote type from precompiled firmware: " + firmware, "Compiled firmware file available", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), "No precompiled firmware found", "Compiled firmware file not available", JOptionPane.ERROR_MESSAGE); return false; } } /* If visualized, show compile dialog and let user configure */ if (visAvailable) { /* Create unique identifier */ if (getIdentifier() == null) { int counter = 0; boolean identifierOK = false; while (!identifierOK) { identifierOK = true; counter++; setIdentifier("sky" + counter); for (MoteType existingMoteType : simulation.getMoteTypes()) { if (existingMoteType == this) { continue; } if (existingMoteType.getIdentifier().equals(getIdentifier())) { identifierOK = false; break; } } } } /* Create initial description */ if (getDescription() == null) { setDescription("Sky Mote Type #" + getIdentifier()); } return MspCompileDialog.showDialog(parentContainer, simulation, this, "sky"); } /* Not visualized: Compile Contiki immediately */ if (getIdentifier() == null) { throw new MoteTypeCreationException("No identifier"); } final MessageList compilationOutput = new MessageList(); if (getCompileCommands() != null) { /* Handle multiple compilation commands one by one */ String[] arr = getCompileCommands().split("\n"); for (String cmd: arr) { if (cmd.trim().isEmpty()) { continue; } try { CompileContiki.compile( cmd, null, null /* Do not observe output firmware file */, getContikiSourceFile().getParentFile(), null, null, compilationOutput, true ); } catch (Exception e) { MoteTypeCreationException newException = new MoteTypeCreationException("Mote type creation failed: " + e.getMessage()); newException = (MoteTypeCreationException) newException.initCause(e); newException.setCompilationOutput(compilationOutput); /* Print last 10 compilation errors to console */ MessageContainer[] messages = compilationOutput.getMessages(); for (int i=messages.length-10; i < messages.length; i++) { if (i < 0) { continue; } logger.fatal(">> " + messages[i]); } logger.fatal("Compilation error: " + e.getMessage()); throw newException; } } } if (getContikiFirmwareFile() == null || !getContikiFirmwareFile().exists()) { throw new MoteTypeCreationException("Contiki firmware file does not exist: " + getContikiFirmwareFile()); } return true; } public Icon getMoteTypeIcon() { Toolkit toolkit = Toolkit.getDefaultToolkit(); URL imageURL = this.getClass().getClassLoader().getResource("images/sky.jpg"); Image image = toolkit.getImage(imageURL); MediaTracker tracker = new MediaTracker(Cooja.getTopParentContainer()); tracker.addImage(image, 1); try { tracker.waitForAll(); } catch (InterruptedException ex) { } if (image.getHeight(Cooja.getTopParentContainer()) > 0 && image.getWidth(Cooja.getTopParentContainer()) > 0) { image = image.getScaledInstance((200*image.getWidth(Cooja.getTopParentContainer())/image.getHeight(Cooja.getTopParentContainer())), 200, Image.SCALE_DEFAULT); return new ImageIcon(image); } return null; } public Class<? extends MoteInterface>[] getDefaultMoteInterfaceClasses() { return getAllMoteInterfaceClasses(); } public Class<? extends MoteInterface>[] getAllMoteInterfaceClasses() { return new Class[] { Position.class, RimeAddress.class, IPAddress.class, Mote2MoteRelations.class, MoteAttributes.class, MspClock.class, MspMoteID.class, SkyButton.class, SkyFlash.class, SkyCoffeeFilesystem.class, Msp802154Radio.class, MspSerial.class, SkyLED.class, MspDebugOutput.class, /* EXPERIMENTAL: Enable me for COOJA_DEBUG(..) */ SkyTemperature.class }; } public File getExpectedFirmwareFile(File source) { File parentDir = source.getParentFile(); String sourceNoExtension = source.getName().substring(0, source.getName().length()-2); return new File(parentDir, sourceNoExtension + ".sky"); } protected String getTargetName() { return "sky"; } }
package net.nullspace_mc.tapestry.mixin.core; import net.nullspace_mc.tapestry.Tapestry; import net.minecraft.server.MinecraftServer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(MinecraftServer.class) public abstract class MinecraftServerMixin { @Inject( method = "start", at = @At("HEAD") ) public void onStart(CallbackInfo ci) { Tapestry.onStart(); } @Inject( method = "tick", at = @At("HEAD") ) public void onTick(CallbackInfo ci) { Tapestry.onTick(); } }
package tb.common.block; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import DummyCore.Client.Icon; import DummyCore.Client.IconRegister; import DummyCore.Client.RenderAccessLibrary; import DummyCore.Utils.BlockStateMetadata; import DummyCore.Utils.IOldCubicBlock; import DummyCore.Utils.MathUtils; import DummyCore.Utils.MetadataBasedMethodsHelper; import net.minecraft.block.Block; import net.minecraft.block.BlockDirt; import net.minecraft.block.BlockGrass; import net.minecraft.block.BlockGravel; import net.minecraft.block.BlockNetherrack; import net.minecraft.block.BlockObsidian; import net.minecraft.block.BlockSand; import net.minecraft.block.BlockSoulSand; import net.minecraft.block.BlockStone; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry; import net.minecraftforge.common.IShearable; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.oredict.OreDictionary; import tb.core.TBCore; import tb.init.TBBlocks; public class BlockTBLeaves extends Block implements IOldCubicBlock, IShearable{ public static final String[] names = new String[]{ "goldenOakLeaves", "peacefullTreeLeaves", "netherTreeLeaves", "enderTreeLeaves" }; public static final String[] textures = new String[]{ "goldenOak/leaves", "peacefullTree/leaves", "netherTree/leaves", "enderTree/leaves" }; public static Icon[] icons = new Icon[names.length]; public BlockTBLeaves() { super(Material.leaves); this.setLightOpacity(1); this.setTickRandomly(true); this.setHardness(0.2F); this.setStepSound(soundTypeGrass); } public boolean canEntityDestroy(IBlockAccess world, BlockPos pos, Entity entity) { if(BlockStateMetadata.getBlockMetadata(world, pos)%8==3) if(entity instanceof EntityDragon) return false; return super.canEntityDestroy(world, pos, entity); } public boolean isFlammable(IBlockAccess world, BlockPos pos, EnumFacing face) { if(BlockStateMetadata.getBlockMetadata(world, pos)%8==2) return true; return super.isFlammable(world, pos, face); } public int getFlammability(IBlockAccess world, BlockPos pos, EnumFacing face) { if(BlockStateMetadata.getBlockMetadata(world, pos)%8==2) return 0; return super.getFlammability(world, pos, face); } public int getFireSpreadSpeed(IBlockAccess world, BlockPos pos, EnumFacing face) { if(BlockStateMetadata.getBlockMetadata(world, pos)%8==2) return 0; return super.getFlammability(world, pos, face); } public boolean isFireSource(World world, BlockPos pos, EnumFacing side) { if(BlockStateMetadata.getBlockMetadata(world, pos)%8==2) return true; return super.isFireSource(world, pos, side); } public boolean isFullCube() { return false; } public boolean isOpaqueCube() { return false; } public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.CUTOUT_MIPPED; } @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { return true; } @Override public Icon getIcon(int side, int meta) { return icons[Math.min(icons.length-1, meta % 8)]; } @SuppressWarnings({ "unchecked", "rawtypes" }) public void getSubBlocks(Item i, CreativeTabs p_149666_2_, List p_149666_3_) { for(int f = 0; f < names.length; ++f) p_149666_3_.add(new ItemStack(i,1,f)); } @Override public Icon getIcon(IBlockAccess world, int x, int y, int z, int side) { return getIcon(side,BlockStateMetadata.getBlockMetadata(world, x, y, z)); } public int damageDropped(IBlockState state) { return BlockStateMetadata.getMetaFromState(state) % 8; } public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(BlockStateMetadata.METADATA, meta); } public int getMetaFromState(IBlockState state) { return BlockStateMetadata.getMetaFromState(state); } protected BlockState createBlockState() { return new BlockState(this,BlockStateMetadata.METADATA); } @Override public List<IBlockState> listPossibleStates(Block b) { ArrayList<IBlockState> retLst = new ArrayList<IBlockState>(); for(int i = 0; i < names.length; ++i) { retLst.add(getStateFromMeta(i)); retLst.add(getStateFromMeta(i+8)); } return retLst; } @Override public void registerBlockIcons(IconRegister ir) { for(int i = 0; i < icons.length; ++i) icons[i] = ir.registerBlockIcon(TBCore.modid+":"+textures[i]); } @Override public int getDCRenderID() { return RenderAccessLibrary.RENDER_ID_CUBE_AND_CROSS; } public void dropApple(World worldIn, BlockPos pos, IBlockState state, int chance) { if (BlockStateMetadata.getMetaFromState(state) == 0 && worldIn.rand.nextInt(chance) == 0) spawnAsEntity(worldIn, pos, new ItemStack(Items.golden_apple, 1, 0)); } public int getSaplingDropChance(IBlockState state) { return BlockStateMetadata.getMetaFromState(state) == 0 ? 50 : 30; } public ItemStack createStackedBlock(IBlockState state) { return new ItemStack(state.getBlock(),1,BlockStateMetadata.getMetaFromState(state)%8); } public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te) { if (!worldIn.isRemote && player.getCurrentEquippedItem() != null && player.getCurrentEquippedItem().getItem() == Items.shears) player.triggerAchievement(StatList.mineBlockStatArray[Block.getIdFromBlock(this)]); else super.harvestBlock(worldIn, player, pos, state, te); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public List<ItemStack> onSheared(ItemStack item, IBlockAccess world, BlockPos pos, int fortune) { return new ArrayList(Arrays.asList(new ItemStack(this, 1, BlockStateMetadata.getBlockMetadata(world, pos) % 8))); } @Override public boolean isShearable(ItemStack item, IBlockAccess world, BlockPos pos) { return true; } @Override public boolean isLeaves(IBlockAccess world, BlockPos pos) { return true; } @Override public void beginLeavesDecay(World world, BlockPos pos) { int meta = BlockStateMetadata.getBlockMetadata(world, pos) % 8; world.setBlockState(pos, getStateFromMeta(meta + 8)); } public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { MetadataBasedMethodsHelper.breakLeaves(worldIn, pos, state); } @SideOnly(Side.CLIENT) public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { if (worldIn.canLightningStrike(pos.up()) && !World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) && rand.nextInt(15) == 1) { double d0 = pos.getX() + rand.nextFloat(); double d1 = pos.getY() - 0.05D; double d2 = pos.getZ() + rand.nextFloat(); worldIn.spawnParticle(EnumParticleTypes.DRIP_WATER, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); } World w = worldIn; int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); Random rnd = rand; if(BlockStateMetadata.getBlockMetadata(worldIn, pos)%8 == 0) w.spawnParticle(EnumParticleTypes.REDSTONE, x+rnd.nextDouble(), y+rnd.nextDouble(), z+rnd.nextDouble(), 1, 1, 0); if(BlockStateMetadata.getBlockMetadata(worldIn, pos)%8 == 1 && rnd.nextFloat() <= 0.01F) w.spawnParticle(EnumParticleTypes.HEART, x+rnd.nextDouble(), y+rnd.nextDouble(), z+rnd.nextDouble(), 0, 10, 0); if(BlockStateMetadata.getBlockMetadata(worldIn, pos)%8 == 2) { if(w.isAirBlock(new BlockPos(x, y-1, z))) w.spawnParticle(EnumParticleTypes.DRIP_LAVA, x+rnd.nextDouble(), y, z+rnd.nextDouble(), 0, 0, 0); } if(BlockStateMetadata.getBlockMetadata(worldIn, pos)%8 == 3) w.spawnParticle(EnumParticleTypes.PORTAL, x+rnd.nextDouble(), y+rnd.nextDouble(), z+rnd.nextDouble(), MathUtils.randomDouble(rnd), MathUtils.randomDouble(rnd), MathUtils.randomDouble(rnd)); } public void spawnAction(World w, Random rnd, BlockPos pos) { int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); if(BlockStateMetadata.getBlockMetadata(w,pos)%8 == 1) { if(rnd.nextDouble() > 0.03D) return; int dy = y; BiomeGenBase base = w.getBiomeGenForCoords(new BlockPos(x,0, z)); if(base != null) { List<SpawnListEntry> l = base.getSpawnableList(EnumCreatureType.CREATURE); if(l != null && !l.isEmpty()) { SpawnListEntry entry = l.get(rnd.nextInt(l.size())); if(entry != null && entry.entityClass != null) { Class<?> c = entry.entityClass; if(EntityLiving.class.isAssignableFrom(c)) { try { EntityLiving el = EntityLiving.class.cast(c.getConstructor(World.class).newInstance(w)); while(--y >= dy-6) { el.setPositionAndRotation(x+0.5D, y, z+0.5D, 0, 0); if(el.getCanSpawnHere()) { w.spawnEntityInWorld(el); break; } continue; } }catch(Exception e) { FMLLog.warning("[TB]Tried to create an entity of class "+c+" but failed! The exception is listed below:",new Object[0]); e.printStackTrace(); } } } } } } if(BlockStateMetadata.getBlockMetadata(w,pos)%8 == 2) { int dy = y; while(--y >= dy-8) { Block b = w.getBlockState(new BlockPos(x,y,z)).getBlock(); if(!b.isAir(w, new BlockPos(x, y, z))) { boolean netheric = b instanceof BlockNetherrack || b instanceof BlockSoulSand || b == Blocks.quartz_ore; if(netheric && rnd.nextDouble() <= 0.05D) { BiomeGenBase hellBiome = BiomeGenBase.hell; List<SpawnListEntry> l = rnd.nextBoolean() ? hellBiome.getSpawnableList(EnumCreatureType.CREATURE) : hellBiome.getSpawnableList(EnumCreatureType.MONSTER); if(l != null && !l.isEmpty()) { SpawnListEntry entry = l.get(rnd.nextInt(l.size())); if(entry != null && entry.entityClass != null) { Class<?> c = entry.entityClass; if(EntityLiving.class.isAssignableFrom(c)) { try { EntityLiving el = EntityLiving.class.cast(c.getConstructor(World.class).newInstance(w)); el.setPositionAndRotation(x+0.5D, y+1, z+0.5D, 0, 0); el.onInitialSpawn(w.getDifficultyForLocation(new BlockPos(el)), null); if(el.getCanSpawnHere()) { w.spawnEntityInWorld(el); break; } }catch(Exception e) { FMLLog.warning("[TB]Tried to create an entity of class "+c+" but failed! The exception is listed below:",new Object[0]); e.printStackTrace(); } } } } break; } boolean flag = b instanceof BlockDirt || b instanceof BlockGrass || b instanceof BlockGravel || b instanceof BlockSand || b instanceof BlockStone; if(!flag) { ItemStack stk = new ItemStack(b,1,BlockStateMetadata.getBlockMetadata(w,pos)); if(stk!=null&&stk.getItem()!=null) if(OreDictionary.getOreIDs(stk) != null && OreDictionary.getOreIDs(stk).length > 0) { OreDict:for(int i = 0; i < OreDictionary.getOreIDs(stk).length; ++i) { int id = OreDictionary.getOreIDs(stk)[i]; if(id != -1) { String ore = OreDictionary.getOreName(id); if(ore != null && ! ore.isEmpty()) { flag = ore.contains("dirt") || ore.contains("grass") || ore.contains("sand") || ore.contains("gravel") || ore.contains("stone"); if(flag) break OreDict; } } } } } if(flag) { double random = rnd.nextDouble(); Block setTo = random <= 0.6D ? Blocks.netherrack : random <= 0.9D ? Blocks.soul_sand : Blocks.quartz_ore; w.setBlockState(new BlockPos(x, y, z), setTo.getDefaultState()); break; } } } } if(BlockStateMetadata.getBlockMetadata(w,pos)%8 == 3) { int dy = y; while(--y >= dy-11) { Block b = w.getBlockState(new BlockPos(x, y, z)).getBlock(); if(!b.isAir(w, new BlockPos(x, y, z))) { boolean end = b == Blocks.end_stone || b instanceof BlockObsidian; if(end && rnd.nextDouble() <= 0.02D) { BiomeGenBase hellBiome = BiomeGenBase.sky; List<SpawnListEntry> l = rnd.nextBoolean() ? hellBiome.getSpawnableList(EnumCreatureType.CREATURE) : hellBiome.getSpawnableList(EnumCreatureType.MONSTER); if(l != null && !l.isEmpty()) { SpawnListEntry entry = l.get(rnd.nextInt(l.size())); if(entry != null && entry.entityClass != null) { Class<?> c = entry.entityClass; if(EntityLiving.class.isAssignableFrom(c)) { try { EntityLiving el = EntityLiving.class.cast(c.getConstructor(World.class).newInstance(w)); el.setPositionAndRotation(x+0.5D, y+1, z+0.5D, 0, 0); el.onInitialSpawn(w.getDifficultyForLocation(new BlockPos(el)), null); if(w.isAirBlock(new BlockPos(x, y+1, z))) { w.spawnEntityInWorld(el); break; } }catch(Exception e) { FMLLog.warning("[TB]Tried to create an entity of class "+c+" but failed! The exception is listed below:",new Object[0]); e.printStackTrace(); } } } } break; } boolean flag = b instanceof BlockDirt || b instanceof BlockGrass || b instanceof BlockGravel || b instanceof BlockSand || b instanceof BlockStone && !(b instanceof BlockObsidian) && !(b == Blocks.end_stone); if(!flag) { ItemStack stk = new ItemStack(b,1,BlockStateMetadata.getBlockMetadata(w,pos)); if(stk!=null&&stk.getItem()!=null) if(OreDictionary.getOreIDs(stk) != null && OreDictionary.getOreIDs(stk).length > 0) { OreDict:for(int i = 0; i < OreDictionary.getOreIDs(stk).length; ++i) { int id = OreDictionary.getOreIDs(stk)[i]; if(id != -1) { String ore = OreDictionary.getOreName(id); if(ore != null && ! ore.isEmpty()) { flag = ore.contains("dirt") || ore.contains("grass") || ore.contains("sand") || ore.contains("gravel") || ore.contains("stone"); if(flag) break OreDict; } } } } } if(flag) { double random = rnd.nextDouble(); Block setTo = random <= 0.9D ? Blocks.end_stone : Blocks.obsidian; w.setBlockState(new BlockPos(x, y, z), setTo.getDefaultState()); break; } } } } } public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { MetadataBasedMethodsHelper.leavesDecayTick(worldIn, pos, state, rand); spawnAction(worldIn, rand, pos); } public int quantityDropped(Random random) { return random.nextInt(20) == 0 ? 1 : 0; } public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); } public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Item.getItemFromBlock(TBBlocks.sapling); } @Override public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { List<ItemStack> ret = new ArrayList<ItemStack>(); Random rand = world instanceof World ? ((World)world).rand : new Random(); int chance = this.getSaplingDropChance(state); if (fortune > 0) { chance -= 2 << fortune; if (chance < 10) chance = 10; } if (rand.nextInt(chance) == 0) ret.add(new ItemStack(getItemDropped(state, rand, fortune), 1, damageDropped(state))); chance = 200; if (fortune > 0) { chance -= 10 << fortune; if (chance < 40) chance = 40; } this.captureDrops(true); if (world instanceof World) this.dropApple((World)world, pos, state, chance); // Dammet mojang ret.addAll(this.captureDrops(false)); return ret; } }
/* * 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.iotdb.db.qp.logical.crud; import org.apache.iotdb.db.exception.metadata.MetadataException; import org.apache.iotdb.db.exception.query.LogicalOperatorException; import org.apache.iotdb.db.metadata.path.PartialPath; import org.apache.iotdb.db.qp.constant.FilterConstant.FilterType; import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType; import org.apache.iotdb.tsfile.read.common.Path; import org.apache.iotdb.tsfile.read.expression.IUnaryExpression; import org.apache.iotdb.tsfile.read.expression.impl.GlobalTimeExpression; import org.apache.iotdb.tsfile.read.expression.impl.SingleSeriesExpression; import org.apache.iotdb.tsfile.read.filter.TimeFilter; import org.apache.iotdb.tsfile.read.filter.ValueFilter; import org.apache.iotdb.tsfile.read.filter.basic.Filter; import org.apache.iotdb.tsfile.utils.Binary; import org.apache.iotdb.tsfile.utils.Pair; import org.apache.iotdb.tsfile.utils.StringContainer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** operator 'in' 'not in' */ public class InOperator extends FunctionOperator { private boolean not; protected Set<String> values; /** * In Operator Constructor. * * @param filterType filter Type * @param path path * @param values values */ public InOperator(FilterType filterType, PartialPath path, boolean not, Set<String> values) { super(filterType); this.singlePath = path; this.values = values; this.not = not; isLeaf = true; isSingle = true; } public Set<String> getValues() { return values; } public boolean getNot() { return not; } @Override public void reverseFunc() { not = !not; } @Override @SuppressWarnings("squid:S3776") // Suppress high Cognitive Complexity warning protected Pair<IUnaryExpression, String> transformToSingleQueryFilter( Map<PartialPath, TSDataType> pathTSDataTypeHashMap) throws LogicalOperatorException, MetadataException { TSDataType type = pathTSDataTypeHashMap.get(singlePath); if (type == null) { throw new MetadataException( "given seriesPath:{" + singlePath.getFullPath() + "} don't exist in metadata"); } IUnaryExpression ret; switch (type) { case INT32: Set<Integer> integerValues = new HashSet<>(); for (String val : values) { integerValues.add(Integer.valueOf(val)); } ret = In.getUnaryExpression(singlePath, integerValues, not); break; case INT64: Set<Long> longValues = new HashSet<>(); for (String val : values) { longValues.add(Long.valueOf(val)); } ret = In.getUnaryExpression(singlePath, longValues, not); break; case BOOLEAN: Set<Boolean> booleanValues = new HashSet<>(); for (String val : values) { booleanValues.add(Boolean.valueOf(val)); } ret = In.getUnaryExpression(singlePath, booleanValues, not); break; case FLOAT: Set<Float> floatValues = new HashSet<>(); for (String val : values) { floatValues.add(Float.parseFloat(val)); } ret = In.getUnaryExpression(singlePath, floatValues, not); break; case DOUBLE: Set<Double> doubleValues = new HashSet<>(); for (String val : values) { doubleValues.add(Double.parseDouble(val)); } ret = In.getUnaryExpression(singlePath, doubleValues, not); break; case TEXT: Set<Binary> binaryValues = new HashSet<>(); for (String val : values) { binaryValues.add( (val.startsWith("'") && val.endsWith("'")) || (val.startsWith("\"") && val.endsWith("\"")) ? new Binary(val.substring(1, val.length() - 1)) : new Binary(val)); } ret = In.getUnaryExpression(singlePath, binaryValues, not); break; default: throw new LogicalOperatorException(type.toString(), ""); } return new Pair<>(ret, singlePath.getFullPath()); } @Override public String showTree(int spaceNum) { StringContainer sc = new StringContainer(); for (int i = 0; i < spaceNum; i++) { sc.addTail(" "); } sc.addTail(singlePath.getFullPath(), getFilterSymbol(), not, values, ", single\n"); return sc.toString(); } @Override public InOperator copy() { InOperator ret = new InOperator(this.filterType, singlePath.clone(), not, new HashSet<>(values)); ret.isLeaf = isLeaf; ret.isSingle = isSingle; ret.pathSet = pathSet; return ret; } @Override public String toString() { List<String> valuesList = new ArrayList<>(values); Collections.sort(valuesList); return "[" + singlePath.getFullPath() + getFilterSymbol() + not + valuesList + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InOperator that = (InOperator) o; return Objects.equals(singlePath, that.singlePath) && values.containsAll(that.values) && values.size() == that.values.size() && not == that.not; } @Override public int hashCode() { return Objects.hash(super.hashCode(), singlePath, not, values); } private static class In { public static <T extends Comparable<T>> IUnaryExpression getUnaryExpression( Path path, Set<T> values, boolean not) { if (path != null && path.toString().equals("time")) { return new GlobalTimeExpression(TimeFilter.in((Set<Long>) values, not)); } else { return new SingleSeriesExpression(path, ValueFilter.in(values, not)); } } public <T extends Comparable<T>> Filter getValueFilter(T value) { return ValueFilter.notEq(value); } } }
package mage.server.util; import mage.server.util.config.Config; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import java.io.File; public class ConfigFactory { public static Config loadFromFile(final String filePath) { try { final JAXBContext jaxbContext = JAXBContext.newInstance("mage.server.util.config"); final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return (Config) unmarshaller.unmarshal(new File(filePath)); } catch (Exception e) { throw new ConfigurationException(e); } } }
class s implements Runnable { public void run() { } } class Over extends s { public void run() { if (true) { super.run(); } } }
/* * 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 cn.escheduler.common.task.flink; import cn.escheduler.common.enums.ProgramType; import cn.escheduler.common.process.ResourceInfo; import cn.escheduler.common.task.AbstractParameters; import java.util.List; import java.util.stream.Collectors; /** * flink parameters */ public class FlinkParameters extends AbstractParameters { /** * major jar */ private ResourceInfo mainJar; /** * major class */ private String mainClass; /** * deploy mode yarn-cluster yarn-client yarn-local */ private String deployMode; /** * arguments */ private String mainArgs; /** * slot个数 */ private int slot; /** *Yarn application的名字 */ private String appName; /** * taskManager 数量 */ private int taskManager; /** * jobManagerMemory 内存大小 */ private String jobManagerMemory ; /** * taskManagerMemory内存大小 */ private String taskManagerMemory; /** * resource list */ private List<ResourceInfo> resourceList; /** * The YARN queue to submit to */ private String queue; /** * other arguments */ private String others; /** * program type * 0 JAVA,1 SCALA,2 PYTHON */ private ProgramType programType; public ResourceInfo getMainJar() { return mainJar; } public void setMainJar(ResourceInfo mainJar) { this.mainJar = mainJar; } public String getMainClass() { return mainClass; } public void setMainClass(String mainClass) { this.mainClass = mainClass; } public String getDeployMode() { return deployMode; } public void setDeployMode(String deployMode) { this.deployMode = deployMode; } public String getMainArgs() { return mainArgs; } public void setMainArgs(String mainArgs) { this.mainArgs = mainArgs; } public int getSlot() { return slot; } public void setSlot(int slot) { this.slot = slot; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public int getTaskManager() { return taskManager; } public void setTaskManager(int taskManager) { this.taskManager = taskManager; } public String getJobManagerMemory() { return jobManagerMemory; } public void setJobManagerMemory(String jobManagerMemory) { this.jobManagerMemory = jobManagerMemory; } public String getTaskManagerMemory() { return taskManagerMemory; } public void setTaskManagerMemory(String taskManagerMemory) { this.taskManagerMemory = taskManagerMemory; } public String getQueue() { return queue; } public void setQueue(String queue) { this.queue = queue; } public List<ResourceInfo> getResourceList() { return resourceList; } public void setResourceList(List<ResourceInfo> resourceList) { this.resourceList = resourceList; } public String getOthers() { return others; } public void setOthers(String others) { this.others = others; } public ProgramType getProgramType() { return programType; } public void setProgramType(ProgramType programType) { this.programType = programType; } @Override public boolean checkParameters() { return mainJar != null && programType != null; } @Override public List<String> getResourceFilesList() { if(resourceList !=null ) { this.resourceList.add(mainJar); return resourceList.stream() .map(p -> p.getRes()).collect(Collectors.toList()); } return null; } }
package org.cloudfoundry.identity.uaa.oauth; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.cloudfoundry.identity.uaa.approval.Approval; import org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus; import org.cloudfoundry.identity.uaa.approval.ApprovalService; import org.cloudfoundry.identity.uaa.audit.AuditEvent; import org.cloudfoundry.identity.uaa.audit.AuditEventType; import org.cloudfoundry.identity.uaa.audit.event.TokenIssuedEvent; import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.oauth.jwt.Jwt; import org.cloudfoundry.identity.uaa.oauth.jwt.JwtHelper; import org.cloudfoundry.identity.uaa.oauth.openid.IdToken; import org.cloudfoundry.identity.uaa.oauth.openid.IdTokenCreator; import org.cloudfoundry.identity.uaa.oauth.openid.IdTokenGranter; import org.cloudfoundry.identity.uaa.oauth.openid.UserAuthenticationData; import org.cloudfoundry.identity.uaa.oauth.refresh.CompositeExpiringOAuth2RefreshToken; import org.cloudfoundry.identity.uaa.oauth.refresh.RefreshTokenCreator; import org.cloudfoundry.identity.uaa.oauth.token.*; import org.cloudfoundry.identity.uaa.oauth.token.matchers.AbstractOAuth2AccessTokenMatchers; import org.cloudfoundry.identity.uaa.oauth.token.matchers.OAuth2RefreshTokenMatchers; import org.cloudfoundry.identity.uaa.user.UaaUser; import org.cloudfoundry.identity.uaa.user.UaaUserDatabase; import org.cloudfoundry.identity.uaa.user.UaaUserPrototype; import org.cloudfoundry.identity.uaa.user.UserInfo; import org.cloudfoundry.identity.uaa.util.JsonUtils; import org.cloudfoundry.identity.uaa.util.TimeService; import org.cloudfoundry.identity.uaa.util.TokenValidation; import org.cloudfoundry.identity.uaa.util.UaaTokenUtils; import org.cloudfoundry.identity.uaa.zone.*; import org.cloudfoundry.identity.uaa.zone.beans.IdentityZoneManagerImpl; import org.junit.*; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2RefreshToken; import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; import org.springframework.security.oauth2.common.exceptions.InvalidScopeException; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.AuthorizationRequest; import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.TokenRequest; import org.springframework.security.oauth2.provider.client.BaseClientDetails; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import java.util.*; import static java.util.Collections.*; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.*; import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.REQUIRED_USER_GROUPS; import static org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification.SECRET; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.*; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.TokenFormat.JWT; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.TokenFormat.OPAQUE; import static org.cloudfoundry.identity.uaa.oauth.token.matchers.OAuth2AccessTokenMatchers.*; import static org.cloudfoundry.identity.uaa.user.UaaAuthority.USER_AUTHORITIES; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo; import static org.hamcrest.text.IsEmptyString.isEmptyString; import static org.junit.Assert.*; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*; @RunWith(Parameterized.class) public class DeprecatedUaaTokenServicesTests { @Rule public ExpectedException expectedException = ExpectedException.none(); private TestTokenEnhancer tokenEnhancer; private CompositeToken persistToken; private Date expiration; private TokenTestSupport tokenSupport; private RevocableTokenProvisioning tokenProvisioning; private Calendar expiresAt = Calendar.getInstance(); private Calendar updatedAt = Calendar.getInstance(); private Set<String> acrValue = Sets.newHashSet("urn:oasis:names:tc:SAML:2.0:ac:classes:Password"); private UaaTokenServices tokenServices; private KeyInfoService keyInfoService; public DeprecatedUaaTokenServicesTests(TestTokenEnhancer enhancer, String testname) { this.tokenEnhancer = enhancer; } @Parameterized.Parameters(name = "{index}: testname[{1}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{{null, "old behavior"}, {new TestTokenEnhancer(), "using enhancer"}}); } @Before public void setUp() throws Exception { tokenSupport = new TokenTestSupport(tokenEnhancer); keyInfoService = new KeyInfoService("https://uaa.url"); Set<String> thousandScopes = new HashSet<>(); for (int i = 0; i < 1000; i++) { thousandScopes.add(String.valueOf(i)); } persistToken = new CompositeToken("token-value"); expiration = new Date(System.currentTimeMillis() + 10000); persistToken.setScope(thousandScopes); persistToken.setExpiration(expiration); tokenServices = tokenSupport.getUaaTokenServices(); tokenServices.setKeyInfoService(keyInfoService); tokenProvisioning = tokenSupport.getTokenProvisioning(); when(tokenSupport.timeService.getCurrentTimeMillis()).thenReturn(1000L); } @After public void teardown() { AbstractOAuth2AccessTokenMatchers.revocableTokens.remove(); IdentityZoneHolder.clear(); tokenSupport.clear(); } @Test public void test_opaque_tokens_are_persisted() { IdentityZoneHolder.get().getConfig().getTokenPolicy().setJwtRevocable(false); IdentityZoneHolder.get().getConfig().getTokenPolicy().setRefreshTokenFormat(JWT.getStringValue()); CompositeToken result = tokenServices.persistRevocableToken("id", persistToken, new CompositeExpiringOAuth2RefreshToken("refresh-token-value", expiration, "rid"), "clientId", "userId", true, true); ArgumentCaptor<RevocableToken> rt = ArgumentCaptor.forClass(RevocableToken.class); verify(tokenProvisioning, times(2)).create(rt.capture(), anyString()); assertNotNull(rt.getAllValues()); assertThat(rt.getAllValues().size(), equalTo(2)); assertNotNull(rt.getAllValues().get(0)); assertEquals(RevocableToken.TokenType.ACCESS_TOKEN, rt.getAllValues().get(0).getResponseType()); assertEquals(OPAQUE.getStringValue(), rt.getAllValues().get(0).getFormat()); assertEquals("id", result.getValue()); assertEquals(RevocableToken.TokenType.REFRESH_TOKEN, rt.getAllValues().get(1).getResponseType()); assertEquals(OPAQUE.getStringValue(), rt.getAllValues().get(1).getFormat()); assertEquals("rid", result.getRefreshToken().getValue()); } @Test public void test_refresh_tokens_are_uniquely_persisted() { IdentityZoneHolder.get().getConfig().getTokenPolicy().setRefreshTokenUnique(true); IdentityZoneHolder.get().getConfig().getTokenPolicy().setRefreshTokenFormat(OPAQUE.getStringValue()); tokenServices.persistRevocableToken("id", persistToken, new CompositeExpiringOAuth2RefreshToken("refresh-token-value", expiration, ""), "clientId", "userId", true, true); ArgumentCaptor<RevocableToken> rt = ArgumentCaptor.forClass(RevocableToken.class); verify(tokenProvisioning, times(1)).deleteRefreshTokensForClientAndUserId("clientId", "userId", IdentityZoneHolder.get().getId()); verify(tokenProvisioning, times(2)).create(rt.capture(), anyString()); RevocableToken refreshToken = rt.getAllValues().get(1); assertEquals(RevocableToken.TokenType.REFRESH_TOKEN, refreshToken.getResponseType()); } @Test public void test_refresh_token_not_unique_when_set_to_false() { IdentityZoneHolder.get().getConfig().getTokenPolicy().setRefreshTokenUnique(false); tokenServices.persistRevocableToken("id", persistToken, new CompositeExpiringOAuth2RefreshToken("refresh-token-value", expiration, ""), "clientId", "userId", true, true); ArgumentCaptor<RevocableToken> rt = ArgumentCaptor.forClass(RevocableToken.class); String currentZoneId = IdentityZoneHolder.get().getId(); verify(tokenProvisioning, times(0)).deleteRefreshTokensForClientAndUserId(anyString(), anyString(), eq(currentZoneId)); verify(tokenProvisioning, times(2)).create(rt.capture(), anyString()); RevocableToken refreshToken = rt.getAllValues().get(1); assertEquals(RevocableToken.TokenType.REFRESH_TOKEN, refreshToken.getResponseType()); } @Test public void refreshAccessToken_buildsIdToken_withRolesAndAttributesAndACR() throws Exception { IdTokenCreator idTokenCreator = mock(IdTokenCreator.class); when(idTokenCreator.create(any(), any(), any())).thenReturn(mock(IdToken.class)); BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setScope(Sets.newHashSet("openid")); MultitenantClientServices mockMultitenantClientServices = mock(MultitenantClientServices.class); when(mockMultitenantClientServices.loadClientByClientId(eq(TokenTestSupport.CLIENT_ID))) .thenReturn(clientDetails); TokenValidityResolver tokenValidityResolver = mock(TokenValidityResolver.class); when(tokenValidityResolver.resolve(TokenTestSupport.CLIENT_ID)).thenReturn(new Date()); TokenValidation tokenValidation = mock(TokenValidation.class); TokenValidationService tokenValidationService = mock(TokenValidationService.class); when(tokenValidationService.validateToken(anyString(), anyBoolean())).thenReturn(tokenValidation); HashMap<String, Object> claims = Maps.newHashMap(); String userId = "userid"; claims.put(ClaimConstants.USER_ID, userId); claims.put(ClaimConstants.CID, TokenTestSupport.CLIENT_ID); claims.put(ClaimConstants.EXP, 1); claims.put(ClaimConstants.GRANTED_SCOPES, Lists.newArrayList("read", "write", "openid")); claims.put(ClaimConstants.GRANT_TYPE, "password"); claims.put(ClaimConstants.AUD, Lists.newArrayList(TokenTestSupport.CLIENT_ID)); HashMap<Object, Object> acrMap = Maps.newHashMap(); acrMap.put(IdToken.ACR_VALUES_KEY, acrValue); claims.put(ClaimConstants.ACR, acrMap); when(tokenValidation.getClaims()).thenReturn(claims); when(tokenValidation.checkJti()).thenReturn(tokenValidation); Jwt jwt = mock(Jwt.class); when(tokenValidation.getJwt()).thenReturn(jwt); when(jwt.getEncoded()).thenReturn("encoded"); UaaUserDatabase userDatabase = mock(UaaUserDatabase.class); when(userDatabase.retrieveUserById(userId)) .thenReturn(new UaaUser(new UaaUserPrototype().withId(userId).withUsername("marissa").withEmail("marissa@example.com"))); ArgumentCaptor<UserAuthenticationData> userAuthenticationDataArgumentCaptor = ArgumentCaptor.forClass(UserAuthenticationData.class); TimeService timeService = mock(TimeService.class); when(timeService.getCurrentTimeMillis()).thenReturn(1000L); when(timeService.getCurrentDate()).thenCallRealMethod(); ApprovalService approvalService = mock(ApprovalService.class); UaaTokenServices uaaTokenServices = new UaaTokenServices( idTokenCreator, mock(TokenEndpointBuilder.class), mockMultitenantClientServices, mock(RevocableTokenProvisioning.class), tokenValidationService, mock(RefreshTokenCreator.class), timeService, tokenValidityResolver, userDatabase, Sets.newHashSet(), new TokenPolicy(), new KeyInfoService(DEFAULT_ISSUER), new IdTokenGranter(approvalService), approvalService ); UserInfo userInfo = new UserInfo(); userInfo.setRoles(Lists.newArrayList("custom_role")); MultiValueMap<String, String> userAttributes = new LinkedMultiValueMap<>(); userAttributes.put("multi_value", Arrays.asList("value1", "value2")); userAttributes.add("single_value", "value3"); userInfo.setUserAttributes(userAttributes); when(userDatabase.getUserInfo(userId)).thenReturn(userInfo); String refreshToken = getOAuth2AccessToken().getRefreshToken().getValue(); uaaTokenServices.refreshAccessToken(refreshToken, getRefreshTokenRequest()); verify(idTokenCreator).create(eq(TokenTestSupport.CLIENT_ID), eq(userId), userAuthenticationDataArgumentCaptor.capture()); UserAuthenticationData userData = userAuthenticationDataArgumentCaptor.getValue(); Set<String> expectedRoles = Sets.newHashSet("custom_role"); assertEquals(expectedRoles, userData.roles); assertEquals(userAttributes, userData.userAttributes); assertEquals(acrValue, userData.contextClassRef); } @Test public void test_jwt_no_token_is_not_persisted() { IdentityZoneHolder.get().getConfig().getTokenPolicy().setRefreshTokenFormat(JWT.getStringValue()); CompositeToken result = tokenServices.persistRevocableToken("id", persistToken, new CompositeExpiringOAuth2RefreshToken("refresh-token-value", expiration, ""), "clientId", "userId", false, false); ArgumentCaptor<RevocableToken> rt = ArgumentCaptor.forClass(RevocableToken.class); verify(tokenProvisioning, never()).create(rt.capture(), anyString()); assertEquals(persistToken.getValue(), result.getValue()); assertEquals("refresh-token-value", result.getRefreshToken().getValue()); } @Test public void test_opaque_refresh_token_is_persisted() { IdentityZoneHolder.get().getConfig().getTokenPolicy().setRefreshTokenFormat(OPAQUE.getStringValue()); CompositeToken result = tokenServices.persistRevocableToken("id", persistToken, new CompositeExpiringOAuth2RefreshToken("refresh-token-value", expiration, ""), "clientId", "userId", false, false); ArgumentCaptor<RevocableToken> rt = ArgumentCaptor.forClass(RevocableToken.class); verify(tokenProvisioning, times(1)).create(rt.capture(), anyString()); assertNotNull(rt.getAllValues()); assertEquals(1, rt.getAllValues().size()); assertEquals(RevocableToken.TokenType.REFRESH_TOKEN, rt.getAllValues().get(0).getResponseType()); assertEquals(OPAQUE.getStringValue(), rt.getAllValues().get(0).getFormat()); assertEquals("refresh-token-value", rt.getAllValues().get(0).getValue()); assertNotEquals("refresh-token-value", result.getRefreshToken().getValue()); } @Test public void isOpaqueTokenRequired() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, TokenConstants.GRANT_TYPE_USER_TOKEN); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); assertTrue(tokenServices.isOpaqueTokenRequired(authentication)); } @Test(expected = InvalidTokenException.class) public void testNullRefreshTokenString() { tokenServices.refreshAccessToken(null, null); } @Test public void testInvalidRefreshToken() { Map<String, String> map = new HashMap<>(); map.put("grant_type", "refresh_token"); AuthorizationRequest authorizationRequest = new AuthorizationRequest(map, null, null, null, null, null, false, null, null, null); String refreshTokenValue = "dasdasdasdasdas"; try { tokenServices.refreshAccessToken(refreshTokenValue, tokenSupport.requestFactory.createTokenRequest(authorizationRequest, "refresh_token")); fail("Expected Exception was not thrown"); } catch (InvalidTokenException e) { assertThat(e.getMessage(), not(containsString(refreshTokenValue))); } } @Test public void misconfigured_keys_throws_proper_error() { expectedException.expect(InternalAuthenticationServiceException.class); expectedException.expectMessage("Unable to sign token, misconfigured JWT signing keys"); IdentityZoneHolder.get().getConfig().getTokenPolicy().setActiveKeyId("invalid"); performPasswordGrant(JWT.getStringValue()); } @Test public void testCreateAccessTokenForAClient() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.clientScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertCommonClientAccessTokenProperties(accessToken); assertThat(accessToken, validFor(is(tokenSupport.accessTokenValidity))); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, zoneId(is(IdentityZoneHolder.get().getId()))); assertThat(accessToken.getRefreshToken(), is(nullValue())); validateExternalAttributes(accessToken); assertCommonEventProperties(accessToken, CLIENT_ID, tokenSupport.expectedJson); } @Test public void testCreateAccessTokenForAnotherIssuer() throws Exception { String subdomain = "test-zone-subdomain"; IdentityZone identityZone = getIdentityZone(subdomain); identityZone.setConfig( JsonUtils.readValue( "{\"issuer\": \"http://uaamaster:8080/uaa\"}", IdentityZoneConfiguration.class ) ); identityZone.getConfig().getTokenPolicy().setAccessTokenValidity(tokenSupport.accessTokenValidity); tokenSupport.copyClients(IdentityZoneHolder.get().getId(), identityZone.getId()); IdentityZoneHolder.set(identityZone); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.clientScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); tokenServices.setTokenEndpointBuilder(new TokenEndpointBuilder("http://uaaslave:8080/uaa")); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertCommonClientAccessTokenProperties(accessToken); assertThat(accessToken, validFor(is(tokenSupport.accessTokenValidity))); assertThat(accessToken, issuerUri(is("http://uaamaster:8080/uaa/oauth/token"))); assertThat(accessToken, zoneId(is(IdentityZoneHolder.get().getId()))); assertThat(accessToken.getRefreshToken(), is(nullValue())); validateExternalAttributes(accessToken); } @Test public void testCreateAccessTokenForInvalidIssuer() { String subdomain = "test-zone-subdomain"; IdentityZone identityZone = getIdentityZone(subdomain); try { identityZone.setConfig( JsonUtils.readValue( "{\"issuer\": \"notAnURL\"}", IdentityZoneConfiguration.class ) ); fail(); } catch (JsonUtils.JsonUtilException e) { assertThat(e.getMessage(), containsString("Invalid issuer format. Must be valid URL.")); } } @Test public void test_refresh_token_is_opaque_when_requested() { OAuth2AccessToken accessToken = performPasswordGrant(OPAQUE.getStringValue()); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); String refreshTokenValue = accessToken.getRefreshToken().getValue(); assertThat("Token value should be equal to or lesser than 36 characters", refreshTokenValue.length(), lessThanOrEqualTo(36)); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); TokenRequest refreshTokenRequest = getRefreshTokenRequest(); //validate both opaque and JWT refresh tokenSupport.tokens for (String s : Arrays.asList(refreshTokenValue, tokenSupport.tokens.get(refreshTokenValue).getValue())) { OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(s, refreshTokenRequest); assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID); } } @Test public void test_using_opaque_parameter_on_refresh_grant() { OAuth2AccessToken accessToken = performPasswordGrant(OPAQUE.getStringValue()); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); String refreshTokenValue = refreshToken.getValue(); Map<String, String> parameters = new HashMap<>(); parameters.put(REQUEST_TOKEN_FORMAT, OPAQUE.getStringValue()); TokenRequest refreshTokenRequest = getRefreshTokenRequest(parameters); //validate both opaque and JWT refresh tokenSupport.tokens for (String s : Arrays.asList(refreshTokenValue, tokenSupport.tokens.get(refreshTokenValue).getValue())) { OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(s, refreshTokenRequest); assertThat("Token value should be equal to or lesser than 36 characters", refreshedAccessToken.getValue().length(), lessThanOrEqualTo(36)); assertCommonUserAccessTokenProperties(new DefaultOAuth2AccessToken(tokenSupport.tokens.get(refreshedAccessToken).getValue()), CLIENT_ID); validateExternalAttributes(refreshedAccessToken); } } @Test public void testCreateOpaqueAccessTokenForAClient() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.clientScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(REQUEST_TOKEN_FORMAT, OPAQUE.getStringValue()); azParameters.put(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertTrue("Token is not a composite token", accessToken instanceof CompositeToken); assertThat("Token value should be equal to or lesser than 36 characters", accessToken.getValue().length(), lessThanOrEqualTo(36)); assertThat(accessToken.getRefreshToken(), is(nullValue())); } @Test public void testCreateAccessTokenForAClientInAnotherIdentityZone() { String subdomain = "test-zone-subdomain"; IdentityZone identityZone = getIdentityZone(subdomain); identityZone.setConfig( JsonUtils.readValue( "{\"tokenPolicy\":{\"accessTokenValidity\":3600,\"refreshTokenValidity\":7200}}", IdentityZoneConfiguration.class ) ); tokenSupport.copyClients(IdentityZoneHolder.get().getId(), identityZone.getId()); IdentityZoneHolder.set(identityZone); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.clientScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); useIZMIforAccessToken(tokenServices); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonClientAccessTokenProperties(accessToken); assertThat(accessToken, validFor(is(3600))); assertThat(accessToken, issuerUri(is("http://" + subdomain + ".localhost:8080/uaa/oauth/token"))); assertThat(accessToken.getRefreshToken(), is(nullValue())); validateExternalAttributes(accessToken); Assert.assertEquals(1, tokenSupport.publisher.getEventCount()); this.assertCommonEventProperties(accessToken, CLIENT_ID, tokenSupport.expectedJson); } @Test public void testCreateAccessTokenAuthcodeGrant() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); authorizationRequest.setResponseTypes(Sets.newHashSet("id_token")); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); Approval approval = new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(OPENID) .setExpiresAt(new Date()) .setStatus(ApprovalStatus.APPROVED); tokenSupport.approvalStore.addApproval(approval, IdentityZone.getUaaZoneId()); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); CompositeToken castAccessToken = (CompositeToken) accessToken; assertThat(castAccessToken.getIdTokenValue(), is(notNullValue())); validateAccessAndRefreshToken(accessToken); } @Test public void testCreateAccessTokenOnlyForClientWithoutRefreshToken() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID_NO_REFRESH_TOKEN_GRANT, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); validateAccessTokenOnly(accessToken, CLIENT_ID_NO_REFRESH_TOKEN_GRANT); assertNull(accessToken.getRefreshToken()); } @Test public void testCreateAccessTokenAuthcodeGrantSwitchedPrimaryKey() { String originalPrimaryKeyId = tokenSupport.tokenPolicy.getActiveKeyId(); try { tokenSupport.tokenPolicy.setActiveKeyId("otherKey"); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); validateAccessAndRefreshToken(accessToken); } finally { tokenSupport.tokenPolicy.setActiveKeyId(originalPrimaryKeyId); } } @Test public void testCreateAccessTokenPasswordGrant() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_PASSWORD); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); validateAccessAndRefreshToken(accessToken); tokenServices.loadAuthentication(accessToken.getValue()); //ensure that we can load without user_name claim tokenServices.setExcludedClaims(new HashSet(Arrays.asList(ClaimConstants.AUTHORITIES, ClaimConstants.USER_NAME, ClaimConstants.EMAIL))); accessToken = tokenServices.createAccessToken(authentication); assertNotNull(tokenServices.loadAuthentication(accessToken.getValue()).getUserAuthentication()); } @Test public void test_missing_required_user_groups() { tokenSupport.defaultClient.addAdditionalInformation(REQUIRED_USER_GROUPS, singletonList("uaa.admin")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_PASSWORD); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); expectedException.expect(InvalidTokenException.class); expectedException.expectMessage("User does not meet the client's required group criteria."); tokenServices.createAccessToken(authentication); } @Test public void testClientSecret_Added_Token_Validation_Still_Works() { tokenSupport.defaultClient.setClientSecret(SECRET); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_PASSWORD); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); //normal token validation tokenServices.loadAuthentication(accessToken.getValue()); //add a 2nd secret tokenSupport.defaultClient.setClientSecret(tokenSupport.defaultClient.getClientSecret() + " newsecret"); tokenServices.loadAuthentication(accessToken.getValue()); //generate a token when we have two secrets OAuth2AccessToken accessToken2 = tokenServices.createAccessToken(authentication); //remove the 1st secret tokenSupport.defaultClient.setClientSecret("newsecret"); try { tokenServices.loadAuthentication(accessToken.getValue()); fail("Token should fail to validate on the revocation signature"); } catch (InvalidTokenException e) { assertTrue(e.getMessage().contains("revocable signature mismatch")); } tokenServices.loadAuthentication(accessToken2.getValue()); OAuth2AccessToken accessToken3 = tokenServices.createAccessToken(authentication); tokenServices.loadAuthentication(accessToken3.getValue()); } @Test public void testCreateRevocableAccessTokenPasswordGrant() { OAuth2AccessToken accessToken = performPasswordGrant(); validateAccessAndRefreshToken(accessToken); } @Test public void testCreateAccessTokenExternalContext() { OAuth2AccessToken accessToken = getOAuth2AccessToken(); TokenRequest refreshTokenRequest = getRefreshTokenRequest(); OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), refreshTokenRequest); validateExternalAttributes(accessToken); validateExternalAttributes(refreshedAccessToken); } @Test public void testCreateAccessTokenRefreshGrant() { OAuth2AccessToken accessToken = getOAuth2AccessToken(); TokenRequest refreshTokenRequest = getRefreshTokenRequest(); OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), refreshTokenRequest); assertEquals(refreshedAccessToken.getRefreshToken().getValue(), accessToken.getRefreshToken().getValue()); this.assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID); assertThat(refreshedAccessToken, issuerUri(is(ISSUER_URI))); assertThat(refreshedAccessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(refreshedAccessToken, validFor(is(60 * 60 * 12))); validateExternalAttributes(accessToken); } @Test public void testCreateAccessTokenRefreshGrant_with_an_old_refresh_token_format_containing_scopes_claim() { //Given OAuth2AccessToken accessToken = getOAuth2AccessToken(); String refreshTokenJwt = accessToken.getRefreshToken().getValue(); String kid = JwtHelper.decode(refreshTokenJwt).getHeader().getKid(); HashMap claimsWithScopeAndNotGrantedScopeMap = JsonUtils.readValue(JwtHelper.decode(refreshTokenJwt).getClaims(), HashMap.class); claimsWithScopeAndNotGrantedScopeMap.put("scope", Arrays.asList("openid", "read", "write")); claimsWithScopeAndNotGrantedScopeMap.remove("granted_scopes"); Map<String, Object> tokenJwtHeaderMap = new HashMap<>(); tokenJwtHeaderMap.put("alg", JwtHelper.decode(refreshTokenJwt).getHeader().getAlg()); tokenJwtHeaderMap.put("kid", JwtHelper.decode(refreshTokenJwt).getHeader().getKid()); tokenJwtHeaderMap.put("typ", JwtHelper.decode(refreshTokenJwt).getHeader().getTyp()); String refreshTokenWithOnlyScopeClaimNotGrantedScopeClaim = UaaTokenUtils.constructToken(tokenJwtHeaderMap, claimsWithScopeAndNotGrantedScopeMap, keyInfoService.getKey(kid).getSigner()); //When OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(refreshTokenWithOnlyScopeClaimNotGrantedScopeClaim, getRefreshTokenRequest()); //Then this.assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID); assertThat(refreshedAccessToken, issuerUri(is(ISSUER_URI))); assertThat(refreshedAccessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(refreshedAccessToken, validFor(is(60 * 60 * 12))); validateExternalAttributes(accessToken); } @Test public void createAccessToken_usingRefreshGrant_inOtherZone() { String subdomain = "test-zone-subdomain"; IdentityZone identityZone = getIdentityZone(subdomain); identityZone.setConfig( JsonUtils.readValue( "{\"tokenPolicy\":{\"accessTokenValidity\":3600,\"refreshTokenValidity\":9600}}", IdentityZoneConfiguration.class ) ); tokenSupport.copyClients(IdentityZoneHolder.get().getId(), identityZone.getId()); IdentityZoneHolder.set(identityZone); OAuth2AccessToken accessToken = getOAuth2AccessToken(); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); useIZMIforAccessToken(tokenServices); OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); assertEquals(refreshedAccessToken.getRefreshToken().getValue(), accessToken.getRefreshToken().getValue()); this.assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID); assertThat(refreshedAccessToken, issuerUri(is("http://test-zone-subdomain.localhost:8080/uaa/oauth/token"))); assertThat(refreshedAccessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(refreshedAccessToken, validFor(is(3600))); validateExternalAttributes(accessToken); } @Test public void testCreateAccessTokenRefreshGrantAllScopesAutoApproved() { BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient); clientDetails.setAutoApproveScopes(singleton("true")); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails) ); // NO APPROVALS REQUIRED AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); assertEquals(refreshedAccessToken.getRefreshToken().getValue(), accessToken.getRefreshToken().getValue()); this.assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID); assertThat(refreshedAccessToken, issuerUri(is(ISSUER_URI))); assertThat(refreshedAccessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(refreshedAccessToken, validFor(is(60 * 60 * 12))); assertThat(accessToken.getRefreshToken(), is(not(nullValue()))); } @Test public void testCreateAccessTokenRefreshGrantSomeScopesAutoApprovedDowngradedRequest() { BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient); clientDetails.setAutoApproveScopes(singleton("true")); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails) ); // NO APPROVALS REQUIRED AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.readScope); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); assertEquals(refreshedAccessToken.getRefreshToken().getValue(), accessToken.getRefreshToken().getValue()); this.assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID); assertThat(refreshedAccessToken, issuerUri(is(ISSUER_URI))); assertThat(refreshedAccessToken, validFor(is(60 * 60 * 12))); assertThat(accessToken.getRefreshToken(), is(not(nullValue()))); } @Test public void testCreateAccessTokenRefreshGrantSomeScopesAutoApproved() { BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient); clientDetails.setAutoApproveScopes(tokenSupport.readScope); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails) ); Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); Calendar updatedAt = Calendar.getInstance(); updatedAt.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(OPENID) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); assertEquals(refreshedAccessToken.getRefreshToken().getValue(), accessToken.getRefreshToken().getValue()); this.assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID); assertThat(refreshedAccessToken, issuerUri(is(ISSUER_URI))); assertThat(refreshedAccessToken, validFor(is(60 * 60 * 12))); assertThat(accessToken.getRefreshToken(), is(not(nullValue()))); } @Test(expected = InvalidTokenException.class) public void testCreateAccessTokenRefreshGrantNoScopesAutoApprovedIncompleteApprovals() { BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient); clientDetails.setAutoApproveScopes(emptyList()); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails) ); Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); Calendar updatedAt = Calendar.getInstance(); updatedAt.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); } @Test public void testCreateAccessTokenRefreshGrantAllScopesAutoApprovedButApprovalDenied() { BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient); clientDetails.setAutoApproveScopes(tokenSupport.requestedAuthScopes); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails) ); Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); Calendar updatedAt = Calendar.getInstance(); updatedAt.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.DENIED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); assertNotNull(refreshedAccessToken); } @Test public void testCreateAccessTokenImplicitGrant() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_IMPLICIT); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, validFor(is(60 * 60 * 12))); assertThat(accessToken.getRefreshToken(), is(nullValue())); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); } @Test public void create_id_token_with_roles_scope() { Jwt idTokenJwt = getIdToken(singletonList(OPENID)); assertTrue(idTokenJwt.getClaims().contains("\"amr\":[\"ext\",\"rba\",\"mfa\"]")); } @Test public void create_id_token_with_amr_claim() { Jwt idTokenJwt = getIdToken(Arrays.asList(OPENID, ROLES)); assertTrue(idTokenJwt.getClaims().contains("\"amr\":[\"ext\",\"rba\",\"mfa\"]")); } @Test public void create_id_token_with_acr_claim() { Jwt idTokenJwt = getIdToken(Arrays.asList(OPENID, ROLES)); assertTrue(idTokenJwt.getClaims().contains("\"" + ClaimConstants.ACR + "\":{\"values\":[\"")); } @Test public void create_id_token_without_roles_scope() { Jwt idTokenJwt = getIdToken(singletonList(OPENID)); assertFalse(idTokenJwt.getClaims().contains("\"roles\"")); } @Test public void create_id_token_with_profile_scope() { Jwt idTokenJwt = getIdToken(Arrays.asList(OPENID, PROFILE)); assertTrue(idTokenJwt.getClaims().contains("\"given_name\":\"" + tokenSupport.defaultUser.getGivenName() + "\"")); assertTrue(idTokenJwt.getClaims().contains("\"family_name\":\"" + tokenSupport.defaultUser.getFamilyName() + "\"")); assertTrue(idTokenJwt.getClaims().contains("\"phone_number\":\"" + tokenSupport.defaultUser.getPhoneNumber() + "\"")); } @Test public void create_id_token_without_profile_scope() { Jwt idTokenJwt = getIdToken(singletonList(OPENID)); assertFalse(idTokenJwt.getClaims().contains("\"given_name\":")); assertFalse(idTokenJwt.getClaims().contains("\"family_name\":")); assertFalse(idTokenJwt.getClaims().contains("\"phone_number\":")); } @Test public void create_id_token_with_last_logon_time_claim() { Jwt idTokenJwt = getIdToken(singletonList(OPENID)); assertTrue(idTokenJwt.getClaims().contains("\"previous_logon_time\":12365")); } @Test public void testCreateAccessWithNonExistingScopes() { List<String> scopesThatDontExist = Arrays.asList("scope1", "scope2"); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, scopesThatDontExist); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_IMPLICIT); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, scope(is(scopesThatDontExist))); assertThat(accessToken, validFor(is(60 * 60 * 12))); assertThat(accessToken.getRefreshToken(), is(nullValue())); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(scopesThatDontExist)); } @Test public void createAccessToken_forUser_inanotherzone() { String subdomain = "test-zone-subdomain"; IdentityZone identityZone = getIdentityZone(subdomain); identityZone.setConfig( JsonUtils.readValue( "{\"tokenPolicy\":{\"accessTokenValidity\":3600,\"refreshTokenValidity\":9600}}", IdentityZoneConfiguration.class ) ); tokenSupport.copyClients(IdentityZone.getUaaZoneId(), identityZone.getId()); IdentityZoneHolder.set(identityZone); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); useIZMIforAccessToken(tokenServices); useIZMIforRefreshToken(tokenServices); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID); assertThat(accessToken, issuerUri(is("http://test-zone-subdomain.localhost:8080/uaa/oauth/token"))); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken, validFor(is(3600))); assertThat(accessToken.getRefreshToken(), is(not(nullValue()))); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is("http://test-zone-subdomain.localhost:8080/uaa/oauth/token"))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(9600))); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); } @Test public void testCreateAccessTokenAuthcodeGrantNarrowerScopes() { Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); Calendar updatedAt = Calendar.getInstance(); updatedAt.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); // First Request AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); assertThat(refreshToken, is(not(nullValue()))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.scope(is(tokenSupport.requestedAuthScopes))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.audience(is(tokenSupport.resourceIds))); // Second request with reduced scopes AuthorizationRequest reducedScopeAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.readScope); reducedScopeAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(reducedScopeAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); reducedScopeAuthorizationRequest.setRequestParameters(refreshAzParameters); OAuth2Authentication reducedScopeAuthentication = new OAuth2Authentication(reducedScopeAuthorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken reducedScopeAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(reducedScopeAuthorizationRequest, "refresh_token")); // AT should have the new scopes, RT should be the same assertThat(reducedScopeAccessToken, scope(is(tokenSupport.readScope))); assertEquals(reducedScopeAccessToken.getRefreshToken(), accessToken.getRefreshToken()); } @Test(expected = InvalidScopeException.class) public void testCreateAccessTokenAuthcodeGrantExpandedScopes() { Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); // First Request AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken.getRefreshToken(), is(not(nullValue()))); assertThat(accessToken.getRefreshToken(), OAuth2RefreshTokenMatchers.scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken.getRefreshToken(), OAuth2RefreshTokenMatchers.audience(is(tokenSupport.resourceIds))); // Second request with expanded scopes AuthorizationRequest expandedScopeAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.expandedScopes); expandedScopeAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(expandedScopeAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); expandedScopeAuthorizationRequest.setRequestParameters(refreshAzParameters); OAuth2Authentication expandedScopeAuthentication = new OAuth2Authentication(expandedScopeAuthorizationRequest.createOAuth2Request(), userAuthentication); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(expandedScopeAuthorizationRequest, "refresh_token")); } @Test public void testChangedExpiryForTokens() { BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient); clientDetails.setAccessTokenValiditySeconds(3600); clientDetails.setRefreshTokenValiditySeconds(36000); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails) ); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertThat(accessToken, validFor(is(3600))); assertThat(accessToken.getRefreshToken(), is(not(nullValue()))); assertThat(accessToken.getRefreshToken(), OAuth2RefreshTokenMatchers.validFor(is(36000))); } @Test(expected = TokenRevokedException.class) public void testUserUpdatedAfterRefreshTokenIssued() { Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); UaaUser user = tokenSupport.userDatabase.retrieveUserByName(tokenSupport.username, OriginKeys.UAA); UaaUser newUser = new UaaUser(new UaaUserPrototype() .withId(tokenSupport.userId) .withUsername(user.getUsername()) .withPassword("blah") .withEmail(user.getEmail()) .withAuthorities(user.getAuthorities())); tokenSupport.userDatabase.updateUser(tokenSupport.userId, newUser); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); } @Test public void testRefreshTokenExpiry() { Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient); // Back date the refresh token. Crude way to do this but i'm not sure of // another clientDetails.setRefreshTokenValiditySeconds(-36000); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails) ); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); try { tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); fail("Expected Exception was not thrown"); } catch (InvalidTokenException e) { assertThat(e.getMessage(), not(containsString(accessToken.getRefreshToken().getValue()))); } } @Test(expected = InvalidTokenException.class) public void testRefreshTokenAfterApprovalsRevoked() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); // Other scope is left unapproved for (Approval approval : tokenSupport.approvalStore.getApprovals(tokenSupport.userId, CLIENT_ID, IdentityZoneHolder.get().getId())) { tokenSupport.approvalStore.revokeApproval(approval, IdentityZoneHolder.get().getId()); } AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); } @Test(expected = InvalidTokenException.class) public void testRefreshTokenAfterApprovalsExpired() { Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, -3000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); } @Test(expected = InvalidTokenException.class) public void testRefreshTokenAfterApprovalsDenied() { Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, -3000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.DENIED), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); } @Test(expected = InvalidTokenException.class) public void testRefreshTokenAfterApprovalsMissing() { Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, -3000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.DENIED), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); } @Test(expected = InvalidTokenException.class) public void testRefreshTokenAfterApprovalsMissing2() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token")); } @Test public void testReadAccessToken() { readAccessToken(EMPTY_SET); } @Test public void testReadAccessToken_No_PII() { readAccessToken(new HashSet<>(Arrays.asList(ClaimConstants.EMAIL, ClaimConstants.USER_NAME))); } @Test public void testReadAccessToken_When_Given_Refresh_token_should_throw_exception() { tokenServices.setExcludedClaims(new HashSet<>(Arrays.asList(ClaimConstants.EMAIL, ClaimConstants.USER_NAME))); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; Calendar expiresAt1 = Calendar.getInstance(); expiresAt1.add(Calendar.MILLISECOND, 3000); Calendar updatedAt1 = Calendar.getInstance(); updatedAt1.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt1.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt1.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt1.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt1.getTime()), IdentityZoneHolder.get().getId()); Approval approval = new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(OPENID) .setExpiresAt(expiresAt1.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt1.getTime()); tokenSupport.approvalStore.addApproval( approval, IdentityZoneHolder.get().getId()); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); expectedException.expectMessage("The token does not bear a \"scope\" claim."); tokenServices.readAccessToken(accessToken.getRefreshToken().getValue()); } @Test(expected = InvalidTokenException.class) public void testReadAccessTokenForDeletedUserId() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); Calendar updatedAt = Calendar.getInstance(); updatedAt.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.tokenSupport.userDatabase.clear(); assertEquals(accessToken, tokenServices.readAccessToken(accessToken.getValue())); } @Test public void testLoadAuthenticationForAUser() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertEquals(USER_AUTHORITIES, loadedAuthentication.getAuthorities()); assertEquals(tokenSupport.username, loadedAuthentication.getName()); UaaPrincipal uaaPrincipal = (UaaPrincipal) tokenSupport.defaultUserAuthentication.getPrincipal(); assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); Authentication userAuth = loadedAuthentication.getUserAuthentication(); assertEquals(tokenSupport.username, userAuth.getName()); assertEquals(uaaPrincipal, userAuth.getPrincipal()); assertTrue(userAuth.isAuthenticated()); } @Test public void load_Opaque_AuthenticationForAUser() { tokenSupport.defaultClient.setAutoApproveScopes(singleton("true")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); azParameters.put(REQUEST_TOKEN_FORMAT, OPAQUE.getStringValue()); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertTrue("Token should be composite token", accessToken instanceof CompositeToken); CompositeToken composite = (CompositeToken) accessToken; assertThat("id_token should be JWT, thus longer than 36 characters", composite.getIdTokenValue().length(), greaterThan(36)); assertThat("Opaque access token must be shorter than 37 characters", accessToken.getValue().length(), lessThanOrEqualTo(36)); assertThat("Opaque refresh token must be shorter than 37 characters", accessToken.getRefreshToken().getValue().length(), lessThanOrEqualTo(36)); String accessTokenValue = tokenProvisioning.retrieve(composite.getValue(), IdentityZoneHolder.get().getId()).getValue(); Map<String, Object> accessTokenClaims = tokenSupport.tokenValidationService.validateToken(accessTokenValue, true).getClaims(); assertTrue((Boolean) accessTokenClaims.get(ClaimConstants.REVOCABLE)); String refreshTokenValue = tokenProvisioning.retrieve(composite.getRefreshToken().getValue(), IdentityZoneHolder.get().getId()).getValue(); Map<String, Object> refreshTokenClaims = tokenSupport.tokenValidationService.validateToken(refreshTokenValue, false).getClaims(); assertTrue((Boolean) refreshTokenClaims.get(ClaimConstants.REVOCABLE)); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertEquals(USER_AUTHORITIES, loadedAuthentication.getAuthorities()); assertEquals(tokenSupport.username, loadedAuthentication.getName()); UaaPrincipal uaaPrincipal = (UaaPrincipal) tokenSupport.defaultUserAuthentication.getPrincipal(); assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); Authentication userAuth = loadedAuthentication.getUserAuthentication(); assertEquals(tokenSupport.username, userAuth.getName()); assertEquals(uaaPrincipal, userAuth.getPrincipal()); assertTrue(userAuth.isAuthenticated()); Map<String, String> params = new HashMap<>(); params.put("grant_type", "refresh_token"); params.put("client_id", CLIENT_ID); params.put("token_format", OPAQUE.getStringValue()); OAuth2AccessToken newAccessToken = tokenServices.refreshAccessToken(composite.getRefreshToken().getValue(), new TokenRequest(params, CLIENT_ID, Collections.EMPTY_SET, "refresh_token")); assertThat("Opaque access token must be shorter than 37 characters", newAccessToken.getValue().length(), lessThanOrEqualTo(36)); assertThat("Opaque refresh token must be shorter than 37 characters", newAccessToken.getRefreshToken().getValue().length(), lessThanOrEqualTo(36)); } @Test public void loadAuthentication_when_given_an_opaque_refreshToken_should_throw_exception() { tokenSupport.defaultClient.setAutoApproveScopes(singleton("true")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); azParameters.put(REQUEST_TOKEN_FORMAT, OPAQUE.getStringValue()); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken compositeToken = tokenServices.createAccessToken(authentication); String refreshTokenValue = tokenProvisioning.retrieve(compositeToken.getRefreshToken().getValue(), IdentityZoneHolder.get().getId()).getValue(); expectedException.expect(InvalidTokenException.class); expectedException.expectMessage("The token does not bear a \"scope\" claim."); tokenServices.loadAuthentication(refreshTokenValue); } @Test public void loadAuthentication_when_given_an_refresh_jwt_should_throw_exception() { IdentityZoneHolder.get().getConfig().getTokenPolicy().setJwtRevocable(true); tokenSupport.defaultClient.setAutoApproveScopes(singleton("true")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); azParameters.put(REQUEST_TOKEN_FORMAT, JWT.getStringValue()); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken compositeToken = tokenServices.createAccessToken(authentication); TokenValidation refreshToken = tokenSupport.tokenValidationService.validateToken(compositeToken.getRefreshToken().getValue(), false); String refreshTokenValue = tokenProvisioning.retrieve(refreshToken.getClaims().get("jti").toString(), IdentityZoneHolder.get().getId()).getValue(); expectedException.expect(InvalidTokenException.class); expectedException.expectMessage("The token does not bear a \"scope\" claim."); tokenServices.loadAuthentication(refreshTokenValue); } @Test public void testLoadAuthenticationForAClient() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertThat("Client authorities match.", loadedAuthentication.getAuthorities(), containsInAnyOrder(AuthorityUtils.commaSeparatedStringToAuthorityList(CLIENT_AUTHORITIES).toArray()) ); assertEquals(CLIENT_ID, loadedAuthentication.getName()); assertEquals(CLIENT_ID, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); assertNull(loadedAuthentication.getUserAuthentication()); } @Test public void testLoadAuthenticationWithAnExpiredToken() { BaseClientDetails shortExpiryClient = tokenSupport.defaultClient; shortExpiryClient.setAccessTokenValiditySeconds(1); tokenSupport.clientDetailsService.setClientDetailsStore( IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, shortExpiryClient) ); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertThat(accessToken, validFor(is(1))); when(tokenSupport.timeService.getCurrentTimeMillis()).thenReturn(2001L); try { tokenServices.loadAuthentication(accessToken.getValue()); fail("Expected Exception was not thrown"); } catch (InvalidTokenException e) { assertThat(e.getMessage(), not(containsString(accessToken.getValue()))); } } @Test public void testCreateAccessTokenAuthcodeGrantAdditionalAuthorizationAttributes() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); azParameters.put("authorities", "{\"az_attr\":{\"external_group\":\"domain\\\\group1\", \"external_id\":\"abcd1234\"}}"); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken token = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(token, CLIENT_ID); assertThat(token, issuerUri(is(ISSUER_URI))); assertThat(token, scope(is(tokenSupport.requestedAuthScopes))); assertThat(token, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = token.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(token, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); Map<String, String> azMap = new LinkedHashMap<>(); azMap.put("external_group", "domain\\group1"); azMap.put("external_id", "abcd1234"); assertEquals(azMap, token.getAdditionalInformation().get("az_attr")); } @Test public void testWrongClientDoesNotLeakToken() { AuthorizationRequest ar = mock(AuthorizationRequest.class); OAuth2AccessToken accessToken = getOAuth2AccessToken(); TokenRequest refreshTokenRequest = getRefreshTokenRequest(); try { refreshTokenRequest.setClientId("invalidClientForToken"); tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), refreshTokenRequest); fail(); } catch (InvalidGrantException e) { assertThat(e.getMessage(), startsWith("Wrong client for this refresh token")); assertThat(e.getMessage(), not(containsString(accessToken.getRefreshToken().getValue()))); } } @Test public void createRefreshToken_JwtDoesNotContainScopeClaim() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); Map<String, String> authzParameters = new HashMap<>(authorizationRequest.getRequestParameters()); authzParameters.put(GRANT_TYPE, GRANT_TYPE_PASSWORD); authzParameters.put(REQUEST_TOKEN_FORMAT, JWT.toString()); authorizationRequest.setRequestParameters(authzParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); String refreshTokenString = accessToken.getRefreshToken().getValue(); assertNotNull(refreshTokenString); Claims refreshTokenClaims = getClaimsFromTokenString(refreshTokenString); assertNotNull(refreshTokenClaims); assertNull(refreshTokenClaims.getScope()); // matcher below can't match list against set assertThat(refreshTokenClaims.getGrantedScopes(), containsInAnyOrder(accessToken.getScope().toArray())); } @Test public void refreshAccessToken_withAccessToken() { expectedException.expect(InvalidTokenException.class); expectedException.expectMessage("Invalid refresh token."); tokenServices.refreshAccessToken(getOAuth2AccessToken().getValue(), getRefreshTokenRequest()); } private void readAccessToken(Set<String> excludedClaims) { tokenServices.setExcludedClaims(excludedClaims); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; Calendar expiresAt = Calendar.getInstance(); expiresAt.add(Calendar.MILLISECOND, 3000); Calendar updatedAt = Calendar.getInstance(); updatedAt.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); Approval approval = new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(OPENID) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()); tokenSupport.approvalStore.addApproval( approval, IdentityZoneHolder.get().getId()); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertEquals(accessToken, tokenServices.readAccessToken(accessToken.getValue())); tokenSupport.approvalStore.revokeApproval(approval, IdentityZoneHolder.get().getId()); try { tokenServices.readAccessToken(accessToken.getValue()); fail("Approval has been revoked"); } catch (InvalidTokenException x) { assertThat("Exception should be about approvals", x.getMessage().contains("some requested scopes are not approved")); } } private Jwt getIdToken(List<String> scopes) { return tokenSupport.getIdToken(scopes); } private String buildJsonString(List<String> list) { StringBuffer buf = new StringBuffer("["); int count = list.size(); for (String s : list) { buf.append("\""); buf.append(s); buf.append("\""); if (--count > 0) { buf.append(","); } } buf.append("]"); return buf.toString(); } private OAuth2AccessToken performPasswordGrant() { return performPasswordGrant(JWT.getStringValue()); } private OAuth2AccessToken performPasswordGrant(String tokenFormat) { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_PASSWORD); azParameters.put(REQUEST_TOKEN_FORMAT, tokenFormat); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); return tokenServices.createAccessToken(authentication); } private IdentityZone getIdentityZone(String subdomain) { IdentityZone identityZone = new IdentityZone(); identityZone.setId(subdomain); identityZone.setSubdomain(subdomain); identityZone.setName("The Twiglet Zone"); identityZone.setDescription("Like the Twilight Zone but tastier."); return identityZone; } private void validateAccessTokenOnly(OAuth2AccessToken accessToken, String clientId) { this.assertCommonUserAccessTokenProperties(accessToken, clientId); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes))); assertThat(accessToken, validFor(is(60 * 60 * 12))); validateExternalAttributes(accessToken); } private void validateAccessAndRefreshToken(OAuth2AccessToken accessToken) { validateAccessTokenOnly(accessToken, CLIENT_ID); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes)); } @SuppressWarnings({"unchecked", "rawtypes"}) private void validateExternalAttributes(OAuth2AccessToken accessToken) { Map<String, String> extendedAttributes = (Map<String, String>) accessToken.getAdditionalInformation().get(ClaimConstants.EXTERNAL_ATTR); if (tokenEnhancer != null) { String atValue = accessToken.getValue().length() < 40 ? tokenSupport.tokens.get(accessToken.getValue()).getValue() : accessToken.getValue(); Map<String, Object> claims = JsonUtils.readValue(JwtHelper.decode(atValue).getClaims(), new TypeReference<Map<String, Object>>() { }); assertNotNull(claims.get("ext_attr")); assertEquals("test", ((Map) claims.get("ext_attr")).get("purpose")); assertNotNull(claims.get("ex_prop")); assertEquals("nz", ((Map) claims.get("ex_prop")).get("country")); assertThat((List<String>) claims.get("ex_groups"), containsInAnyOrder("admin", "editor")); } else { assertNull("External attributes should not exist", extendedAttributes); } } private TokenRequest getRefreshTokenRequest() { return getRefreshTokenRequest(emptyMap()); } private TokenRequest getRefreshTokenRequest(Map<String, String> requestParameters) { AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); refreshAuthorizationRequest.setRequestParameters(requestParameters); Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); return tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"); } private OAuth2AccessToken getOAuth2AccessToken() { expiresAt.add(Calendar.MILLISECOND, 300000); updatedAt.add(Calendar.MILLISECOND, -1000); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.readScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(tokenSupport.writeScope.get(0)) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); tokenSupport.approvalStore.addApproval(new Approval() .setUserId(tokenSupport.userId) .setClientId(CLIENT_ID) .setScope(OPENID) .setExpiresAt(expiresAt.getTime()) .setStatus(ApprovalStatus.APPROVED) .setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId()); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = tokenSupport.defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); return tokenServices.createAccessToken(authentication); } private BaseClientDetails cloneClient(ClientDetails client) { return new BaseClientDetails(client); } @SuppressWarnings("unchecked") private void assertCommonClientAccessTokenProperties(OAuth2AccessToken accessToken) { assertThat(accessToken, allOf(clientId(is(CLIENT_ID)), userId(is(nullValue())), subject(is(CLIENT_ID)), username(is(nullValue())), cid(is(CLIENT_ID)), scope(is(tokenSupport.clientScopes)), audience(is(tokenSupport.resourceIds)), jwtId(not(isEmptyString())), issuedAt(is(greaterThan(0))), expiry(is(greaterThan(0))))); } @SuppressWarnings({"unused", "unchecked"}) private void assertCommonUserAccessTokenProperties(OAuth2AccessToken accessToken, String clientId) { assertThat(accessToken, allOf(username(is(tokenSupport.username)), clientId(is(clientId)), subject(is(tokenSupport.userId)), audience(is(tokenSupport.resourceIds)), origin(is(OriginKeys.UAA)), revocationSignature(is(not(nullValue()))), cid(is(clientId)), userId(is(tokenSupport.userId)), email(is(tokenSupport.email)), jwtId(not(isEmptyString())), issuedAt(is(greaterThan(0))), expiry(is(greaterThan(0))) )); } @SuppressWarnings("unchecked") private void assertCommonUserRefreshTokenProperties(OAuth2RefreshToken refreshToken) { assertThat(refreshToken, allOf(/*issuer(is(issuerUri)),*/ OAuth2RefreshTokenMatchers.username(is(tokenSupport.username)), OAuth2RefreshTokenMatchers.clientId(is(CLIENT_ID)), OAuth2RefreshTokenMatchers.subject(is(not(nullValue()))), OAuth2RefreshTokenMatchers.audience(is(tokenSupport.resourceIds)), OAuth2RefreshTokenMatchers.origin(is(OriginKeys.UAA)), OAuth2RefreshTokenMatchers.revocationSignature(is(not(nullValue()))), OAuth2RefreshTokenMatchers.jwtId(not(isEmptyString())), OAuth2RefreshTokenMatchers.issuedAt(is(greaterThan(0))), OAuth2RefreshTokenMatchers.expiry(is(greaterThan(0))) ) ); } private void assertCommonEventProperties(OAuth2AccessToken accessToken, String expectedPrincipalId, String expectedData) { Assert.assertEquals(1, tokenSupport.publisher.getEventCount()); TokenIssuedEvent event = tokenSupport.publisher.getLatestEvent(); Assert.assertEquals(accessToken, event.getSource()); Assert.assertEquals(tokenSupport.mockAuthentication, event.getAuthentication()); AuditEvent auditEvent = event.getAuditEvent(); Assert.assertEquals(expectedPrincipalId, auditEvent.getPrincipalId()); Assert.assertEquals(expectedData, auditEvent.getData()); Assert.assertEquals(AuditEventType.TokenIssuedEvent, auditEvent.getType()); } private Claims getClaimsFromTokenString(String token) { Jwt jwt = JwtHelper.decode(token); if (jwt == null) { return null; } else { return JsonUtils.readValue(jwt.getClaims(), Claims.class); } } private static void useIZMIforAccessToken(UaaTokenServices tokenServices) { TokenValidityResolver accessTokenValidityResolver = (TokenValidityResolver) ReflectionTestUtils.getField(tokenServices, "accessTokenValidityResolver"); ClientTokenValidity clientTokenValidity = (ClientTokenValidity) ReflectionTestUtils.getField(accessTokenValidityResolver, "clientTokenValidity"); ReflectionTestUtils.setField(clientTokenValidity, "identityZoneManager", new IdentityZoneManagerImpl()); } private static void useIZMIforRefreshToken(UaaTokenServices tokenServices) { RefreshTokenCreator refreshTokenCreator = (RefreshTokenCreator) ReflectionTestUtils.getField(tokenServices, "refreshTokenCreator"); TokenValidityResolver refreshTokenValidityResolver = (TokenValidityResolver) ReflectionTestUtils.getField(refreshTokenCreator, "refreshTokenValidityResolver"); ClientTokenValidity clientTokenValidity = (ClientTokenValidity) ReflectionTestUtils.getField(refreshTokenValidityResolver, "clientTokenValidity"); ReflectionTestUtils.setField(clientTokenValidity, "identityZoneManager", new IdentityZoneManagerImpl()); } }
package com.example.selectmenu; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SearchView; import android.widget.Toast; import java.lang.reflect.Method; public class LoginActivity extends AppCompatActivity { private Button login; private Button regbtn; private EditText uedit; private EditText keyedit; private String username,ukey; private MyApplication app; private CheckBox remuser; SharedPreferences usermessage; private final String ufile = "ufile"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); app=(MyApplication)getApplication(); uedit = (EditText)findViewById(R.id.editText); keyedit=(EditText)findViewById(R.id.editText2); remuser=(CheckBox)findViewById(R.id.rember_me); usermessage=LoadUserPreference(); username=((SharedPreferences) usermessage).getString("uname",""); ukey=((SharedPreferences) usermessage).getString("ukey",""); int ifrem = ((SharedPreferences) usermessage).getInt("ifrem",0); if(ifrem == 1 ){ uedit.setText(username); keyedit.setText(ukey); Toast.makeText(LoginActivity.this,"恢复用户状态成功!",Toast.LENGTH_SHORT).show(); } login=(Button) findViewById(R.id.submit); regbtn=(Button)findViewById(R.id.signIn); btnlistener btnlis = new btnlistener(); login.setOnClickListener(btnlis); regbtn.setOnClickListener(btnlis); Button buttonChangeToRelative = (Button)findViewById(R.id.changeToRlative); buttonChangeToRelative.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent2 = new Intent(LoginActivity.this,SlectMenuRelative.class);//SlectMenuRelative 问题 Toast.makeText(LoginActivity.this,"启动相对布局界面",Toast.LENGTH_SHORT).show(); startActivity(intent2); } }); Button switch1 = (Button)findViewById(R.id.changel); switch1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(LoginActivity.this,Main2Activity.class); Toast.makeText(LoginActivity.this,"切换表格布局",Toast.LENGTH_SHORT).show(); startActivity(intent); } }); Button switch3 = (Button)findViewById(R.id.maintable); switch3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent3 = new Intent(LoginActivity.this,MainTable.class); Toast.makeText(LoginActivity.this,"maintable",Toast.LENGTH_SHORT).show(); startActivity(intent3); } }); /*Button submit = (Button)findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { usermessage = LoadUserPreference(); String uname = usermessage.getString("uname",""); Intent intent3 = new Intent(MainActivity.this,MainTable.class); Toast.makeText(MainActivity.this,"maintable",Toast.LENGTH_SHORT).show(); startActivity(intent3); } });*/ } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.conmenu,menu); MenuItem sItem = menu.findItem(R.id.action_search); sItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { return false; } }); SearchView searchView = (SearchView)sItem.getActionView(); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuOpened(int featureID, Menu menu){ if(featureID == Window.FEATURE_ACTION_BAR && menu != null){ if(menu.getClass().getSimpleName().equals("MenuBuilder")){ try { Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible",Boolean.TYPE); m.setAccessible(true); m.invoke(menu,true); }catch (Exception e){ } } } return super.onMenuOpened(featureID,menu); } @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case R.id.about: Intent intent = new Intent(LoginActivity.this,Help.class); Toast.makeText(LoginActivity.this,"about",Toast.LENGTH_SHORT).show(); startActivity(intent); break; case R.id.exit: AlertDialog.Builder exitdialog = new AlertDialog.Builder(LoginActivity.this); exitdialog.setTitle("note:").setMessage("Sure to exit?"); exitdialog.setPositiveButton("sure", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); exitdialog.setNegativeButton("cancel",null); exitdialog.create(); exitdialog.show(); break; default: break; } return super.onOptionsItemSelected(item); } protected void onActivityResult(int requestCode,int resultCode,Intent data){ super.onActivityResult(requestCode,resultCode,data); if(requestCode == 1){ if(resultCode == RESULT_OK){ Bundle udata = data.getExtras(); username = udata.getString("uname"); ukey = udata.getString("ukey"); uedit.setText(username); keyedit.setText(ukey); } } } private SharedPreferences LoadUserPreference(){ int mode = Activity.MODE_PRIVATE; SharedPreferences usetting = getSharedPreferences(ufile,mode); return usetting; } private void WriteUserPreference(String name,String key,int ifrem){ int mode = Activity.MODE_PRIVATE; SharedPreferences uSetting = getSharedPreferences(ufile,mode); SharedPreferences.Editor editor = uSetting.edit(); editor.putString("uname",name); editor.putString("ukey",key); editor.putInt("ifrem",ifrem); editor.commit(); } class btnlistener implements View.OnClickListener{ @Override public void onClick(View v){ switch (v.getId()){ case R.id.submit: username = uedit.getText().toString().trim(); ukey = keyedit.getText().toString().trim(); if(username.isEmpty()||ukey.isEmpty()){ Toast.makeText(LoginActivity.this,"NULL!!!",Toast.LENGTH_SHORT).show(); uedit.setFocusable(true); uedit.requestFocus(); return; } else{ usermessage=LoadUserPreference(); String uname = usermessage.getString("uname",""); String uukey = usermessage.getString("ukey",""); if(!username.equalsIgnoreCase(uname)||!ukey.equalsIgnoreCase(uukey)){ Toast.makeText(LoginActivity.this,"username or password wrong",Toast.LENGTH_SHORT).show(); return; } if(remuser.isChecked()){ WriteUserPreference(username,ukey,1); }else{ WriteUserPreference(username,ukey,0); } app.setLoginstate(true); } Intent intentt = new Intent(LoginActivity.this,MainTable.class); setResult(RESULT_OK,intentt); finish(); break; case R.id.signIn: app.setLoginstate(false); Intent intent2 = new Intent(LoginActivity.this,SignIn.class); Toast.makeText(LoginActivity.this,"注册",Toast.LENGTH_SHORT).show(); startActivityForResult(intent2,1); break; default: break; } } } }
/* Xholon Runtime Framework - executes event-driven & dynamic applications * Copyright (C) 2007, 2008 Ken Webb * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * 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. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.primordion.ef.fsm; import java.util.Date; import org.primordion.ef.AbstractXholon2ExternalFormat; import org.primordion.xholon.base.ISignal; import org.primordion.xholon.base.IStateMachineEntity; import org.primordion.xholon.base.IXholon; import org.primordion.xholon.base.StateMachineEntity; import org.primordion.xholon.base.Xholon; import org.primordion.xholon.base.XPath; import org.primordion.xholon.common.mechanism.CeStateMachineEntity; import org.primordion.xholon.service.ef.IXholon2ExternalFormat; /** * Export an executing Xholon application as an Java file in Quantum Event Processor (QEP) format. * @author <a href="mailto:ken@primordion.com">Ken Webb</a> * @see <a href="http://www.primordion.com/Xholon">Xholon Project website</a> * @since 0.7 (Created on August 14, 2007) * @see http://www.quantum-leaps.com for information about QEP. */ public class Xholon2Qep extends AbstractXholon2ExternalFormat implements IXholon2ExternalFormat, CeStateMachineEntity { private String qepFileName; private String outPath = "./ef/qep/"; private StringBuilder sb; private IXholon root; private String modelName; private XPath xpath = null; private IXholon owningXholon; private String owningXholonName; private String owningXholonJavaClassName; private IXholon topState; /** * Current date and time. */ private Date timeNow; private long timeStamp; /** * Constructor. */ public Xholon2Qep() {} @Override public String getVal_String() { return sb.toString(); } /** * Constructor. * @param qepFileName Name of the output QEP file. * @param modelName Name of the model. * @param root Root of the tree that will be written out. */ public Xholon2Qep(String qepFileName, String modelName, IXholon root) { initialize(qepFileName, modelName, root); } /* * @see org.primordion.xholon.io.IXholon2Qep#initialize(java.lang.String, java.lang.String, org.primordion.xholon.base.IXholon) */ public boolean initialize(String qepFileName, String modelName, IXholon root) { timeNow = new Date(); timeStamp = timeNow.getTime(); if (qepFileName == null) { this.qepFileName = outPath + root.getXhcName() + "_" + root.getId() + "_" + timeStamp + ".qep"; } else { this.qepFileName = qepFileName; } this.modelName = modelName; this.root = root; xpath = new XPath(); return true; } /* * @see org.primordion.xholon.io.IXholon2Qep#writeAll() */ public void writeAll() { topState = xpath.evaluate("descendant::StateMachine/descendant::State", root); if (topState == null) {return;} owningXholon = ((IStateMachineEntity)topState).getOwningXholon(); owningXholonName = owningXholon.getXhcName(); owningXholonJavaClassName = owningXholon.getClass().getName(); // get the entire path + name if (qepFileName == null) { // there is no default file name, so create a file name consistent with this Java class qepFileName = "./qep/" + owningXholonName + "QHsm.java"; } sb = new StringBuilder(); sb.append(""); sb.append( "\n//Automatically generated by Xholon version 0.7, using Xholon2Qep.java\n//" + timeNow + "\n//www.primordion.com/Xholon\n" + "//See http://www.quantum-leaps.com for information about QEP.\n"); writeQep(); writeToTarget(sb.toString(), qepFileName, outPath, root); } /** * Write the qep tag, and the entire structure contained within that element. */ protected void writeQep() { sb.append("package " + owningXholonJavaClassName.substring(0, owningXholonJavaClassName.lastIndexOf('.')) + ";\n\n"); sb.append("import qep.*;\n"); sb.append("import " + owningXholonJavaClassName + ";\n"); owningXholonJavaClassName = owningXholonJavaClassName.substring(owningXholonJavaClassName.lastIndexOf('.') + 1); sb.append("import org.primordion.xholon.base.IMessage;\n"); sb.append("import org.primordion.xholon.base.ISignal;\n"); sb.append("\n"); sb.append("public class "); sb.append(owningXholonName + "QHsm"); sb.append(" extends QHsm {\n"); // write variables // owner of this state machine sb.append("protected "); sb.append(owningXholonJavaClassName + " smOwner;\n"); // write QEP signals // use Java reflection; but not yet sure if these are really needed // write QEP events sb.append("public static class " + owningXholonName + "Evt extends QEvent {\n"); sb.append("\tpublic IMessage msg;\n"); sb.append("\tpublic " + owningXholonName + "Evt" + "(int s, IMessage msgArg) {\n"); sb.append("\t\tsig = s;\n"); sb.append("\t\tmsg = msgArg;\n"); sb.append("\t}\n"); sb.append("}\n"); // write constructor sb.append("public " + owningXholonName + "QHsm (" + owningXholonJavaClassName + " smOwner) {\n"); sb.append("\tthis.smOwner = smOwner;\n"); sb.append("}\n"); // write QEP init() sb.append("public void init(QEvent e) {\n"); sb.append("\tsuper.init_tran(" + topState.getRoleName() + ");\n"); sb.append("}\n"); sb.append("\n"); writeStates(); sb.append("}\n"); } /** * Write notes. */ protected void writeNotes() { sb.append("//This QEP file has been generated by an early version of the Xholon QEP exporter.\n"); sb.append("modelName: " + modelName); } /** * Write the state machine hierarchy. */ protected void writeStates() { sb.append("// States\n"); if (root.getFirstChild() != null) { writeState(root.getFirstChild()); } } /** * Write one state, its transitions, and its child states. * @param node The current node in the Xholon composite structure hierarchy. */ protected void writeState(IXholon node) { switch(node.getXhcId()) { case StateCE: case FinalStateCE: sb.append("protected QState " + node.getRoleName() + " = new QState() {\n"); sb.append("\tpublic QState handler(QEvent e) {\n"); sb.append("\t\tIMessage msg = e.getClass() == " + owningXholonName + "Evt.class ? " + "((" + owningXholonName + "Evt)e).msg : null;\n"); sb.append("\t\tswitch (e.sig) {\n"); // write Q_ENTRY_SIG int actId = ((IStateMachineEntity)node).getEntryActivityId(); if (actId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\tcase Q_ENTRY_SIG:\n"); sb.append("\t\t\tsmOwner.performActivity(" + actId + ", msg);\n"); sb.append("\t\t\treturn null;\n"); } // write Q_INIT_SIG writePseudostateInitial(node); // write user transitions writeTransitions(node); // transitions // write Q_EXIT_SIG actId = ((IStateMachineEntity)node).getExitActivityId(); if (actId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\tcase Q_EXIT_SIG:\n"); sb.append("\t\t\tsmOwner.performActivity(" + actId + ", msg);\n"); sb.append("\t\t\treturn null;\n"); } sb.append("\t\t}\n"); // end switch // return the parent state (the super state) IXholon parentState = node.getParentNode(); String parentStateStr = "top"; // default return value while (parentState != null) { if (parentState.getXhcId() == StateCE) { parentStateStr = parentState.getRoleName(); break; } else if (parentState.getXhcId() == StateMachineCE) { break; } parentState = parentState.getParentNode(); } sb.append("\t\treturn " + parentStateStr + ";\n"); sb.append("\t}\n"); sb.append("};\n"); break; case RegionCE: break; case PseudostateTerminateCE: sb.append("protected QState " + node.getRoleName() + " = new QState() {\n"); sb.append("\tpublic QState handler(QEvent e) {\n"); // return the parent state (the super state) parentState = node.getParentNode(); parentStateStr = "top"; // default return value while (parentState != null) { if (parentState.getXhcId() == StateCE) { parentStateStr = parentState.getRoleName(); break; } else if (parentState.getXhcId() == StateMachineCE) { break; } parentState = parentState.getParentNode(); } // parentStateStr may equal null at this point // this is OK if sb.append("\t\treturn " + parentStateStr + ";\n"); sb.append("\t}\n"); sb.append("};\n"); break; default: break; } // children if (node.getFirstChild() != null) { writeState(node.getFirstChild()); } // siblings if (node.getNextSibling() != null) { writeState(node.getNextSibling()); } } /** * Write an initial pseudostate element, if the current state has one. * @param stateNode The current state node. */ protected void writePseudostateInitial(IXholon stateNode) { IXholon initial = xpath.evaluate("descendant::PseudostateInitial", stateNode); if (initial != null) { IXholon transition = initial.getPort(0); sb.append("\t\tcase Q_INIT_SIG:\n"); int actId = ((IStateMachineEntity)transition).getActivityId(); if (actId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\t\tsmOwner.performActivity(" + actId + ", msg);\n"); } sb.append("\t\t\tQ_INIT("); IXholon target = transition.getPort(0); sb.append(target.getRoleName()); sb.append(");\n"); sb.append("\t\t\treturn null;\n"); } } /** * Write all transitions that eminate from this state. * @param stateNode The current state node. */ protected void writeTransitions(IXholon stateNode) { // TODO get actual number of ports to use in for loop int lastEvent = ISignal.SIGNAL_DUMMY; // a signal that will never occur for (int i = 0; i < StateMachineEntity.getMaxPorts(); i++) { IXholon transition = stateNode.getPort(i); if (transition != null) { lastEvent = writeTransition(transition, lastEvent); } } // write out end of final transition, if there are any transitions if (lastEvent != ISignal.SIGNAL_DUMMY) { sb.append("\t\t\treturn null;\n"); } } /** * Write one transition. * @param transition The current transition node. * @param lastEvent */ protected int writeTransition(IXholon transition, int lastEvent) { int event = ISignal.SIGNAL_DUMMY; int triggerIx = 0; // trigger index used as input to getTrigger() event = ((IStateMachineEntity)transition).getTrigger(triggerIx); IXholon triggerNode = xpath.evaluate("Trigger", transition); if (event != lastEvent) { if (lastEvent != ISignal.SIGNAL_DUMMY) { // write out end of last transition, if this is not the first transition sb.append("\t\t\treturn null;\n"); } while ((triggerNode != null) && (triggerNode.getXhcId() == TriggerCE)) { // TODO should use constants //event = ((IStateMachineEntity)transition).getTrigger(triggerIx); // write out case label(s) sb.append("\t\tcase "); if (triggerNode != null) { if (triggerNode.getRoleName().startsWith("ISignal")) { sb.append(triggerNode.getRoleName()); } else { sb.append(owningXholonJavaClassName + "." + triggerNode.getRoleName()); } } else { sb.append(Integer.toString(event)); } sb.append(":\n"); triggerIx++; triggerNode = triggerNode.getNextSibling(); // get a possible additional trigger for this transition } } int guardActId = ((IStateMachineEntity)transition).getGuardActivityId(); if (guardActId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\t\t"); if (event == lastEvent) { sb.append("else "); } sb.append("if (smOwner.performGuard(" + guardActId + ", msg)) {\n"); sb.append("\t"); } int actId = ((IStateMachineEntity)transition).getActivityId(); if (actId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\t\tsmOwner.performActivity(" + actId + ", msg);\n"); } IXholon target = transition.getPort(0); if (target != null) { if (guardActId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t" ); } switch (target.getXhcId()) { case StateCE: sb.append("\t\t\tQ_TRAN(" ); sb.append(target.getRoleName()); sb.append(");\n" ); break; case FinalStateCE: case PseudostateTerminateCE: sb.append("\t\t\tQ_TRAN(" ); sb.append(target.getRoleName()); sb.append(");\n" ); break; case PseudostateChoiceCE: writeChoices(target); break; case PseudostateEntryPointCE: case PseudostateExitPointCE: target = target.getPort(0).getPort(0); if (target != null) { sb.append("\t\t\tQ_TRAN(" ); sb.append(target.getRoleName()); sb.append(");\n" ); } break; default: break; } } if (guardActId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\t\t}\n" ); } return event; } /** * Write all transitions from a choice node. * @param choiceNode A UML choice node. */ protected void writeChoices(IXholon choiceNode) { for (int i = 0; i < StateMachineEntity.getMaxPorts(); i++) { IXholon transition = choiceNode.getPort(i); if (transition != null) { writeChoice(transition, i); } } } /** * Write one transition from a choice node. * @param transition A transition leading out of a choice. * @param ix An index. If this is not the first transition leading from the choice, then "else" needs to be added. */ protected void writeChoice(IXholon transition, int ix) { int guardActId = ((IStateMachineEntity)transition).getGuardActivityId(); if (guardActId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\t\t"); if (ix > 0) { sb.append("else "); } sb.append("if (smOwner.performGuard(" + guardActId + ", msg)) {\n"); sb.append("\t"); } int actId = ((IStateMachineEntity)transition).getActivityId(); if (actId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\t\tsmOwner.performActivity(" + actId + ", msg);\n"); } IXholon target = transition.getPort(0); if (target != null) { if (guardActId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t" ); } sb.append("\t\t\tQ_TRAN(" ); switch (target.getXhcId()) { case StateCE: sb.append(target.getRoleName()); break; case FinalStateCE: case PseudostateTerminateCE: sb.append(target.getRoleName()); break; case PseudostateChoiceCE: writeChoices(target); break; case PseudostateEntryPointCE: case PseudostateExitPointCE: target = target.getPort(0).getPort(0); if (target != null) { sb.append(target.getRoleName()); } break; default: break; } sb.append(");\n" ); } if (guardActId != StateMachineEntity.ACTIVITYID_NONE) { sb.append("\t\t\t}\n" ); } } }
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis.config.transitions; import com.google.devtools.build.lib.analysis.config.BuildOptions; import com.google.devtools.build.lib.analysis.config.BuildOptionsView; import com.google.devtools.build.lib.events.EventHandler; import java.util.Collections; import java.util.Map; /** * A configuration transition that maps a single input {@link BuildOptions} to a single output * {@link BuildOptions}. * * <p>Also see {@link SplitTransition}, which maps a single input {@link BuildOptions} to possibly * multiple {@link BuildOptions}. * * <p>The concept is simple: given the input configuration's build options, the transition does * whatever it wants to them and returns the modified result. * * <p>Implementations must be stateless: the output must exclusively depend on the input build * options and any immutable member fields. Implementations must also override {@link Object#equals} * and {@link Object#hashCode} unless exclusively accessed as singletons. For example: * * <pre> * public class MyTransition implements PatchTransition { * public MyTransition INSTANCE = new MyTransition(); * * private MyTransition() {} * * {@literal @}Override * public BuildOptions patch(RestrictedBuildOptions options) { * BuildOptions toOptions = options.clone(); * // Change some setting on toOptions * return toOptions; * } * } * </pre> * * <p>For performance reasons, the input options are passed as a <i>reference</i>, not a * <i>copy</i>. Implementations should <i>always</i> treat these as immutable, and call {@link * com.google.devtools.build.lib.analysis.config.BuildOptions#clone} before making changes. * Unfortunately, {@link com.google.devtools.build.lib.analysis.config.BuildOptions} doesn't * currently enforce immutability. So care must be taken not to modify the wrong instance. */ public interface PatchTransition extends ConfigurationTransition { /** * Applies the transition. * * <p>Blaze throws an {@link IllegalArgumentException} if this method reads any options fragment * not declared in {@link ConfigurationTransition#requiresOptionFragments}. * * @param options the options representing the input configuration to this transition. <b>DO NOT * MODIFY THIS VARIABLE WITHOUT CLONING IT FIRST!</b> * @param eventHandler * @return the options representing the desired post-transition configuration */ BuildOptions patch(BuildOptionsView options, EventHandler eventHandler); @Override default Map<String, BuildOptions> apply( BuildOptionsView buildOptions, EventHandler eventHandler) { return Collections.singletonMap(PATCH_TRANSITION_KEY, patch(buildOptions, eventHandler)); } @Override default String reasonForOverride() { return "This is a fundamental transition modeling the simple, common case 1-1 options mapping"; } }
package maged.csi5230.edu.tictactoegame; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.telephony.SmsMessage; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import java.util.Objects; import maged.csi5230.edu.tictactoegame.utils.Constants; import maged.csi5230.edu.tictactoegame.utils.SmsUtils; import static android.content.Context.MODE_PRIVATE; /** * Created by dragonlayout on 2017/11/10. */ public class SMSMessageBroadcastReceiver extends BroadcastReceiver { public static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED"; private OnSmsReceivedListener mListener; @Override public void onReceive(final Context context, final Intent intent) { // sms receive action if (Objects.equals(intent.getAction(), SMS_ACTION)) { // get sms message from intent Bundle bundle = intent.getExtras(); if (bundle != null) { Object pdusData[] = (Object[]) bundle.get("pdus"); // pdu: protocol data unit // parse the sms // for this application, one single sms can contain the protocol SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdusData[0]); String messageBody = msg.getMessageBody(); final long phoneNumber = Long.valueOf(msg.getDisplayOriginatingAddress()); // handle the self-defined protocol // the protocol is string, interval with ',' number like x,y,z // for the x is the flag of the player's action // x => 0 join, y has three options, -1, 0, 1, // -1 for you send a invitation, // 0 for the receiver say no to the invitation // 1 for the receiver say yes to the game // z stands for the player's name like John // => 1 start // y has three options, -1, 0, 1 // -1 for you send a start request // 0 for you say no the the start request // 1 for you say yes the the start request // z stands for the player's name like John // // => 2 stop button // y has three options -1, 0, 1 // -1 for request for stopping the game // 0 for refuse to stop the game // 1 for agree to stop the game // z => name // => 4 move i.e. => 4,0,1,chenlong // y position data(0,1), z => opponent's name // y => -1,1 guest wins circle // y => -1,0 host wins plus // y => -1,-1 no winner int flag = Integer.valueOf(messageBody.split(",")[0]); switch (flag) { case 0: int joinY = Integer.valueOf(messageBody.split(",")[1]); final String joniName = messageBody.split(",")[2]; if (joinY == -1) { // you got a game invitation // now z represent the player's name(who invite you to join the game) // popup a dialog to ask you say yes or no View view = LayoutInflater.from(context).inflate(R.layout.view_welcome_dialog_layout, null); final EditText editTextName = view.findViewById(R.id.edit_text_name); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Game Invitation") .setMessage(joniName + " " + "invite you to join the TicTacToe Game!") .setView(view) .setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!TextUtils.isEmpty(editTextName.getText())) { // save to sharedPreferences SharedPreferences sf = context.getSharedPreferences(Constants.SF_FILE_NAME, MODE_PRIVATE); sf.edit().putLong(Constants.PHONE_NUMBER, phoneNumber).apply(); sf.edit().putString(Constants.NAME, editTextName.getText().toString()).apply(); // go to the mainActivity Intent mainActivityIntent = new Intent(context, MainActivity.class); mainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mainActivityIntent.putExtra(Constants.OPPONENT_PLAYER_NAME, joniName); context.startActivity(mainActivityIntent); SmsUtils.sendMessage(phoneNumber, "0,1," + editTextName.getText().toString()); } } }) .setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // close the dialog } }); AlertDialog dialog = builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); } else if (joinY == 1) { // join accepted, jump to mainActivity Intent mainActivityIntent = new Intent(context, MainActivity.class); mainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mainActivityIntent.putExtra(Constants.OPPONENT_PLAYER_NAME, joniName); context.startActivity(mainActivityIntent); } else { // todo toast 对方未接受 join请求 } break; case 1: int startY = Integer.valueOf(messageBody.split(",")[1]); final String startName = messageBody.split(",")[2]; if (startY == -1) { // pop up a dialog // get a game start request AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Start the game") .setMessage("You want to start the game with " + startName) .setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // send sms back SharedPreferences sf = context.getSharedPreferences(Constants.SF_FILE_NAME, MODE_PRIVATE); long opponentPhoneNumber = sf.getLong(Constants.PHONE_NUMBER, 0); String name = sf.getString(Constants.NAME, "default name"); SmsUtils.sendMessage(opponentPhoneNumber, "1,1," + name); // 通知 mListener.agreeToStartTheGame(startName); } }) .setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // dismiss the dialog } }) .show(); } else if (startY == 1) { // say yes // not your turn just display whose turn it is mListener.getStartGameConfirmed(startName); } else { // todo toast not agree to start the game } break; case 2: // stop button int stopY = Integer.valueOf(messageBody.split(",")[1]); SharedPreferences sf = context.getSharedPreferences(Constants.SF_FILE_NAME, MODE_PRIVATE); final long opponentPhoneNumber = sf.getLong(Constants.PHONE_NUMBER, 0); final String name = sf.getString(Constants.NAME, "default name"); if (stopY == -1) { // 对手提出结束游戏 弹出对话框 统一或者拒绝 AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Stop the game.") .setMessage("Do you agree to stop the game?") .setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // send back sms SmsUtils.sendMessage(opponentPhoneNumber, "2,1," + name); // close the main activity mListener.finishMainActivity(); } }) .setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // send back sms no agree to stop the game SmsUtils.sendMessage(opponentPhoneNumber, "2,0," + name); } }) .show(); } else if (stopY == 0) { // 对手拒绝 结束游戏 继续下去 // todo toast } else { // 对手统一结束游戏 关闭 main activity mListener.finishMainActivity(); } break; case 4: // move part 4,0,0,name int moveFlag = Integer.valueOf(messageBody.split(",")[1]); if (moveFlag < 0) { // got a winner or no winner pop up a dialog int result = Integer.valueOf(messageBody.split(",")[2]); String winnerName = messageBody.split(",")[3]; String dialogMessage = ""; int hostOrGuest = mListener.hostOrGuest(); if (hostOrGuest == result) { dialogMessage = "Congrats you win the game."; } else { dialogMessage = winnerName + " wins the game."; } AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Game Over") .setMessage(dialogMessage) // .setPositiveButton("Restart the game", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // todo restart the game // // } // }) .setNegativeButton("Leave", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // leave the game mListener.finishMainActivity(); } }) .show(); } else { // send back sms // get to display the opponent's move int x = Integer.valueOf(messageBody.split(",")[1]); int y = Integer.valueOf(messageBody.split(",")[2]); mListener.showOpponentMove(x, y); } break; default: break; } } } } public void setOnSmsReceivedListener(OnSmsReceivedListener listener) { mListener = listener; } public interface OnSmsReceivedListener { // agree to start the game void agreeToStartTheGame(String opponentName); // host get the confirm of starting the game void getStartGameConfirmed(String opponentName); // display the opponent's move void showOpponentMove(int x, int y); // finish mainActivity void finishMainActivity(); int hostOrGuest(); } }
/* * Copyright 2019 y7 * * 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.y7single.service.annotations; import com.y7single.service.model.po.BasePO; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author: y7 * @date: 2019/10/29 17:43 * @qq: 88247290 * @wechat: 88247290 * @phone: 13562233004 * @email: 88247290@qq.com * @github: https://github.com/PayAbyss * @description: unknown */ @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface JoinTable { /** * 连接对象 * * @return cls */ Class<? extends BasePO> connectClass(); /** * 连接列 * * @return 列名 */ String connectColumn(); /** * 关联对象 * * @return */ Class<? extends BasePO> joinClass(); /** * 连接列 */ String joinColumn(); /** * 查询别名 * * @return 查询别名 */ String aliasName(); /** * 查询列 * * @return 列明 */ String queryName(); }
/* * Copyright 2020 Fraunhofer Institute for Software and Systems Engineering * * 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.dataspaceconnector.service.message.type; import de.fraunhofer.iais.eis.ArtifactResponseMessage; import de.fraunhofer.iais.eis.DynamicAttributeTokenBuilder; import de.fraunhofer.iais.eis.TokenFormat; import io.dataspaceconnector.model.message.ArtifactResponseMessageDesc; import io.dataspaceconnector.service.ids.ConnectorService; import io.dataspaceconnector.service.ids.DeserializationService; import de.fraunhofer.ids.messaging.protocol.http.IdsHttpService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import java.net.URI; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @SpringBootTest(classes = {ArtifactResponseService.class}) class ArtifactResponseServiceTest { @MockBean private ConnectorService connectorService; @MockBean private IdsHttpService idsHttpService; @MockBean private DeserializationService deserializationService; @Autowired private ArtifactResponseService responseService; @Test public void buildMessage_null_throwsIllegalArgumentException() { /* ARRANGE */ // Nothing to arrange here. /* ACT & ASSERT */ assertThrows(IllegalArgumentException.class, () -> responseService.buildMessage(null)); } @Test public void buildMessage_validDesc_returnValidMessage() { /* ARRANGE */ final var desc = new ArtifactResponseMessageDesc(); desc.setRecipient(URI.create("https://recipient")); desc.setCorrelationMessage(URI.create("https://correlationMessage")); desc.setTransferContract(URI.create("https://transferContract")); final var connectorId = URI.create("https://connector"); final var modelVersion = "4.0.0"; final var token = new DynamicAttributeTokenBuilder() ._tokenFormat_(TokenFormat.OTHER)._tokenValue_("").build(); Mockito.when(connectorService.getConnectorId()).thenReturn(connectorId); Mockito.when(connectorService.getOutboundModelVersion()).thenReturn(modelVersion); Mockito.when(connectorService.getCurrentDat()).thenReturn(token); /* ACT */ final var result = (ArtifactResponseMessage) responseService.buildMessage(desc); /* ASSERT */ assertEquals(1, result.getRecipientConnector().size()); assertEquals(desc.getRecipient(), result.getRecipientConnector().get(0)); assertEquals(desc.getCorrelationMessage(), result.getCorrelationMessage()); assertEquals(desc.getTransferContract(), result.getTransferContract()); assertEquals(connectorId, result.getIssuerConnector()); assertEquals(modelVersion, result.getModelVersion()); assertEquals(token, result.getSecurityToken()); } }
package org.apache.spark.ui.jobs; // no position class TaskTableRowOutputData$ extends scala.runtime.AbstractFunction2<java.lang.Object, java.lang.String, org.apache.spark.ui.jobs.TaskTableRowOutputData> implements scala.Serializable { /** * Static reference to the singleton instance of this Scala object. */ public static final TaskTableRowOutputData$ MODULE$ = null; public TaskTableRowOutputData$ () { throw new RuntimeException(); } }
package module452packageJava0; import java.lang.Integer; public class Foo52 { Integer int0; public void foo0() { new module452packageJava0.Foo51().foo4(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } }
package com.ilusons.harmony.ref.permissions; /** * Enum class to handle the different states * of permissions since the PackageManager only * has a granted and denied state. */ enum Permissions { GRANTED, DENIED, NOT_FOUND }
package com.macro.mall.dao; import com.macro.mall.model.CmsSubjectProductRelation; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * 自定义商品和专题关系操作Dao * /4/26. */ @Repository public interface CmsSubjectProductRelationDao { /** * 批量创建 */ int insertList(@Param("list") List<CmsSubjectProductRelation> subjectProductRelationList); }
package com.jynx.pro.request; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.math.BigInteger; @EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) public class UpdateStakeRequest extends SignedRequest { private BigInteger amount; private String targetKey; private Long blockNumber; private String txHash; }
/* * Copyright (C) 2012 TopCoder Inc., All Rights Reserved. */ package gov.medicaid.screening.services.impl; import gov.medicaid.entities.ChildrensResidentialSearchCriteria; import gov.medicaid.entities.ProviderProfile; import gov.medicaid.entities.SearchResult; import gov.medicaid.screening.dao.ChildrensResidentialDAO; import gov.medicaid.screening.services.ChildrensResidentialService; import gov.medicaid.screening.services.ConfigurationException; import gov.medicaid.screening.services.ParsingException; import gov.medicaid.screening.services.ServiceException; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; /** * This class provides an EJB implementation of the ChildrensResidentialService interface. It * is a stateless, remote web service bean. * * <p> * <strong>Thread Safety:</strong> This bean is mutable and not thread-safe as it deals with non-thread-safe * entities. However, in the context of being used in a container, it is thread-safe. * </p> * * @author argolite, TCSASSEMBLER * @version 1.0 * @since Organizational Provider Screening External Datasources Services 2 */ @Stateless @Remote(ChildrensResidentialService.class) @TransactionManagement(TransactionManagementType.CONTAINER) public class ChildrensResidentialServiceBean extends BaseService implements ChildrensResidentialService { /** * Represent the name of this class */ private static final String CLASS_NAME = ChildrensResidentialServiceBean.class.getName(); /** * Represents the DAO that will back this service. It may have any value. It is fully mutable, but not * expected to change after dependency injection. */ @EJB private ChildrensResidentialDAO childrensResidentialDAO; /** * Empty constructor */ public ChildrensResidentialServiceBean() { } /** * Checks if the container properly initialized the injected fields. * * @throws ConfigurationException * if any injected field is null */ @PostConstruct protected void init() { super.init(); if (childrensResidentialDAO == null) { throw new ConfigurationException("The childrensResidentialDAO must be configured."); } } /** * This method gets the applicable providers that meet the search criteria. If none available, the search * result will be empty. * * @param criteria * the search criteria * @return the search result with the matched providers * @throws IllegalArgumentException * if the criteria is null * @throws IllegalArgumentException * if criteria.pageNumber < 0 * @throws IllegalArgumentException * - if criteria.pageSize < 1 unless criteria.pageNumber <= 0 * @throws ParsingException * if any parsing errors are encountered * @throws ServiceException * for any other exceptions encountered */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public SearchResult<ProviderProfile> search(ChildrensResidentialSearchCriteria criteria) throws ServiceException { String signature = CLASS_NAME + "#search(ChildrensResidentialSearchCriteria criteria)"; LogUtil.traceEntry(getLog(), signature, new String[] { "criteria" }, new Object[] { criteria }); try { SearchResult<ProviderProfile> results = childrensResidentialDAO.search(criteria); return LogUtil.traceExit(getLog(), signature, results); } catch (IllegalArgumentException e) { LogUtil.traceError(getLog(), signature, e); throw e; } catch (ServiceException e) { LogUtil.traceError(getLog(), signature, e); throw e; } } }
package com.ilm9001.nightclub.commands; import co.aikar.commands.BaseCommand; import co.aikar.commands.annotation.*; import com.ilm9001.nightclub.Nightclub; import com.ilm9001.nightclub.light.*; import com.ilm9001.nightclub.light.event.LightChannel; import com.ilm9001.nightclub.light.event.LightSpeedChannel; import com.ilm9001.nightclub.util.Location; import com.ilm9001.nightclub.util.Util; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.awt.*; import java.util.List; import java.util.*; import static com.ilm9001.nightclub.util.Util.formatErrors; @CommandAlias("light|li") @CommandPermission("nightclub.light") public class LightCommand extends BaseCommand { private static Light light; private static List<CommandError> isUnloaded() { List<CommandError> errors = new ArrayList<>(); errors.add(light == null ? CommandError.LIGHT_UNLOADED : CommandError.VALID); errors.add(Nightclub.getLightUniverseManager().getLoadedUniverse() == null ? CommandError.LIGHTUNIVERSE_UNLOADED : CommandError.VALID); errors.add(BeatmapCommand.getPlayer() != null && BeatmapCommand.getPlayer().isPlaying() ? CommandError.BEATMAP_PLAYING : CommandError.VALID); return errors; } private static List<CommandError> isUnloaded(String[] args, int minArgsLength) { List<CommandError> errors = isUnloaded(); errors.add(args.length < minArgsLength ? CommandError.TOO_LITTLE_ARGUMENTS : CommandError.VALID); return errors; } @Subcommand("build") @CommandAlias("b") @Description("Build a new Light!") @CommandPermission("nightclub.light") public static void onBuild(Player player, CommandSender sender) { LightUniverseManager manager = Nightclub.getLightUniverseManager(); List<CommandError> errors = isUnloaded(); errors.add(player == null ? CommandError.COMMAND_SENT_FROM_CONSOLE : CommandError.VALID); if (errors.stream().anyMatch(error -> error != CommandError.VALID && error != CommandError.LIGHT_UNLOADED)) { sender.sendMessage(formatErrors(errors)); return; } LightData data = LightData.builder() .patternData(new LightPatternData(LightPattern.LINE, 0.3, 5, 0)) .secondPatternData(new LightPatternData(LightPattern.LINE, 0.2, 3, 0)) .maxLength(15) .onLength(80) .timeToFadeToBlack(45) .lightCount(4) .flipStartAndEnd(player.getLocation().getPitch() > -10).build(); light = Light.builder() .uuid(UUID.randomUUID()) .name("Unnamed-Light-" + new Random().nextInt()) .location(Location.getFromBukkitLocation(player.getLocation().add(0, 1, 0))) .type(LightType.GUARDIAN_BEAM) .channel(LightChannel.CENTER_LIGHTS) .speedChannel(LightSpeedChannel.RIGHT_ROTATING_LASERS) .data(data).build(); light.start(); light.on(new Color(0x0066ff)); manager.getLoadedUniverse().addLight(light); manager.save(); } @Subcommand("remove") @CommandAlias("r") @Description("Remove currently loaded Light") @CommandPermission("nightclub.light") public static void onRemove(CommandSender sender) { LightUniverseManager manager = Nightclub.getLightUniverseManager(); if (isUnloaded().stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded())); return; } light.unload(); manager.getLoadedUniverse().removeLight(light); manager.save(); light = null; } @Subcommand("load") @CommandAlias("l") @Description("Load a Light from currently loaded LightUniverse") @CommandCompletion("@lights") @CommandPermission("nightclub.light") public static void onLoad(CommandSender sender, String[] args) { LightUniverseManager manager = Nightclub.getLightUniverseManager(); LightUniverse universe = manager.getLoadedUniverse(); List<CommandError> errors = isUnloaded(); errors.add(args.length < 1 ? CommandError.TOO_LITTLE_ARGUMENTS : CommandError.VALID); if (errors.stream().noneMatch(error -> error == CommandError.LIGHTUNIVERSE_UNLOADED)) { errors.add(universe.getLight(args[0]) == null ? CommandError.INVALID_ARGUMENT : CommandError.VALID); } if (errors.stream().anyMatch(error -> error != CommandError.VALID && error != CommandError.LIGHT_UNLOADED)) { sender.sendMessage(formatErrors(errors)); return; } light = universe.getLight(args[0]); light.start(); light.on(new Color(0x0066ff)); } @Subcommand("data") @CommandAlias("d") @Description("Modify a Light's data") @CommandPermission("nightclub.light") public class LightDataCommand extends BaseCommand { @Subcommand("name") @CommandAlias("n") @Description("Alter Light Name") @CommandPermission("nightclub.light") public static void onNameChange(CommandSender sender, String[] args) { List<CommandError> errors = isUnloaded(args, 1); errors.add(Nightclub.getLightUniverseManager().getLoadedUniverse().getLights().stream().anyMatch(l -> Objects.equals(l.getName(), args[0])) ? CommandError.NAME_ALREADY_EXISTS : CommandError.VALID); if (errors.stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(errors)); return; } light.setName(args[0]); } @Subcommand("pattern") @CommandAlias("p") @Description("Alter pattern") @CommandCompletion("@pattern") @CommandPermission("nightclub.light") public static void onPattern(CommandSender sender, String[] args) { List<CommandError> errors = isUnloaded(args, 1); try { LightPattern.valueOf(args[0]); } catch (IllegalArgumentException e) { errors.add(CommandError.INVALID_ARGUMENT); } if (errors.stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(errors)); return; } light.getData().getPatternData().setPattern(LightPattern.valueOf(args[0])); light.on(new Color(0x0066ff)); } @Subcommand("secondarypattern") @CommandAlias("sp") @Description("Alter secondary pattern") @CommandCompletion("@pattern") @CommandPermission("nightclub.light") public static void onSecondPattern(CommandSender sender, String[] args) { List<CommandError> errors = isUnloaded(args, 1); try { LightPattern.valueOf(args[0]); } catch (IllegalArgumentException e) { errors.add(CommandError.INVALID_ARGUMENT); } if (errors.stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(errors)); return; } light.getData().getPatternData().setPattern(LightPattern.valueOf(args[0])); light.on(new Color(0x0066ff)); } @Subcommand("maxlength") @CommandAlias("ml") @Description("Alter max length multiplier") @CommandPermission("nightclub.light") public static void onMaxLength(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.getData().setMaxLength(Util.parseNumber(args[0]).doubleValue()); light.on(new Color(0x0066ff)); } @Subcommand("onlength") @CommandAlias("ol") @Description("Alter the on length percentage") @CommandPermission("nightclub.light") public static void onModifyOnLength(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.getData().setOnLength(Util.parseNumber(args[0]).doubleValue()); light.on(new Color(0x0066ff)); } @Subcommand("patternmultiplier") @CommandAlias("pm") @Description("Alter the pattern size multiplier") @CommandPermission("nightclub.light") public static void onModifyPatternMultiplier(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.getData().getPatternData().setPatternSizeMultiplier(Util.parseNumber(args[0]).doubleValue()); light.on(new Color(0x0066ff)); } @Subcommand("secondarypatternmultiplier") @CommandAlias("spm") @Description("Alter the secondary pattern size multiplier") @CommandPermission("nightclub.light") public static void onModifySecondaryPatternMultiplier(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.getData().getSecondPatternData().setPatternSizeMultiplier(Util.parseNumber(args[0]).doubleValue()); light.on(new Color(0x0066ff)); } @Subcommand("speed") @CommandAlias("s") @Description("Alter speed") @CommandPermission("nightclub.light") public static void onModifySpeed(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.setBaseSpeed(Util.parseNumber(args[0]).doubleValue()); } @Subcommand("secondaryspeed") @CommandAlias("ss") @Description("Alter secondary speed") @CommandPermission("nightclub.light") public static void onModifySecondarySpeed(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.setSecondaryBaseSpeed(Util.parseNumber(args[0]).doubleValue()); } @Subcommand("lightcount") @CommandAlias("lc") @Description("Alter the amount of lights") @CommandPermission("nightclub.light") public static void onModifyLightCount(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.getData().setLightCount(Util.parseNumber(args[0]).intValue()); light.buildLasers(); light.on(new Color(0x0066ff)); } @Subcommand("type") @CommandAlias("t") @Description("Alter the Light's type") @CommandCompletion("@type") @CommandPermission("nightclub.light") public static void onModifyType(CommandSender sender, String[] args) { List<CommandError> errors = isUnloaded(args, 1); try { LightType.valueOf(args[0]); } catch (IllegalArgumentException e) { errors.add(CommandError.INVALID_ARGUMENT); } if (errors.stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(errors)); return; } light.setType(LightType.valueOf(args[0])); light.on(new Color(0x0066ff)); light.buildLasers(); } @Subcommand("rotation") @CommandAlias("r") @Description("Alter rotation") @CommandPermission("nightclub.light") public static void onModifyRotation(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.getData().getPatternData().setRotation(Math.toRadians(Util.parseNumber(args[0]).doubleValue())); light.buildLasers(); light.on(new Color(0x0066ff)); } @Subcommand("secondaryrotation") @CommandAlias("sr") @Description("Alter secondary rotation") @CommandPermission("nightclub.light") public static void onModifySecondaryRotation(CommandSender sender, String[] args) { if (isUnloaded(args, 1).stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded(args, 1))); return; } light.getData().getSecondPatternData().setRotation(Math.toRadians(Util.parseNumber(args[0]).doubleValue())); light.buildLasers(); light.on(new Color(0x0066ff)); } @Subcommand("channel") @CommandAlias("c") @Description("Change a Light's channel") @CommandCompletion("@channels") @CommandPermission("nightclub.light") public static void onModifyChannel(CommandSender sender, String[] args) { List<CommandError> errors = isUnloaded(args, 1); try { LightChannel.valueOf(args[0]); } catch (IllegalArgumentException e) { errors.add(CommandError.INVALID_ARGUMENT); } if (errors.stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(errors)); return; } light.setChannel(LightChannel.valueOf(args[0])); } @Subcommand("speedchannel") @CommandAlias("sc") @Description("Change a Light's speed channel") @CommandCompletion("@speedchannels") @CommandPermission("nightclub.light") public static void onModifySpeedChannel(CommandSender sender, String[] args) { List<CommandError> errors = isUnloaded(args, 1); try { LightSpeedChannel.valueOf(args[0]); } catch (IllegalArgumentException e) { errors.add(CommandError.INVALID_ARGUMENT); } if (errors.stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(errors)); return; } light.setSpeedChannel(LightSpeedChannel.valueOf(args[0])); } @Subcommand("setlocation") @CommandAlias("sl") @Description("Set the lights location to your location, including pitch and yaw") @CommandPermission("nightclub.light") public static void onSetLocation(CommandSender sender, Player player, String[] args) { List<CommandError> errors = isUnloaded(); errors.add(player == null ? CommandError.COMMAND_SENT_FROM_CONSOLE : CommandError.VALID); errors.add(args.length > 1 && args.length < 5 ? CommandError.TOO_LITTLE_ARGUMENTS : CommandError.VALID); if (errors.stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(errors)); return; } if (args.length >= 5) { light.setLocation(new Location(Util.parseNumber(args[0]), Util.parseNumber(args[1]), Util.parseNumber(args[2]), // x y z Util.parseNumber(args[3]), Util.parseNumber(args[4]))); // pitch and yaw } else { light.setLocation(Location.getFromBukkitLocation(player.getLocation().add(0, 1, 0))); } light.buildLasers(); light.on(new Color(0x000000)); } @Subcommand("flip") @CommandAlias("fl") @Description("Flip start and end locations of light") @CommandPermission("nightclub.light") public static void onFlip(CommandSender sender, String[] args) { if (isUnloaded().stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded())); return; } light.getData().setFlipStartAndEnd(!light.getData().isFlipStartAndEnd()); light.buildLasers(); light.on(new Color(0x000000)); } } @Subcommand("control") @CommandAlias("c") @Description("Control a light, for example, turn it on or off") @CommandPermission("nightclub.light") public class LightControlCommand extends BaseCommand { @Subcommand("on") @Description("Turn light on") @CommandPermission("nightclub.light") public static void onTurnOn(CommandSender sender) { if (isUnloaded().stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded())); return; } light.on(new Color(0x0066ff)); } @Subcommand("off") @Description("Turn light off") @CommandPermission("nightclub.light") public static void onTurnOff(CommandSender sender) { if (isUnloaded().stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded())); return; } light.off(new Color(0x000000)); } @Subcommand("flash") @Description("Flash light") @CommandPermission("nightclub.light") public static void onFlash(CommandSender sender) { if (isUnloaded().stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded())); return; } light.flash(new Color(0x0066ff)); } @Subcommand("flashoff") @Description("Flash off light") @CommandPermission("nightclub.light") public static void onFlashOff(CommandSender sender) { if (isUnloaded().stream().anyMatch(error -> error != CommandError.VALID)) { sender.sendMessage(formatErrors(isUnloaded())); return; } light.flashOff(new Color(0x0066ff)); } } }
package com.example.music_player; import androidx.appcompat.app.AppCompatActivity; import com.example.music_player.MusicService.IsPlayingListener; import static com.example.music_player.Classes.Singleton.getPlayInstance; public abstract class BaseActivity extends AppCompatActivity { abstract IsPlayingListener getIsPlayingListener(); @Override protected void onResume() { getPlayInstance().getMusicValues().mediaPlayer.setIsPlayingListener(getIsPlayingListener()); super.onResume(); } @Override protected void onPause() { getPlayInstance().getMusicValues().mediaPlayer.setIsPlayingListener(null); super.onPause(); } }
package com.google.api.ads.adwords.jaxws.v201402.express; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.google.api.ads.adwords.jaxws.v201402.cm.Selector; /** * * Retrieves the promotions that meet the criteria set in the given selector. * @param selector the selector specifying the AdWords Express promotion to return * @return list of AdWords Express promotion identified by the selector * * * <p>Java class for get element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="get"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="selector" type="{https://adwords.google.com/api/adwords/cm/v201402}Selector" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "selector" }) @XmlRootElement(name = "get") public class PromotionServiceInterfaceget { protected Selector selector; /** * Gets the value of the selector property. * * @return * possible object is * {@link Selector } * */ public Selector getSelector() { return selector; } /** * Sets the value of the selector property. * * @param value * allowed object is * {@link Selector } * */ public void setSelector(Selector value) { this.selector = value; } }
package com.sigmundgranaas.forgero.core.toolpart.toolpart; import com.sigmundgranaas.forgero.Constants; import com.sigmundgranaas.forgero.core.ForgeroRegistry; import com.sigmundgranaas.forgero.core.gem.EmptyGem; import com.sigmundgranaas.forgero.core.identifier.tool.ForgeroMaterialIdentifierImpl; import com.sigmundgranaas.forgero.core.material.material.EmptySecondaryMaterial; import com.sigmundgranaas.forgero.core.material.material.PrimaryMaterial; import com.sigmundgranaas.forgero.core.toolpart.ForgeroToolPart; import com.sigmundgranaas.forgero.core.toolpart.handle.Handle; import com.sigmundgranaas.forgero.core.toolpart.handle.HandleState; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static com.sigmundgranaas.forgero.core.property.ToolPropertyTest.HANDLE_SCHEMATIC; public class HandleTest { public static Handle createDefaultToolPartHandle() { HandleState state = new HandleState((PrimaryMaterial) ForgeroRegistry.getInstance().materialCollection().getMaterial(new ForgeroMaterialIdentifierImpl(Constants.IRON_IDENTIFIER_STRING)), new EmptySecondaryMaterial(), EmptyGem.createEmptyGem(), HANDLE_SCHEMATIC.get()); return new Handle(state); } @Test void getToolPartName() { ForgeroToolPart referenceToolPart = createDefaultToolPartHandle(); Assertions.assertEquals("handle", referenceToolPart.getToolPartName()); } }
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.coin2playj.crypto; import org.coin2playj.core.ECKey; import org.coin2playj.core.Transaction; import org.coin2playj.core.VerificationException; import org.coin2playj.core.Transaction.SigHash; import com.google.common.base.Preconditions; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; /** * A TransactionSignature wraps an {@link org.coin2playj.core.ECKey.ECDSASignature} and adds methods for handling * the additional SIGHASH mode byte that is used. */ public class TransactionSignature extends ECKey.ECDSASignature { /** * A byte that controls which parts of a transaction are signed. This is exposed because signatures * parsed off the wire may have sighash flags that aren't "normal" serializations of the enum values. * Because Bitcoin Core works via bit testing, we must not lose the exact value when round-tripping * otherwise we'll fail to verify signature hashes. */ public final int sighashFlags; /** Constructs a signature with the given components and SIGHASH_ALL. */ public TransactionSignature(BigInteger r, BigInteger s) { this(r, s, Transaction.SigHash.ALL.value); } /** Constructs a signature with the given components and raw sighash flag bytes (needed for rule compatibility). */ public TransactionSignature(BigInteger r, BigInteger s, int sighashFlags) { super(r, s); this.sighashFlags = sighashFlags; } /** Constructs a transaction signature based on the ECDSA signature. */ public TransactionSignature(ECKey.ECDSASignature signature, Transaction.SigHash mode, boolean anyoneCanPay) { super(signature.r, signature.s); sighashFlags = calcSigHashValue(mode, anyoneCanPay); } /** * Returns a dummy invalid signature whose R/S values are set such that they will take up the same number of * encoded bytes as a real signature. This can be useful when you want to fill out a transaction to be of the * right size (e.g. for fee calculations) but don't have the requisite signing key yet and will fill out the * real signature later. */ public static TransactionSignature dummy() { BigInteger val = ECKey.HALF_CURVE_ORDER; return new TransactionSignature(val, val); } /** Calculates the byte used in the protocol to represent the combination of mode and anyoneCanPay. */ public static int calcSigHashValue(Transaction.SigHash mode, boolean anyoneCanPay) { Preconditions.checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated int sighashFlags = mode.value; if (anyoneCanPay) sighashFlags |= Transaction.SigHash.ANYONECANPAY.value; return sighashFlags; } /** * Returns true if the given signature is has canonical encoding, and will thus be accepted as standard by * Bitcoin Core. DER and the SIGHASH encoding allow for quite some flexibility in how the same structures * are encoded, and this can open up novel attacks in which a man in the middle takes a transaction and then * changes its signature such that the transaction hash is different but it's still valid. This can confuse wallets * and generally violates people's mental model of how Bitcoin should work, thus, non-canonical signatures are now * not relayed by default. */ public static boolean isEncodingCanonical(byte[] signature) { // See Bitcoin Core's IsCanonicalSignature, https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype> // Where R and S are not negative (their first byte has its highest bit not set), and not // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows, // in which case a single 0 byte is necessary and even required). if (signature.length < 9 || signature.length > 73) return false; int hashType = (signature[signature.length-1] & 0xff) & ~Transaction.SigHash.ANYONECANPAY.value; // mask the byte to prevent sign-extension hurting us if (hashType < Transaction.SigHash.ALL.value || hashType > Transaction.SigHash.SINGLE.value) return false; // "wrong type" "wrong length marker" if ((signature[0] & 0xff) != 0x30 || (signature[1] & 0xff) != signature.length-3) return false; int lenR = signature[3] & 0xff; if (5 + lenR >= signature.length || lenR == 0) return false; int lenS = signature[5+lenR] & 0xff; if (lenR + lenS + 7 != signature.length || lenS == 0) return false; // R value type mismatch R value negative if (signature[4-2] != 0x02 || (signature[4] & 0x80) == 0x80) return false; if (lenR > 1 && signature[4] == 0x00 && (signature[4+1] & 0x80) != 0x80) return false; // R value excessively padded // S value type mismatch S value negative if (signature[6 + lenR - 2] != 0x02 || (signature[6 + lenR] & 0x80) == 0x80) return false; if (lenS > 1 && signature[6 + lenR] == 0x00 && (signature[6 + lenR + 1] & 0x80) != 0x80) return false; // S value excessively padded return true; } public boolean anyoneCanPay() { return (sighashFlags & Transaction.SigHash.ANYONECANPAY.value) != 0; } public Transaction.SigHash sigHashMode() { final int mode = sighashFlags & 0x1f; if (mode == Transaction.SigHash.NONE.value) return Transaction.SigHash.NONE; else if (mode == Transaction.SigHash.SINGLE.value) return Transaction.SigHash.SINGLE; else return Transaction.SigHash.ALL; } /** * What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream * of the type used by Bitcoin we have to encode them using DER encoding, which is just a way to pack the two * components into a structure, and then we append a byte to the end for the sighash flags. */ public byte[] encodeToBitcoin() { try { ByteArrayOutputStream bos = derByteStream(); bos.write(sighashFlags); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } @Override public ECKey.ECDSASignature toCanonicalised() { return new TransactionSignature(super.toCanonicalised(), sigHashMode(), anyoneCanPay()); } /** * Returns a decoded signature. * * @param requireCanonicalEncoding if the encoding of the signature must * be canonical. * @throws RuntimeException if the signature is invalid or unparseable in some way. * @deprecated use {@link #decodeFromBitcoin(byte[], boolean, boolean} instead}. */ @Deprecated public static TransactionSignature decodeFromBitcoin(byte[] bytes, boolean requireCanonicalEncoding) throws VerificationException { return decodeFromBitcoin(bytes, requireCanonicalEncoding, false); } /** * Returns a decoded signature. * * @param requireCanonicalEncoding if the encoding of the signature must * be canonical. * @param requireCanonicalSValue if the S-value must be canonical (below half * the order of the curve). * @throws RuntimeException if the signature is invalid or unparseable in some way. */ public static TransactionSignature decodeFromBitcoin(byte[] bytes, boolean requireCanonicalEncoding, boolean requireCanonicalSValue) throws VerificationException { // Bitcoin encoding is DER signature + sighash byte. if (requireCanonicalEncoding && !isEncodingCanonical(bytes)) throw new VerificationException("Signature encoding is not canonical."); ECKey.ECDSASignature sig; try { sig = ECKey.ECDSASignature.decodeFromDER(bytes); } catch (IllegalArgumentException e) { throw new VerificationException("Could not decode DER", e); } if (requireCanonicalSValue && !sig.isCanonical()) throw new VerificationException("S-value is not canonical."); // In Bitcoin, any value of the final byte is valid, but not necessarily canonical. See javadocs for // isEncodingCanonical to learn more about this. So we must store the exact byte found. return new TransactionSignature(sig.r, sig.s, bytes[bytes.length - 1]); } }
package org.innovateuk.ifs.application.forms.sections.yourprojectcosts.saver; import org.apache.commons.lang3.BooleanUtils; import org.innovateuk.ifs.application.forms.sections.yourprojectcosts.form.YourProjectCostsForm; import org.innovateuk.ifs.commons.exception.IFSRuntimeException; import org.innovateuk.ifs.finance.resource.ApplicationFinanceResource; import org.innovateuk.ifs.finance.resource.category.*; import org.innovateuk.ifs.finance.resource.cost.*; import org.innovateuk.ifs.finance.resource.cost.KtpTravelCost.KtpTravelCostType; import org.innovateuk.ifs.finance.service.ApplicationFinanceRestService; import org.innovateuk.ifs.finance.service.ApplicationFinanceRowRestService; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.OrganisationRestService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.Optional; import java.util.function.Supplier; import static java.lang.String.format; import static java.util.Collections.emptyList; import static org.innovateuk.ifs.application.forms.sections.yourprojectcosts.form.AbstractCostRowForm.UNSAVED_ROW_PREFIX; import static org.innovateuk.ifs.application.forms.sections.yourprojectcosts.saver.IndirectCostsUtil.INDIRECT_COST_PERCENTAGE; import static org.innovateuk.ifs.application.forms.sections.yourprojectcosts.saver.IndirectCostsUtil.calculateIndirectCost; @Component @SuppressWarnings("unchecked") public class YourProjectCostsAutosaver { private final static Logger LOG = LoggerFactory.getLogger(YourProjectCostsAutosaver.class); @Autowired private ApplicationFinanceRestService applicationFinanceRestService; @Autowired private OrganisationRestService organisationRestService; @Autowired private ApplicationFinanceRowRestService financeRowRestService; public Optional<Long> autoSave(String field, String value, long applicationId, UserResource user) { OrganisationResource organisation = organisationRestService.getByUserAndApplicationId(user.getId(), applicationId).getSuccess(); ApplicationFinanceResource finance = applicationFinanceRestService.getApplicationFinance(applicationId, organisation.getId()).getSuccess(); try { if (field.equals("labour.workingDaysPerYear")) { finance = applicationFinanceRestService.getFinanceDetails(applicationId, organisation.getId()).getSuccess(); LabourCostCategory category = (LabourCostCategory) finance.getFinanceOrganisationDetails().get(FinanceRowType.LABOUR); LabourCost workingDaysCost = category.getWorkingDaysPerYearCostItem(); workingDaysCost.setLabourDays(Integer.parseInt(value)); financeRowRestService.update(workingDaysCost).getSuccess(); } else if (field.startsWith("labour.rows")) { return autosaveLabourCost(field, value, finance); } else if (field.startsWith("overhead")) { return autosaveOverheadCost(field, value, finance, applicationId, organisation.getId()); } else if (field.startsWith("materialRows")) { return autosaveMaterialCost(field, value, finance); } else if (field.startsWith("capitalUsageRows")) { return autosaveCapitalUsageCost(field, value, finance); } else if (field.startsWith("subcontractingRows")) { return autosaveSubcontractingCost(field, value, finance); } else if (field.startsWith("travelRows")) { return autosaveTravelCost(field, value, finance); } else if (field.startsWith("otherRows")) { return autosaveOtherCost(field, value, finance); } else if (field.startsWith("associateSalaryCostRows")) { return autosaveAssociateSalaryCost(field, value, finance, applicationId, organisation.getId()); } else if (field.startsWith("associateDevelopmentCostRows")) { return autosaveAssociateDevelopmentCost(field, value, finance); } else if (field.startsWith("associateSupportCostRows")) { return autosaveAssociateSupportCost(field, value, finance); } else if (field.startsWith("consumableCostRows")) { return autosaveConsumableCost(field, value, finance); } else if (field.startsWith("knowledgeBaseCostRows")) { return autosaveKnowledgeBaseCost(field, value, finance); } else if (field.startsWith("additionalCompanyCostForm")) { return autosaveAdditionalCompanyCostForm(field, value, finance); } else if (field.startsWith("estateCostRows")) { return autosaveEstateCost(field, value, finance); } else if (field.startsWith("ktpTravelCostRows")) { return autosaveKtpTravelCostRows(field, value, finance); } else if (field.startsWith("procurementOverheadRows")) { return autosaveProcurementOverheadCost(field, value, finance); } else if (field.startsWith("vat")) { return autosaveVAT(value, finance, applicationId, organisation.getId()); } else if (field.startsWith("justificationForm.justification")) { return autosaveJustification(value, finance, applicationId, organisation.getId()); } else if (field.startsWith("academicAndSecretarialSupportForm.cost")) { return autosaveAcademicAndSecretarialSupportCostRows(field, value, finance, applicationId, organisation.getId()); } else { throw new IFSRuntimeException(format("Auto save field not handled %s", field), emptyList()); } } catch (Exception e) { LOG.debug("Error auto saving", e); LOG.info(format("Unable to auto save field (%s) value (%s)", field, value)); } return Optional.empty(); } private Optional<Long> autosaveAcademicAndSecretarialSupport(String field, String value, ApplicationFinanceResource financeResource) { AcademicAndSecretarialSupport academicAndSecretarialSupport = new AcademicAndSecretarialSupport(); academicAndSecretarialSupport.setCost(new BigInteger(value)); financeRowRestService.update(academicAndSecretarialSupport); return Optional.empty(); } private Optional<Long> autosaveJustification(String value, ApplicationFinanceResource finance, long applicationId, long organisationId) { finance = applicationFinanceRestService.getFinanceDetails(applicationId, organisationId).getSuccess(); if (value != null) { finance.setJustification(value); } applicationFinanceRestService.update(finance.getId(), finance); return Optional.empty(); } private Optional<Long> autosaveAdditionalCompanyCostForm(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); AdditionalCompanyCostCategory costCategory = (AdditionalCompanyCostCategory) finance.getFinanceOrganisationDetails().get(FinanceRowType.ADDITIONAL_COMPANY_COSTS); AdditionalCompanyCost toSave; switch (rowField) { case "associateSalary.cost": toSave = costCategory.getAssociateSalary(); toSave.setCost(new BigInteger(value)); break; case "associateSalary.description": toSave = costCategory.getAssociateSalary(); toSave.setDescription(value); break; case "managementSupervision.cost": toSave = costCategory.getManagementSupervision(); toSave.setCost(new BigInteger(value)); break; case "managementSupervision.description": toSave = costCategory.getManagementSupervision(); toSave.setDescription(value); break; case "otherStaff.cost": toSave = costCategory.getOtherStaff(); toSave.setCost(new BigInteger(value)); break; case "otherStaff.description": toSave = costCategory.getOtherStaff(); toSave.setDescription(value); break; case "capitalEquipment.cost": toSave = costCategory.getCapitalEquipment(); toSave.setCost(new BigInteger(value)); break; case "capitalEquipment.description": toSave = costCategory.getCapitalEquipment(); toSave.setDescription(value); break; case "consumables.cost": toSave = costCategory.getConsumables(); toSave.setCost(new BigInteger(value)); break; case "consumables.description": toSave = costCategory.getConsumables(); toSave.setDescription(value); break; case "otherCosts.cost": toSave = costCategory.getOtherCosts(); toSave.setCost(new BigInteger(value)); break; case "otherCosts.description": toSave = costCategory.getOtherCosts(); toSave.setDescription(value); break; default: throw new IFSRuntimeException(format("Auto save consumable field not handled %s", rowField), emptyList()); } financeRowRestService.update(toSave); return Optional.empty(); } private Optional<Long> autosaveKnowledgeBaseCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); KnowledgeBaseCost cost = getCost(id, () -> new KnowledgeBaseCost(finance.getId())); switch (rowField) { case "description": cost.setDescription(value); break; case "cost": cost.setCost(new BigInteger(value)); break; default: throw new IFSRuntimeException(format("Auto save consumable field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveConsumableCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); Consumable cost = getCost(id, () -> new Consumable(finance.getId())); switch (rowField) { case "item": cost.setItem(value); break; case "quantity": cost.setQuantity(Integer.parseInt(value)); break; case "cost": cost.setCost(new BigInteger(value)); break; default: throw new IFSRuntimeException(format("Auto save consumable field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveAssociateDevelopmentCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); AssociateDevelopmentCost cost = getCost(id, () -> new AssociateDevelopmentCost(finance.getId())); switch (rowField) { case "role": cost.setRole(value); break; case "duration": cost.setDuration(Integer.parseInt(value)); break; case "cost": cost.setCost(new BigInteger(value)); break; default: throw new IFSRuntimeException(format("Auto save associate development field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveLabourCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); LabourCost cost = getCost(id, () -> new LabourCost(finance.getId())); switch (rowField) { case "role": cost.setRole(value); break; case "gross": cost.setGrossEmployeeCost(new BigDecimal(value)); break; case "days": cost.setLabourDays(Integer.parseInt(value)); break; default: throw new IFSRuntimeException(format("Auto save labour field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveAssociateSalaryCost(String field, String value, ApplicationFinanceResource finance, long applicationId, Long organisationId) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); AssociateSalaryCost cost = getCost(id, () -> new AssociateSalaryCost(finance.getId())); switch (rowField) { case "role": cost.setRole(value); break; case "duration": cost.setDuration(Integer.parseInt(value)); break; case "cost": cost.setCost(new BigInteger(value)); break; default: throw new IFSRuntimeException(format("Auto save associate salary field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); autoSaveIndirectCost(finance, applicationId, organisationId); return Optional.of(cost.getId()); } private Optional<Long> autosaveAcademicAndSecretarialSupportCostRows(String field, String value, ApplicationFinanceResource finance, long applicationId, Long organisationId) { if (!finance.getFecModelEnabled()) { ApplicationFinanceResource organisationFinance = applicationFinanceRestService.getFinanceDetails(applicationId, organisationId).getSuccess(); DefaultCostCategory financeOrganisationDetails = (DefaultCostCategory) organisationFinance.getFinanceOrganisationDetails(FinanceRowType.ACADEMIC_AND_SECRETARIAL_SUPPORT); AcademicAndSecretarialSupport financeRowItem = (AcademicAndSecretarialSupport) financeOrganisationDetails.getCosts().stream() .filter(costRowItem -> costRowItem.getCostType() == FinanceRowType.ACADEMIC_AND_SECRETARIAL_SUPPORT) .findFirst() .orElseGet(() -> financeRowRestService.create(new AcademicAndSecretarialSupport(finance.getId())).getSuccess()); financeRowItem.setCost(new BigInteger(value)); financeRowRestService.update(financeRowItem); autoSaveIndirectCost(finance, applicationId, organisationId); return Optional.of(financeRowItem.getId()); } return Optional.empty(); } private void autoSaveIndirectCost(ApplicationFinanceResource finance, long applicationId, Long organisationId) { if (BooleanUtils.isFalse(finance.getFecModelEnabled())) { ApplicationFinanceResource organisationFinance = applicationFinanceRestService.getFinanceDetails(applicationId, organisationId).getSuccess(); DefaultCostCategory defaultCostCategory = (DefaultCostCategory) organisationFinance.getFinanceOrganisationDetails(FinanceRowType.INDIRECT_COSTS); IndirectCost indirectCost = (IndirectCost) defaultCostCategory.getCosts().stream() .filter(costRowItem -> costRowItem.getCostType() == FinanceRowType.INDIRECT_COSTS) .findFirst() .orElseGet(() -> financeRowRestService.create(new IndirectCost(finance.getId())).getSuccess()); BigDecimal calculateIndirectCost = calculateIndirectCost(organisationFinance); indirectCost.setCost(calculateIndirectCost.toBigIntegerExact()); financeRowRestService.update(indirectCost); } } private Optional<Long> autosaveAssociateSupportCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); AssociateSupportCost cost = getCost(id, () -> new AssociateSupportCost(finance.getId())); switch (rowField) { case "description": cost.setDescription(value); break; case "cost": cost.setCost(new BigInteger(value)); break; default: throw new IFSRuntimeException(format("Auto save associate support field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveKtpTravelCostRows(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); KtpTravelCost cost = getCost(id, () -> new KtpTravelCost(finance.getId())); switch (rowField) { case "type": cost.setType(KtpTravelCostType.valueOf(value)); break; case "description": cost.setDescription(value); break; case "times": cost.setQuantity(Integer.valueOf(value)); break; case "eachCost": cost.setCost(new BigDecimal(value)); break; default: throw new IFSRuntimeException(format("Auto save ktp travel field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveEstateCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); EstateCost cost = getCost(id, () -> new EstateCost(finance.getId())); switch (rowField) { case "description": cost.setDescription(value); break; case "cost": cost.setCost(new BigInteger(value)); break; default: throw new IFSRuntimeException(format("Auto save estate costs field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveOverheadCost(String field, String value, ApplicationFinanceResource finance, long applicationId, Long organisationId) { if (field.equals("overhead.totalSpreadsheet")) { finance = applicationFinanceRestService.getFinanceDetails(applicationId, organisationId).getSuccess(); OverheadCostCategory category = (OverheadCostCategory) finance.getFinanceOrganisationDetails().get(FinanceRowType.OVERHEADS); Overhead overheadCost = (Overhead) category.getCosts().get(0); overheadCost.setRate(Integer.valueOf(value)); financeRowRestService.update(overheadCost); } return Optional.empty(); } private Optional<Long> autosaveVAT(String value, ApplicationFinanceResource finance, long applicationId, Long organisationId) { finance = applicationFinanceRestService.getFinanceDetails(applicationId, organisationId).getSuccess(); VatCostCategory category = (VatCostCategory) finance.getFinanceOrganisationDetails().get(FinanceRowType.VAT); Vat vat = (Vat) category.getCosts().get(0); vat.setRegistered(Boolean.valueOf(value)); financeRowRestService.update(vat); return Optional.empty(); } private Optional<Long> autosaveMaterialCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); Materials cost = getCost(id, () -> new Materials(finance.getId())); switch (rowField) { case "item": cost.setItem(value); break; case "quantity": cost.setQuantity(Integer.parseInt(value)); break; case "cost": cost.setCost(new BigDecimal(value)); break; default: throw new IFSRuntimeException(format("Auto save material field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveProcurementOverheadCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); ProcurementOverhead cost = getCost(id, () -> new ProcurementOverhead(finance.getId())); switch (rowField) { case "item": cost.setItem(value); break; case "companyCost": cost.setCompanyCost(Integer.parseInt(value)); break; case "projectCost": cost.setProjectCost(new BigDecimal(value)); break; default: throw new IFSRuntimeException(format("Auto save procurement overhead field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveCapitalUsageCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); CapitalUsage cost = getCost(id, () -> new CapitalUsage(finance.getId())); switch (rowField) { case "item": cost.setDescription(value); break; case "newItem": cost.setExisting(Boolean.parseBoolean(value) ? "New" : "Existing"); break; case "deprecation": cost.setDeprecation(Integer.valueOf(value)); break; case "netValue": cost.setNpv(new BigDecimal(value)); break; case "residualValue": cost.setResidualValue(new BigDecimal(value)); break; case "utilisation": cost.setUtilisation(Integer.valueOf(value)); break; default: throw new IFSRuntimeException(format("Auto save capital usage field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveSubcontractingCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); SubContractingCost cost = getCost(id, () -> new SubContractingCost(finance.getId())); switch (rowField) { case "name": cost.setName(value); break; case "country": cost.setCountry(value); break; case "role": cost.setRole(value); break; case "cost": cost.setCost(new BigDecimal(value)); break; default: throw new IFSRuntimeException(format("Auto save sub-contracting field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveTravelCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); TravelCost cost = getCost(id, () -> new TravelCost(finance.getId())); switch (rowField) { case "item": cost.setItem(value); break; case "times": cost.setQuantity(Integer.valueOf(value)); break; case "eachCost": cost.setCost(new BigDecimal(value)); break; default: throw new IFSRuntimeException(format("Auto save travel field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private Optional<Long> autosaveOtherCost(String field, String value, ApplicationFinanceResource finance) { String id = idFromRowPath(field); String rowField = fieldFromRowPath(field); OtherCost cost = getCost(id, () -> new OtherCost(finance.getId())); switch (rowField) { case "description": cost.setDescription(value); break; case "estimate": cost.setCost(new BigDecimal(value)); break; default: throw new IFSRuntimeException(format("Auto save other cost field not handled %s", rowField), emptyList()); } financeRowRestService.update(cost); return Optional.of(cost.getId()); } private <R extends FinanceRowItem> R getCost(String id, Supplier<R> creator) { if (id.startsWith(UNSAVED_ROW_PREFIX)) { return (R) financeRowRestService.create(creator.get()).getSuccess(); } else { return (R) financeRowRestService.get(Long.valueOf(id)).getSuccess(); } } private String idFromRowPath(String field) { return field.substring(field.indexOf('[') + 1, field.indexOf(']')); } private String fieldFromRowPath(String field) { return field.substring(field.indexOf("].") + 2); } public void resetCostRowEntriesBasedOnFecModelUpdate(long applicationId, long organisationId) { financeRowRestService.resetCostRowEntriesBasedOnFecModelUpdate(applicationId, organisationId); } }
package com.hxtech.offer.service.misc; import java.io.IOException; import android.content.Context; import android.content.SharedPreferences; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; // Referenced classes of package com.rjfittime.app.service.misc: // PersistentJsonStore public class SharedPreferencesJsonStore implements PersistentJsonStore { private static final String TAG = SharedPreferencesJsonStore.class.getSimpleName(); private ObjectMapper mObjectMapper; private SharedPreferences mSharedPreferences; public SharedPreferencesJsonStore(Context context, ObjectMapper objectmapper, String s) { mSharedPreferences = context.getSharedPreferences(s, 0); mObjectMapper = objectmapper; } public SharedPreferencesJsonStore(Context context, String s) { this(context, new ObjectMapper(), s); } public String getRawText(String s) { return mSharedPreferences.getString(s, "null"); } public Object getValue(String s, TypeReference typereference) throws IOException { return mObjectMapper.readValue(getRawText(s), typereference); } public Object getValue(String s, Class class1) throws IOException { return mObjectMapper.readValue(getRawText(s), class1); } public void putRawText(String s, String s1) { mSharedPreferences.edit().putString(s, s1).apply(); } public void putValue(String s, Object obj) throws JsonProcessingException { putRawText(s, mObjectMapper.writeValueAsString(obj)); } }
package com.hy.pull.mapper; /** * 对应数据表tb_max_log的操作接口 * @author temdy */ public interface TbMaxLogMapper extends BaseMapper{ }
/* * Copyright (c) 2018, The University of Memphis, MD2K Center of Excellence * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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. */ package org.md2k.datakit.cerebralcortex; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.net.ConnectivityManager; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.md2k.datakit.configuration.Configuration; import org.md2k.datakit.configuration.ConfigurationManager; import org.md2k.datakit.logger.DatabaseLogger; import org.md2k.datakitapi.datatype.DataTypeLong; import org.md2k.datakitapi.datatype.RowObject; import org.md2k.datakitapi.source.datasource.DataSource; import org.md2k.datakitapi.source.datasource.DataSourceBuilder; import org.md2k.datakitapi.source.datasource.DataSourceClient; import org.md2k.datakitapi.time.DateTime; import org.md2k.mcerebrum.core.access.serverinfo.ServerCP; import org.md2k.mcerebrum.system.cerebralcortexwebapi.CCWebAPICalls; import org.md2k.mcerebrum.system.cerebralcortexwebapi.interfaces.CerebralCortexWebApi; import org.md2k.mcerebrum.system.cerebralcortexwebapi.metadata.MetadataBuilder; import org.md2k.mcerebrum.system.cerebralcortexwebapi.models.AuthResponse; import org.md2k.mcerebrum.system.cerebralcortexwebapi.models.stream.DataStream; import org.md2k.mcerebrum.system.cerebralcortexwebapi.utils.ApiUtils; import org.md2k.utilities.FileManager; import org.md2k.utilities.Report.Log; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.zip.GZIPOutputStream; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.functions.Func1; import static android.content.Context.CONNECTIVITY_SERVICE; import static java.util.UUID.randomUUID; /** * Provides a wrapper for <code>CerebralCortex</code> API calls. */ public class CerebralCortexWrapper extends Thread { /** * Constant used for logging. <p>Uses <code>class.getSimpleName()</code>.</p> */ private static final String TAG = CerebralCortexWrapper.class.getSimpleName(); /** * Directory for raw data. */ private static String raw_directory = ""; /** * Android context. */ private Context context; /** * List of restricted or ignored <code>DataSource</code>s. */ private List<DataSource> restricted; private String network_high_freq; /** * Network to use for low frequency uploads. */ private String network_low_freq; /** * Subscription for observing file pruning. */ private Subscription subsPrune; /** * Constructor * <p> * <p> * Sets up the uploader and introduces a list of data sources to not be uploaded. * </p> * * @throws IOException */ public CerebralCortexWrapper(Context context, List<DataSource> restricted) throws IOException { Configuration configuration = ConfigurationManager.read(context); this.context = context; this.restricted = restricted; this.network_high_freq = configuration.upload.network_high_frequency; this.network_low_freq = configuration.upload.network_low_frequency; raw_directory = FileManager.getDirectory(context, FileManager.INTERNAL_SDCARD_PREFERRED) + org.md2k.datakit.Constants.RAW_DIRECTORY; } /** * Sends broadcast messages containing the given message and an extra name, <code>"CC_Upload"</code>. * * @param message Message to put into the broadcast. */ private void messenger(String message) { Intent intent = new Intent(Constants.CEREBRAL_CORTEX_STATUS); Time t = new Time(System.currentTimeMillis()); String msg = t.toString() + ": " + message; intent.putExtra("CC_Upload", msg); Log.d("CerebralCortexMessenger", msg); LocalBroadcastManager.getInstance(this.context).sendBroadcast(intent); } /** * Main upload method for an individual <code>DataStream</code>. * <p> * <p> * This method is responsible for offloading all unsynced data from low-frequency sources. * The data is offloaded to an SQLite database. * </p> * * @param dsc <code>DataSourceClient</code> to upload. * @param ccWebAPICalls <code>CerebralCortex</code> Web API Calls. * @param ar Authorization response. * @param dsMetadata Metadata for the data stream. * @param dbLogger Database logger */ private void publishDataStream(DataSourceClient dsc, CCWebAPICalls ccWebAPICalls, AuthResponse ar, DataStream dsMetadata, DatabaseLogger dbLogger) { Log.d("abc", "upload start... id=" + dsc.getDs_id() + " source=" + dsc.getDataSource().getType()); boolean cont = true; int BLOCK_SIZE_LIMIT = Constants.DATA_BLOCK_SIZE_LIMIT; long count = 0; while (cont) { cont = false; //Computed Data Store List<RowObject> objects; objects = dbLogger.queryLastKey(dsc.getDs_id(), Constants.DATA_BLOCK_SIZE_LIMIT); count = dbLogger.queryCount(dsc.getDs_id(), true).getSample(); if (objects.size() > 0) { String outputTempFile = FileManager.getDirectory(context, FileManager.INTERNAL_SDCARD_PREFERRED) + randomUUID().toString() + ".gz"; File outputfile = new File(outputTempFile); try { FileOutputStream output = new FileOutputStream(outputfile, false); Writer writer = new OutputStreamWriter(new GZIPOutputStream(output), "UTF-8"); for (RowObject obj : objects) { writer.write(obj.csvString() + "\n"); } writer.close(); output.close(); } catch (IOException e) { Log.e("CerebralCortex", "Compressed file creation failed" + e); e.printStackTrace(); return; } messenger("Offloading data: " + dsc.getDs_id() + "(Remaining: " + count + ")"); Boolean resultUpload = ccWebAPICalls.putArchiveDataAndMetadata(ar.getAccessToken().toString(), dsMetadata, outputTempFile); if (resultUpload) { try { dbLogger.setSyncedBit(dsc.getDs_id(), objects.get(objects.size() - 1).rowKey); } catch (Exception ignored) { Log.e(TAG, "Error uploading file: " + outputTempFile + " for SQLite database dump"); return; } // delete the temporary file here outputfile.delete(); } else { Log.e(TAG, "Error uploading file: " + outputTempFile + " for SQLite database dump"); return; } } if (objects.size() == BLOCK_SIZE_LIMIT) { cont = true; } } Log.d(TAG, "upload done... prune... id=" + dsc.getDs_id() + " source=" + dsc.getDataSource().getType()); } /** * Frees space on the device by removing any raw data files that have already been synced to the cloud. * * @param prunes ArrayList of data source identifiers to delete. */ private void deleteArchiveFile(final ArrayList<Integer> prunes) { final int[] current = new int[1]; if (prunes == null || prunes.size() == 0) return; current[0] = 0; if (subsPrune != null && !subsPrune.isUnsubscribed()) subsPrune.unsubscribe(); subsPrune = Observable.range(1, 1000000).takeUntil(new Func1<Integer, Boolean>() { /** * Deletes the files in the directory when called. * * @param aLong Needed for proper override. * @return Whether the deletion was completed or not. */ @Override public Boolean call(Integer aLong) { Log.d("abc", "current=" + current[0] + " size=" + prunes.size()); if (current[0] >= prunes.size()) return true; File directory = new File(raw_directory + "/raw" + current[0]); FilenameFilter ff = new FilenameFilter() { /** * Method checks if the file is marked archive or corrupt. * * @param dir Directory the file is in. * @param filename File to check. * @return Whether the file is acceptable or not. */ @Override public boolean accept(File dir, String filename) { if (filename.contains("_archive") || filename.contains("_corrupt")) return true; return false; } }; File[] files = directory.listFiles(ff); for (int i = 0; files != null && i < files.length; i++) { files[i].delete(); } current[0]++; return false; } }).subscribe(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer aLong) { } }); } /** * Main upload method for an individual raw <code>DataStream</code>. * <p> * <p> * This method is responsible for offloading all unsynced data from high-frequency sources. * </p> * * @param dsc <code>DataSourceClient</code> * @param ccWebAPICalls * @param ar * @param dsMetadata Metadata for the given data stream. */ private void publishDataFiles(DataSourceClient dsc, CCWebAPICalls ccWebAPICalls, AuthResponse ar, DataStream dsMetadata) { File directory = new File(raw_directory + "/raw" + dsc.getDs_id()); FilenameFilter ff = new FilenameFilter() { /** * Method checks if the file is marked archive or corrupt and if so, rejects them. * * @param dir Directory the file is in. * @param filename File to check. * @return Whether the file is acceptable or not. */ @Override public boolean accept(File dir, String filename) { if (filename.contains("_archive") || filename.contains("_corrupt")) return false; return true; } }; File[] files = directory.listFiles(ff); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH"); if (files != null) { Arrays.sort(files); for (File file : files) { Long fileTimestamp = Long.valueOf(file.getName().substring(0, 10)); Long currentTimestamp = Long.valueOf(dateFormat.format(new Date())); if (fileTimestamp < currentTimestamp) { Log.d(TAG, file.getAbsolutePath()); Boolean resultUpload = ccWebAPICalls.putArchiveDataAndMetadata(ar.getAccessToken() .toString(), dsMetadata, file.getAbsolutePath()); if (resultUpload) { File newFile = new File(file.getAbsolutePath()); newFile.delete(); } else { Log.e(TAG, "Error uploading file: " + file.getName()); return; } } } } } /** * Checks if the given data source is in the restricted list. * * @param dsc <code>DataSourceClient</code> to search for. * @return Whether the given data source is the restricted list. */ private boolean inRestrictedList(DataSourceClient dsc) { for (DataSource d : restricted) { if (dsc.getDataSource().getType().equals(d.getType())) { return true; } } return false; } /** * Executes the upload routine. * <p> * <p> * The upload routine is as follows: * <ul> * <li>First, the user is authenticated.</li> * <li>Then, for each data source:</li> * <ul> * <li>data source is checked for restriction.</li> * <li>low frequency network connection type is checked for validity.</li> * <li>low frequency data is published to the server.</li> * <li>high frequency network connection type is checked for validity.</li> * <li>high frequency data is published to the server.</li> * </ul> * <li>After all data sources have been published, the synced data is removed from the database.</li> * <li>And finally, the raw files are deleted.</li> * </ul> * </p> */ public void run() { if (ServerCP.getServerAddress(context) == null) return; Log.w("CerebralCortex", "Starting publishdataKitData"); DatabaseLogger dbLogger = null; if (!DatabaseLogger.isAlive()) { Log.w(TAG, "Database is not initialized yet...quitting"); return; } try { dbLogger = DatabaseLogger.getInstance(context); if (dbLogger == null) return; } catch (IOException e) { return; } messenger("Starting publish procedure"); String username = ServerCP.getUserName(context); String passwordHash = ServerCP.getPasswordHash(context); String token = ServerCP.getToken(context); String serverURL = ServerCP.getServerAddress(context); if (serverURL == null || serverURL.length() == 0 || username == null || username.length() == 0 || passwordHash == null || passwordHash.length() == 0) { messenger("username/password/server address empty"); return; } CerebralCortexWebApi ccService = ApiUtils.getCCService(serverURL); CCWebAPICalls ccWebAPICalls = new CCWebAPICalls(ccService); // Authenticate the user. AuthResponse ar = ccWebAPICalls.authenticateUser(username, passwordHash); if (ar != null) { messenger("Authenticated with server"); } else { messenger("Authentication Failed"); return; } try { DataSourceBuilder dataSourceBuilder = new DataSourceBuilder(); List<DataSourceClient> dataSourceClients = dbLogger.find(dataSourceBuilder.build()); ArrayList<Integer> prune = new ArrayList<>(); ArrayList<Integer> pruneFiles = new ArrayList<>(); for (DataSourceClient dsc : dataSourceClients) { if (!inRestrictedList(dsc)) { MetadataBuilder metadataBuilder = new MetadataBuilder(); DataStream dsMetadata = metadataBuilder.buildDataStreamMetadata(ar.getUserUuid(), dsc); if (isNetworkConnectionValid(network_low_freq)) { Log.d("abc", "trying to upload from database id=" + dsc.getDs_id()); messenger("Publishing data for " + dsc.getDs_id() + " (" + dsc.getDataSource().getId() + ":" + dsc.getDataSource().getType() + ") to " + dsMetadata.getIdentifier()); publishDataStream(dsc, ccWebAPICalls, ar, dsMetadata, dbLogger); prune.add(dsc.getDs_id()); } if (isNetworkConnectionValid(network_high_freq)) { Log.d("abc", "trying to upload from file id=" + dsc.getDs_id()); messenger("Publishing raw data for " + dsc.getDs_id() + " (" + dsc.getDataSource().getId() + ":" + dsc.getDataSource().getType() + ") to " + dsMetadata.getIdentifier()); pruneFiles.add(dsc.getDs_id()); publishDataFiles(dsc, ccWebAPICalls, ar, dsMetadata); } } } dbLogger.pruneSyncData(prune); deleteArchiveFile(pruneFiles); // dbLogger.pruneSyncData(dsc.getDs_id()); messenger("Upload Complete"); } catch (Exception e) { } } /** * Check network connectivity. * * @param value Type of network connection. * @return Whether the network connection is working. */ private boolean isNetworkConnectionValid(String value) { if (value == null || value.equalsIgnoreCase("ANY")) return true; if (value.equalsIgnoreCase("NONE")) return false; ConnectivityManager manager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); if (value.equalsIgnoreCase("WIFI")) { return manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); } return manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.config.model.v20200907; import com.aliyuncs.AcsResponse; import com.aliyuncs.config.transform.v20200907.GenerateConfigRulesReportResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class GenerateConfigRulesReportResponse extends AcsResponse { private String requestId; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public GenerateConfigRulesReportResponse getInstance(UnmarshallerContext context) { return GenerateConfigRulesReportResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
package com.neverpile.eureka.plugin.audit.service; import java.time.Instant; /** * This interfaces defines functions to create and validate such Audit IDs. The Id will be generated using using the * Document ID in combination with a given hig precision timestamp. the timestamp will bes used to distinguish audit * events within a single document and to generate the corresponding Block ID. */ public interface TimeBasedAuditIdGenerationStrategy extends AuditIdGenerationStrategy { /** * Creates a new AuditId for a given Document. This id is unique among all other Audit IDs. * * @param timestamp the creation Time of the AuditEvent. * @param documentId the Document ID to generate an new Audit ID for. * @return the newly generated Audit ID. */ public String createAuditId(Instant timestamp, String documentId); }
package net.jackw.authenticator; public interface ErrorCallback<T> { public void onError(T param); }
package com.yisu.shardingsphere; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @description 启动类 * @author xuyisu * @date '2020-03-22' */ @SpringBootApplication public class FwShardingsphereSubDbDruid { public static void main(String[] args) { SpringApplication.run(FwShardingsphereSubDbDruid.class, args); } }
/* * Copyright 2016-2019 Netflix, 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.netflix.hollow.core.type.delegate; import com.netflix.hollow.api.custom.HollowTypeAPI; import com.netflix.hollow.api.objects.delegate.HollowCachedDelegate; import com.netflix.hollow.api.objects.delegate.HollowObjectAbstractDelegate; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.type.IntegerTypeAPI; public class IntegerDelegateCachedImpl extends HollowObjectAbstractDelegate implements HollowCachedDelegate, IntegerDelegate { private final Integer value; private IntegerTypeAPI typeAPI; public IntegerDelegateCachedImpl(IntegerTypeAPI typeAPI, int ordinal) { this.value = typeAPI.getValueBoxed(ordinal); this.typeAPI = typeAPI; } @Override public int getValue(int ordinal) { if(value == null) return Integer.MIN_VALUE; return value.intValue(); } @Override public Integer getValueBoxed(int ordinal) { return value; } @Override public HollowObjectSchema getSchema() { return typeAPI.getTypeDataAccess().getSchema(); } @Override public HollowObjectTypeDataAccess getTypeDataAccess() { return typeAPI.getTypeDataAccess(); } @Override public IntegerTypeAPI getTypeAPI() { return typeAPI; } @Override public void updateTypeAPI(HollowTypeAPI typeAPI) { this.typeAPI = (IntegerTypeAPI) typeAPI; } }
package com.lzy.imagepicker.adapter; import android.Manifest; import android.app.Activity; import androidx.core.app.ActivityCompat; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ImageView; import android.widget.Toast; import com.lzy.imagepicker.ImagePicker; import com.lzy.imagepicker.R; import com.lzy.imagepicker.bean.ImageItem; import com.lzy.imagepicker.ui.ImageBaseActivity; import com.lzy.imagepicker.ui.ImageGridActivity; import com.lzy.imagepicker.util.Utils; import com.lzy.imagepicker.view.SuperCheckBox; import java.util.ArrayList; /** * 加载相册图片的RecyclerView适配器 * * 用于替换原项目的GridView,使用局部刷新解决选中照片出现闪动问题 * * 替换为RecyclerView后只是不再会导致全局刷新, * * 但还是会出现明显的重新加载图片,可能是picasso图片加载框架的问题 * * Author: nanchen * Email: liushilin520@foxmail.com * Date: 2017-04-05 10:04 */ public class ImageRecyclerAdapter extends RecyclerView.Adapter<ViewHolder> { private static final int ITEM_TYPE_CAMERA = 0; //第一个条目是相机 private static final int ITEM_TYPE_NORMAL = 1; //第一个条目不是相机 private ImagePicker imagePicker; private Activity mActivity; private ArrayList<ImageItem> images; //当前需要显示的所有的图片数据 private ArrayList<ImageItem> mSelectedImages; //全局保存的已经选中的图片数据 private boolean isShowCamera; //是否显示拍照按钮 private int mImageSize; //每个条目的大小 private LayoutInflater mInflater; private OnImageItemClickListener listener; //图片被点击的监听 public void setOnImageItemClickListener(OnImageItemClickListener listener) { this.listener = listener; } public interface OnImageItemClickListener { void onImageItemClick(View view, ImageItem imageItem, int position); } public void refreshData(ArrayList<ImageItem> images) { if (images == null || images.size() == 0) this.images = new ArrayList<>(); else this.images = images; notifyDataSetChanged(); } /** * 构造方法 */ public ImageRecyclerAdapter(Activity activity, ArrayList<ImageItem> images) { this.mActivity = activity; if (images == null || images.size() == 0) this.images = new ArrayList<>(); else this.images = images; mImageSize = Utils.getImageItemWidth(mActivity); imagePicker = ImagePicker.getInstance(); isShowCamera = imagePicker.isShowCamera(); mSelectedImages = imagePicker.getSelectedImages(); mInflater = LayoutInflater.from(activity); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == ITEM_TYPE_CAMERA){ return new CameraViewHolder(mInflater.inflate(R.layout.adapter_camera_item,parent,false)); } return new ImageViewHolder(mInflater.inflate(R.layout.adapter_image_list_item,parent,false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (holder instanceof CameraViewHolder){ ((CameraViewHolder)holder).bindCamera(); }else if (holder instanceof ImageViewHolder){ ((ImageViewHolder)holder).bind(position); } } @Override public int getItemViewType(int position) { if (isShowCamera) return position == 0 ? ITEM_TYPE_CAMERA : ITEM_TYPE_NORMAL; return ITEM_TYPE_NORMAL; } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return isShowCamera ? images.size() + 1 : images.size(); } public ImageItem getItem(int position) { if (isShowCamera) { if (position == 0) return null; return images.get(position - 1); } else { return images.get(position); } } private class ImageViewHolder extends ViewHolder{ View rootView; ImageView ivThumb; View mask; View checkView; SuperCheckBox cbCheck; ImageViewHolder(View itemView) { super(itemView); rootView = itemView; ivThumb = (ImageView) itemView.findViewById(R.id.iv_thumb); mask = itemView.findViewById(R.id.mask); checkView=itemView.findViewById(R.id.checkView); cbCheck = (SuperCheckBox) itemView.findViewById(R.id.cb_check); itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mImageSize)); //让图片是个正方形 } void bind(final int position){ final ImageItem imageItem = getItem(position); ivThumb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) listener.onImageItemClick(rootView, imageItem, position); } }); checkView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cbCheck.setChecked(!cbCheck.isChecked()); int selectLimit = imagePicker.getSelectLimit(); if (cbCheck.isChecked() && mSelectedImages.size() >= selectLimit) { Toast.makeText(mActivity.getApplicationContext(), mActivity.getString(R.string.ip_select_limit, selectLimit), Toast.LENGTH_SHORT).show(); cbCheck.setChecked(false); mask.setVisibility(View.GONE); } else { imagePicker.addSelectedImageItem(position, imageItem, cbCheck.isChecked()); mask.setVisibility(View.VISIBLE); } } }); //根据是否多选,显示或隐藏checkbox if (imagePicker.isMultiMode()) { cbCheck.setVisibility(View.VISIBLE); boolean checked = mSelectedImages.contains(imageItem); if (checked) { mask.setVisibility(View.VISIBLE); cbCheck.setChecked(true); } else { mask.setVisibility(View.GONE); cbCheck.setChecked(false); } } else { cbCheck.setVisibility(View.GONE); } imagePicker.getImageLoader().displayImage(mActivity, imageItem.path, ivThumb, mImageSize, mImageSize); //显示图片 } } private class CameraViewHolder extends ViewHolder{ View mItemView; CameraViewHolder(View itemView) { super(itemView); mItemView = itemView; } void bindCamera(){ mItemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mImageSize)); //让图片是个正方形 mItemView.setTag(null); mItemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!((ImageBaseActivity) mActivity).checkPermission(Manifest.permission.CAMERA)) { ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA}, ImageGridActivity.REQUEST_PERMISSION_CAMERA); } else { imagePicker.takePicture(mActivity, ImagePicker.REQUEST_CODE_TAKE); } } }); } } }
package net.parttimepolymath.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class ControllerHolderTest { @Mock private Controller controller; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void testGetAndSet() { ControllerHolder.reset(); assertNull(ControllerHolder.getController()); ControllerHolder.setController(controller); assertNotNull(ControllerHolder.getController()); assertEquals(controller, ControllerHolder.getController()); } }
/* * Copyright (C) 2015 Square, 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 retrofit2; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Objects; import java.util.concurrent.Executor; import javax.annotation.Nullable; import okhttp3.Request; import okio.Timeout; final class DefaultCallAdapterFactory extends CallAdapter.Factory { private final @Nullable Executor callbackExecutor; DefaultCallAdapterFactory(@Nullable Executor callbackExecutor) { this.callbackExecutor = callbackExecutor; } @Override public @Nullable CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != Call.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalArgumentException( "Call return type must be parameterized as Call<Foo> or Call<? extends Foo>"); } final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType); final Executor executor = Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class) ? null : callbackExecutor; //返回对应的callAdapter return new CallAdapter<Object, Call<?>>() { @Override public Type responseType() { return responseType; } @Override public Call<Object> adapt(Call<Object> call) { return executor == null ? call : new ExecutorCallbackCall<>(executor, call); } }; } static final class ExecutorCallbackCall<T> implements Call<T> { final Executor callbackExecutor; final Call<T> delegate; ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) { this.callbackExecutor = callbackExecutor; this.delegate = delegate; } @Override public void enqueue(final Callback<T> callback) { Objects.requireNonNull(callback, "callback == null"); delegate.enqueue( new Callback<T>() { @Override public void onResponse(Call<T> call, final Response<T> response) { //切一下线程,然后进行调用。这里会通过Handler,切换到UI线程,所以retrofit的回调是在主线程的 callbackExecutor.execute( () -> { if (delegate.isCanceled()) { // Emulate OkHttp's behavior of throwing/delivering an IOException on // cancellation. callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled")); } else { callback.onResponse(ExecutorCallbackCall.this, response); } }); } @Override public void onFailure(Call<T> call, final Throwable t) { callbackExecutor.execute(() -> callback.onFailure(ExecutorCallbackCall.this, t)); } }); } @Override public boolean isExecuted() { return delegate.isExecuted(); } @Override public Response<T> execute() throws IOException { return delegate.execute(); } @Override public void cancel() { delegate.cancel(); } @Override public boolean isCanceled() { return delegate.isCanceled(); } @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override public Call<T> clone() { return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone()); } @Override public Request request() { return delegate.request(); } @Override public Timeout timeout() { return delegate.timeout(); } } }
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting.activity; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.googlecode.android_scripting.Constants; import com.googlecode.android_scripting.R; import com.googlecode.android_scripting.bluetooth.BluetoothDiscoveryHelper; import com.googlecode.android_scripting.bluetooth.BluetoothDiscoveryHelper.BluetoothDiscoveryListener; import java.util.ArrayList; import java.util.List; public class BluetoothDeviceList extends ListActivity { private static class DeviceInfo { public final String mmName; public final String mmAddress; public DeviceInfo(String name, String address) { mmName = name; mmAddress = address; } } private final DeviceListAdapter mAdapter = new DeviceListAdapter(); private final BluetoothDiscoveryHelper mBluetoothHelper = new BluetoothDiscoveryHelper(this, mAdapter); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CustomizeWindow.requestCustomTitle(this, "Bluetooth Devices", R.layout.bluetooth_device_list); setListAdapter(mAdapter); // Analytics.trackActivity(this); } @Override protected void onStart() { super.onStart(); CustomizeWindow.toggleProgressBarVisibility(this, true); mBluetoothHelper.startDiscovery(); } @Override protected void onStop() { super.onStop(); mBluetoothHelper.cancel(); } @Override protected void onListItemClick(android.widget.ListView l, View v, int position, long id) { DeviceInfo device = (DeviceInfo) mAdapter.getItem(position); final Intent result = new Intent(); result.putExtra(Constants.EXTRA_DEVICE_ADDRESS, device.mmAddress); setResult(RESULT_OK, result); finish(); }; private class DeviceListAdapter extends BaseAdapter implements BluetoothDiscoveryListener { List<DeviceInfo> mmDeviceList; public DeviceListAdapter() { mmDeviceList = new ArrayList<DeviceInfo>(); } public void addDevice(String name, String address) { mmDeviceList.add(new DeviceInfo(name, address)); notifyDataSetChanged(); } @Override public int getCount() { return mmDeviceList.size(); } @Override public Object getItem(int position) { return mmDeviceList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup viewGroup) { final DeviceInfo device = mmDeviceList.get(position); final TextView view = new TextView(BluetoothDeviceList.this); view.setPadding(2, 2, 2, 2); view.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); view.setText(device.mmName + " (" + device.mmAddress + ")"); return view; } @Override public void addBondedDevice(String name, String address) { addDevice(name, address); } @Override public void scanDone() { CustomizeWindow.toggleProgressBarVisibility(BluetoothDeviceList.this, false); } } }
package io.sphere.sdk.products.queries; import io.sphere.sdk.models.Identifiable; import io.sphere.sdk.products.Product; import io.sphere.sdk.queries.PagedQueryResult; import io.sphere.sdk.queries.PagedResult; import org.junit.Test; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; public class QueryAllIntegrationTest extends QueryAllBase { //in production code it would higher #smalltestset private static final long PAGE_SIZE = 5; @Test public void useIdPredicateInsteadOfOffset() throws Exception { final ProductQuery seedQuery = ProductQuery.of() //the original predicate, which queries products for a certain product type //the idea works also for no predicate to get all products .withPredicates(m -> m.productType().is(productType)) //important, we sort by id, otherwise id > $lastId would not make sense .withSort(m -> m.id().sort().asc()) .withLimit(PAGE_SIZE) .withFetchTotal(false);//saves also resources and time final CompletionStage<List<Product>> resultStage = findNext(seedQuery, seedQuery, new LinkedList<>()); final List<Product> actualProducts = resultStage.toCompletableFuture().join(); assertThat(actualProducts).hasSize(createdProducts.size()); //!!! the underlying database has a different algorithm to sort by ID, it is a UUID, which differs from String sorting final List<Product> javaSortedActual = actualProducts.stream().sorted(BY_ID_COMPARATOR).collect(toList()); assertThat(javaSortedActual).isEqualTo(createdProducts); } private CompletionStage<List<Product>> findNext(final ProductQuery seedQuery, final ProductQuery query, final List<Product> products) { final CompletionStage<PagedQueryResult<Product>> pageResult = sphereClient().execute(query); return pageResult.thenCompose(page -> { final List<Product> results = page.getResults(); products.addAll(results); final boolean isLastQueryPage = results.size() < PAGE_SIZE; if (isLastQueryPage) { return CompletableFuture.completedFuture(products); } else { final String lastId = getIdForNextQuery(page); return findNext(seedQuery, seedQuery .plusPredicates(m -> m.id().isGreaterThan(lastId)), products); } }); } /** * Gets from a {@link PagedResult} the last ID if the result is not the last page. * This does only work correctly if it was sorted by ID in ascending order. * @param pagedResult the result to extract the id * @return the last ID, if present */ private <T extends Identifiable<T>> String getIdForNextQuery(final PagedResult<T> pagedResult) { final List<T> results = pagedResult.getResults(); final int indexLastElement = results.size() - 1; return results.get(indexLastElement).getId(); } }
package org.hyojeong.stdmgt.dao; import java.util.List; import org.hyojeong.stdmgt.model.AbsenceHistory; import org.hyojeong.stdmgt.model.ActiveHistory; import org.hyojeong.stdmgt.model.AwardsHistory; import org.hyojeong.stdmgt.model.ConsultHistory; import org.hyojeong.stdmgt.model.GradeHistory; import org.hyojeong.stdmgt.model.GrantHistory; import org.hyojeong.stdmgt.model.HolyHistory; import org.hyojeong.stdmgt.model.Login; import org.hyojeong.stdmgt.model.Notice; import org.hyojeong.stdmgt.model.Student; import org.hyojeong.stdmgt.model.UpdateHisory; import org.hyojeong.stdmgt.model.User; public interface UserDao { public int register(User user); public User validateUser(Login login); public Student getStudent(int pid); public List<Student> getStudentAll(); public int idCheck(String id); public int addStudent(Student student); public int insertUpdateStudentInfoHistory(UpdateHisory uhistory); public int updateStudentInfo(Student originStudent); public List<GradeHistory> getGradeHistory(int pid); public List<HolyHistory> getHolyHistory(int pid); public List<ActiveHistory> getActiveHistory(int pid); public List<AwardsHistory> getAwardsHistory(int pid); public List<ConsultHistory> getConsultHistory(int pid); public int updateGradeHistory(GradeHistory gHis); public int insertNewGradeHistory(GradeHistory gHis); public List<AbsenceHistory> getAbsenceHistory(int pid); public List<GrantHistory> getGrantHistory(int pid); public int updateProfileImg(int studentPid, String profilePath); public int insertNewActiveHistory(ActiveHistory aHis); public int updateActiveHistory(ActiveHistory aHis); public int insertNewAwardsHistory(AwardsHistory awHis); public int updateAwardsHistory(AwardsHistory awHis); public int removeAwardsHistory(AwardsHistory awHis); public int removeActiveHistory(ActiveHistory aHis); public int removeGradeHistory(GradeHistory gHis); public int removeHolyHistory(HolyHistory hHis); public int insertHolyHistory(HolyHistory hHis); public int updateHolyHistory(HolyHistory hHis); public int removeConsultHistory(ConsultHistory cHis); public int insertConsultHistory(ConsultHistory cHis); public int updateConsultHistory(ConsultHistory cHis); public int removeAbsenceHistory(AbsenceHistory aHis); public int insertAbsenceHistory(AbsenceHistory aHis); public int updateAbsenceHistory(AbsenceHistory aHis); public int removeGrantHistory(GrantHistory gHis); public int insertGrantHistory(GrantHistory gHis); public int updateGrantHistory(GrantHistory gHis); public List<Student> searchStudents(String category, String value); public void saveTotalCredit(Student student); public void saveTotalGradeWarning(Student student); public void saveTotalHolyWarning(Student student); public int updateAllItemsStudentInfo(Student originStudent); public List<User> getAdminUserAll(); public int adminUserRemove(User user); public int updateAdminUser(User user); public int insertAdminUser(User user); public List<Student> getPidWithSnoUniv(String sno_univ); public int changepassword(Login vo); public User getUserId(int studentPid); public List<Notice> getNoticeListAll(); public List<String> getAutoNationalityComplete(String query); public Notice getNoticeList(String notice_id); public int noticeInsert(Notice notice); public int noticeDelete(Notice notice); public int noticeEdit(Notice notice); public List<Notice> getNoticeTop3(); }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.web.holiday; import java.net.URI; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.apache.commons.lang.StringUtils; import org.joda.beans.impl.flexi.FlexiBean; import org.threeten.bp.LocalDate; import org.threeten.bp.Year; import com.opengamma.id.UniqueId; import com.opengamma.master.holiday.HolidayDocument; import com.opengamma.util.tuple.Pair; import com.opengamma.util.tuple.Pairs; /** * RESTful resource for a version of a holiday. */ @Path("/holidays/{holidayId}/versions/{versionId}") @Produces(MediaType.TEXT_HTML) public class WebHolidayVersionResource extends AbstractWebHolidayResource { /** * Creates the resource. * @param parent the parent resource, not null */ public WebHolidayVersionResource(final AbstractWebHolidayResource parent) { super(parent); } @GET @Produces(MediaType.APPLICATION_JSON) public Response getJSON(@Context Request request) { EntityTag etag = new EntityTag(data().getVersioned().getUniqueId().toString()); ResponseBuilder builder = request.evaluatePreconditions(etag); if (builder != null) { return builder.build(); } FlexiBean out = createRootData(); String json = getFreemarker().build(JSON_DIR + "holiday.ftl", out); return Response.ok(json).tag(etag).build(); } //------------------------------------------------------------------------- /** * Creates the output root data. * @return the output root data, not null */ @Override protected FlexiBean createRootData() { FlexiBean out = super.createRootData(); HolidayDocument latestDoc = data().getHoliday(); HolidayDocument versionedHoliday = data().getVersioned(); out.put("latestHolidayDoc", latestDoc); out.put("latestHoliday", latestDoc.getHoliday()); out.put("holidayDoc", versionedHoliday); out.put("holiday", versionedHoliday.getHoliday()); out.put("deleted", !latestDoc.isLatest()); List<Pair<Year, List<LocalDate>>> map = new ArrayList<Pair<Year, List<LocalDate>>>(); List<LocalDate> dates = versionedHoliday.getHoliday().getHolidayDates(); if (dates.size() > 0) { int year = dates.get(0).getYear(); int start = 0; int pos = 0; for ( ; pos < dates.size(); pos++) { if (dates.get(pos).getYear() == year) { continue; } map.add(Pairs.of(Year.of(year), dates.subList(start, pos))); year = dates.get(pos).getYear(); start = pos; } map.add(Pairs.of(Year.of(year), dates.subList(start, pos))); } out.put("holidayDatesByYear", map); return out; } //------------------------------------------------------------------------- /** * Builds a URI for this resource. * @param data the data, not null * @return the URI, not null */ public static URI uri(final WebHolidayData data) { return uri(data, null); } /** * Builds a URI for this resource. * @param data the data, not null * @param overrideVersionId the override version id, null uses information from data * @return the URI, not null */ public static URI uri(final WebHolidayData data, final UniqueId overrideVersionId) { String holidayId = data.getBestHolidayUriId(null); String versionId = StringUtils.defaultString(overrideVersionId != null ? overrideVersionId.getVersion() : data.getUriVersionId()); return data.getUriInfo().getBaseUriBuilder().path(WebHolidayVersionResource.class).build(holidayId, versionId); } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network; import com.fasterxml.jackson.annotation.JsonProperty; /** * Parameters that define the retention policy for flow log. */ public class RetentionPolicyParameters { /** * Number of days to retain flow log records. */ @JsonProperty(value = "days") private Integer days; /** * Flag to enable/disable retention. */ @JsonProperty(value = "enabled") private Boolean enabled; /** * Get the days value. * * @return the days value */ public Integer days() { return this.days; } /** * Set the days value. * * @param days the days value to set * @return the RetentionPolicyParameters object itself. */ public RetentionPolicyParameters withDays(Integer days) { this.days = days; return this; } /** * Get the enabled value. * * @return the enabled value */ public Boolean enabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled the enabled value to set * @return the RetentionPolicyParameters object itself. */ public RetentionPolicyParameters withEnabled(Boolean enabled) { this.enabled = enabled; return this; } }
/* * Copyright (c) 2003, 2018, 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. */ package nsk.jdi.ClassType.allInterfaces; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; /** * The debugged application of the test. */ public class allinterfaces002a { //------------------------------------------------------- immutable common fields private static int exitStatus; private static ArgumentHandler argHandler; private static Log log; private static IOPipe pipe; //------------------------------------------------------- immutable common methods static void display(String msg) { log.display("debuggee > " + msg); } static void complain(String msg) { log.complain("debuggee FAILURE > " + msg); } public static void receiveSignal(String signal) { String line = pipe.readln(); if ( !line.equals(signal) ) throw new Failure("UNEXPECTED debugger's signal " + line); display("debugger's <" + signal + "> signal received."); } //------------------------------------------------------ mutable common fields //------------------------------------------------------ test specific fields static Enum1 f1 = Enum1.e1; static Enum2 f2 = Enum2.e2; static Enum3 f3 = Enum3.e1; static Enum4.Enum4_ f4 = Enum4.Enum4_.e1; static allinterfaces002Enum5 f5 = allinterfaces002Enum5.e2; static allinterfaces002Enum6 f6 = allinterfaces002Enum6.e1; static allinterfaces002Enum7 f7 = allinterfaces002Enum7.e2; static allinterfaces002Enum8.Enum8_ f8 = allinterfaces002Enum8.Enum8_.e1; //------------------------------------------------------ mutable common method public static void main (String argv[]) { exitStatus = Consts.TEST_FAILED; argHandler = new ArgumentHandler(argv); log = new Log(System.err, argHandler); pipe = argHandler.createDebugeeIOPipe(log); pipe.println(allinterfaces002.SIGNAL_READY); //pipe.println(allinterfaces002.SIGNAL_GO); receiveSignal(allinterfaces002.SIGNAL_QUIT); display("completed succesfully."); System.exit(Consts.TEST_PASSED + Consts.JCK_STATUS_BASE); } //--------------------------------------------------------- test specific inner classes enum Enum1 { e1, e2; } enum Enum2 { e1 { int val() {return 1;} }, e2 { int val() {return 2;} }; abstract int val(); } enum Enum3 implements allinterfaces002i { e1 { int val() {return i+1;} }, e2 { int val() {return i+2;} }; abstract int val(); } enum Enum4 { e1, e2; enum Enum4_ { e1, e2; } } } //--------------------------------------------------------- test specific classes enum allinterfaces002Enum5 { e1, e2; } enum allinterfaces002Enum6 { e1 { int val() {return 1;} }, e2 { int val() {return 2;} }; abstract int val(); } enum allinterfaces002Enum7 implements allinterfaces002i { e1 { int val() {return i+1;} }, e2 { int val() {return i+2;} }; abstract int val(); } enum allinterfaces002Enum8 { e1, e2; enum Enum8_ { e1, e2; } } interface allinterfaces002i { int i = 1; }
package com.boilerplate; import android.app.Application; import android.util.Log; import com.facebook.react.PackageList; import com.facebook.hermes.reactexecutor.HermesExecutorFactory; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.ReactApplication; import com.horcrux.svg.SvgPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
/* * Copyright (C) 2018 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.webapp.architecture; import com.tngtech.archunit.base.DescribedPredicate; import com.tngtech.archunit.base.PackageMatcher; import com.tngtech.archunit.core.domain.JavaClass; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.domain.JavaModifier; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchCondition; import com.tngtech.archunit.lang.ConditionEvents; import com.tngtech.archunit.lang.Priority; import com.tngtech.archunit.lang.SimpleConditionEvent; import org.aeonbits.owner.Config; import org.hibernate.envers.Audited; import org.jbb.lib.db.domain.BaseEntity; import org.jbb.lib.db.revision.RevisionInfo; import org.jbb.lib.eventbus.JbbEvent; import org.jbb.lib.restful.domain.ErrorInfoCodes; import org.jbb.permissions.api.annotation.AdministratorPermissionRequired; import org.jbb.permissions.api.annotation.MemberPermissionRequired; import org.jbb.system.impl.stacktrace.PermissionBasedStackTraceProvider; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.RestController; import java.lang.annotation.Annotation; import javax.persistence.Entity; import javax.persistence.Table; import io.swagger.annotations.ApiOperation; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.priority; import static com.tngtech.archunit.library.Architectures.layeredArchitecture; import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices; public class JbbArchRules { public static final String TECH_LIBS_LAYER = "Tech libs Layer"; public static final String API_LAYER = "API Layer"; public static final String EVENT_API_LAYER = "Event API Layer"; public static final String SERVICES_LAYER = "Services Layer"; public static final String WEB_LAYER = "Web Layer"; public static final String REST_LAYER = "REST Layer"; public static final String APP_INIT_LAYER = "App Initializer Layer"; public static final String TECH_LIBS_PACKAGES = "org.jbb.lib.."; public static final String API_PACKAGES = "org.jbb.(*).api.."; public static final String EVENT_API_PACKAGES = "org.jbb.(*).event.."; public static final String SERVICES_PACKAGES = "org.jbb.(*).impl.."; public static final String WEB_PACKAGES = "org.jbb.(*).web.."; public static final String REST_PACKAGES = "org.jbb.(*).rest.."; public static final String APP_INIT_PACKAGES = "org.jbb.webapp.."; @ArchTest public static void testLayeredArchitecture(JavaClasses classes) { layeredArchitecture() .layer(TECH_LIBS_LAYER).definedBy(TECH_LIBS_PACKAGES) .layer(API_LAYER).definedBy(API_PACKAGES) .layer(EVENT_API_LAYER).definedBy(EVENT_API_PACKAGES) .layer(SERVICES_LAYER).definedBy(SERVICES_PACKAGES) .layer(WEB_LAYER).definedBy(WEB_PACKAGES) .layer(REST_LAYER).definedBy(REST_PACKAGES) .layer(APP_INIT_LAYER).definedBy(APP_INIT_PACKAGES) .whereLayer(TECH_LIBS_LAYER) .mayOnlyBeAccessedByLayers( SERVICES_LAYER, WEB_LAYER, REST_LAYER, EVENT_API_LAYER, APP_INIT_LAYER) .whereLayer(API_LAYER) .mayOnlyBeAccessedByLayers(SERVICES_LAYER, WEB_LAYER, REST_LAYER, APP_INIT_LAYER) .whereLayer(EVENT_API_LAYER) .mayOnlyBeAccessedByLayers(SERVICES_LAYER, WEB_LAYER, REST_LAYER) .whereLayer(SERVICES_LAYER).mayNotBeAccessedByAnyLayer() .whereLayer(WEB_LAYER).mayNotBeAccessedByAnyLayer() .whereLayer(REST_LAYER).mayNotBeAccessedByAnyLayer() .whereLayer(APP_INIT_LAYER).mayNotBeAccessedByAnyLayer() .check(classes); } @ArchTest public static void serviceLayerShouldNotUseWebLayer(JavaClasses classes) { priority(Priority.HIGH).noClasses() .that().resideInAPackage(SERVICES_PACKAGES) .should().accessClassesThat().resideInAPackage(WEB_PACKAGES) .check(classes); } @ArchTest public static void serviceLayerShouldNotUseRestLayer(JavaClasses classes) { priority(Priority.HIGH).noClasses() .that().resideInAPackage(SERVICES_PACKAGES) .should().accessClassesThat().resideInAPackage(REST_PACKAGES) .check(classes); } @ArchTest public static void webLayerShouldNotUseServiceLayer(JavaClasses classes) { priority(Priority.HIGH).noClasses() .that().resideInAPackage(WEB_PACKAGES) .should().accessClassesThat().resideInAPackage(SERVICES_PACKAGES) .check(classes); } @ArchTest public static void webLayerShouldNotUseRestLayer(JavaClasses classes) { priority(Priority.HIGH).noClasses() .that().resideInAPackage(WEB_PACKAGES) .should().accessClassesThat().resideInAPackage(REST_PACKAGES) .check(classes); } @ArchTest public static void restLayerShouldNotUseServiceLayer(JavaClasses classes) { priority(Priority.HIGH).noClasses() .that().resideInAPackage(REST_PACKAGES) .should().accessClassesThat().resideInAPackage(SERVICES_PACKAGES) .check(classes); } @ArchTest public static void restLayerShouldNotUseWebLayer(JavaClasses classes) { priority(Priority.HIGH).noClasses() .that().resideInAPackage(REST_PACKAGES) .should().accessClassesThat().resideInAPackage(WEB_PACKAGES) .check(classes); } @ArchTest public static void controllersShouldNotUseRepositoriesDirectly(JavaClasses classes) { priority(Priority.HIGH).noClasses().that().areAnnotatedWith(Controller.class) .should().accessClassesThat().areAnnotatedWith(Repository.class) .check(classes); } @ArchTest public static void restControllersShouldNotUseRepositoriesDirectly(JavaClasses classes) { priority(Priority.HIGH).noClasses().that().areAnnotatedWith(RestController.class) .should().accessClassesThat().areAnnotatedWith(Repository.class) .check(classes); } @ArchTest public static void controllerNameShouldEndsWithController(JavaClasses classes) { priority(Priority.LOW).classes().that().areAnnotatedWith(Controller.class) .should().haveNameMatching(".*Controller") .check(classes); } @ArchTest public static void restControllerNameShouldEndsWithResource(JavaClasses classes) { priority(Priority.LOW).classes().that().areAnnotatedWith(RestController.class) .should().haveNameMatching(".*Resource") .check(classes); } @ArchTest public static void entitiesShouldExtendBaseEntity(JavaClasses classes) { priority(Priority.MEDIUM).classes().that(areEntity()).and(notBe(RevisionInfo.class)) .should().beAssignableTo(BaseEntity.class) .check(classes); } @ArchTest public static void entitiesShouldBeAudited(JavaClasses classes) { priority(Priority.HIGH).classes().that(areEntity()).and(notBe(RevisionInfo.class)) .should().beAnnotatedWith(Audited.class) .check(classes); } @ArchTest public static void entityNameShouldEndsWithEntity(JavaClasses classes) { priority(Priority.LOW).classes().that(areEntity()).and(notBe(RevisionInfo.class)) .should().haveNameMatching(".*Entity") .check(classes); } @ArchTest public static void allClassesMustBeInOrgJbbPackage(JavaClasses classes) { priority(Priority.MEDIUM).classes() .should().resideInAPackage("org.jbb..").check(classes); } @ArchTest public static void springConfigurationClassNameShouldEndsWithConfig(JavaClasses classes) { priority(Priority.LOW).classes().that().areAnnotatedWith(Configuration.class) .should().haveNameMatching(".*Config") .check(classes); } @ArchTest public static void ownerConfigurationClassNameShouldEndsWithProperties(JavaClasses classes) { priority(Priority.LOW).classes().that().areAssignableTo(Config.class) .should().haveNameMatching(".*Properties") .check(classes); } @ArchTest public static void jbbDomainEventClassNameShouldEndsWithEvent(JavaClasses classes) { priority(Priority.LOW).classes().that().areAssignableTo(JbbEvent.class) .should().haveNameMatching(".*Event") .check(classes); } @ArchTest public static void libModulesCannotHaveCycle(JavaClasses classes) { slices().matching(TECH_LIBS_PACKAGES).namingSlices("$1 lib") .as(TECH_LIBS_LAYER).should().beFreeOfCycles().check(classes); } @ArchTest public static void apiModuleCannotUseAnotherApiModule(JavaClasses classes) { slices().matching(API_PACKAGES).namingSlices("$1 api") .as(API_LAYER).should().notDependOnEachOther().check(classes); } @ArchTest public static void eventApiModuleCannotUseAnotherEventApiModule(JavaClasses classes) { slices().matching(EVENT_API_PACKAGES).namingSlices("$1 event api") .as(EVENT_API_LAYER).should().notDependOnEachOther().check(classes); } @ArchTest public static void serviceModuleCannotUseAnotherServiceModule(JavaClasses classes) { slices().matching(SERVICES_PACKAGES).namingSlices("$1 service") .as(SERVICES_LAYER).should().notDependOnEachOther().check(classes); } @ArchTest public static void webModuleCannotUseAnotherWebModule(JavaClasses classes) { slices().matching(WEB_PACKAGES).namingSlices("$1 web") .as(WEB_LAYER).should().notDependOnEachOther().check(classes); } @ArchTest public static void restModuleCannotUseAnotherRestModule(JavaClasses classes) { slices().matching(REST_PACKAGES).namingSlices("$1 rest") .as(REST_LAYER).should().notDependOnEachOther().check(classes); } @ArchTest public static void serviceLayerShouldNotBeSecuredWithAdministratorPermissionRequiredAnnotation( JavaClasses classes) { priority(Priority.HIGH).classes() .that().resideInAPackage(SERVICES_PACKAGES) .should().notBeAnnotatedWith(AdministratorPermissionRequired.class) .andShould(notHaveMethodAnnotatedWith(AdministratorPermissionRequired.class)) .check(classes); } @ArchTest public static void serviceLayerShouldNotBeSecuredWithMemberPermissionRequiredAnnotation( JavaClasses classes) { priority(Priority.HIGH).classes() .that().resideInAPackage(SERVICES_PACKAGES) .should().notBeAnnotatedWith(MemberPermissionRequired.class) .andShould(notHaveMethodAnnotatedWith(MemberPermissionRequired.class)) .check(classes); } @ArchTest public static void serviceLayerShouldNotBeSecuredWithPermissionServiceAssertion( JavaClasses classes) { priority(Priority.HIGH).noClasses().that(areInAServicePackagesExcludingPermissions()) .should().accessClassesThat().resideInAPackage("org.jbb.permissions.(*)") .check(classes); } @ArchTest public static void publicMethodsOfRestControllersShouldHaveDefinedErrorInfoCodes( JavaClasses classes) { priority(Priority.MEDIUM).classes().that().areAnnotatedWith(RestController.class) .should(havePublicMethodAnnotatedWith(ErrorInfoCodes.class)) .check(classes); } @ArchTest public static void publicMethodsOfRestControllersShouldHaveApiOperation( JavaClasses classes) { priority(Priority.MEDIUM).classes().that().areAnnotatedWith(RestController.class) .should(havePublicMethodAnnotatedWith(ApiOperation.class)) .check(classes); } @ArchTest public static void publicMethodsOfRestControllersShouldHavePreAuthorize( JavaClasses classes) { priority(Priority.MEDIUM).classes().that().areAnnotatedWith(RestController.class) .should(havePublicMethodAnnotatedWith(PreAuthorize.class)) .check(classes); } private static DescribedPredicate<JavaClass> areInAServicePackagesExcludingPermissions() { return new DescribedPredicate<JavaClass>( "Service layer (excluding permission service layer and PermissionBasedStackTraceProvider)") { @Override public boolean apply(JavaClass javaClass) { return PackageMatcher.of(SERVICES_PACKAGES).matches(javaClass.getPackage()) && !javaClass.getPackage().startsWith("org.jbb.permissions") && !javaClass.getName().equals(PermissionBasedStackTraceProvider.class.getName()); } }; } private static DescribedPredicate<JavaClass> areEntity() { return new DescribedPredicate<JavaClass>("Entity class") { @Override public boolean apply(JavaClass javaClass) { return javaClass.isAnnotatedWith(Entity.class) || javaClass.isAnnotatedWith(Table.class); } }; } private static ArchCondition<JavaClass> notHaveMethodAnnotatedWith( Class<? extends Annotation> annotation) { return new ArchCondition<JavaClass>( "not have method annotated with @" + annotation.getName()) { @Override public void check(JavaClass javaClass, ConditionEvents conditionEvents) { javaClass.getMethods().stream() .filter(method -> method.isAnnotatedWith(annotation)) .forEach(method -> { conditionEvents.add(new SimpleConditionEvent(javaClass, false, "method " + method.getFullName() + " is annotated with @" + annotation .getSimpleName())); }); } }; } private static ArchCondition<JavaClass> havePublicMethodAnnotatedWith( Class<? extends Annotation> annotation) { return new ArchCondition<JavaClass>( "have public method annotated with @" + annotation.getName()) { @Override public void check(JavaClass javaClass, ConditionEvents conditionEvents) { javaClass.getMethods().stream() .filter(method -> method.getModifiers().contains(JavaModifier.PUBLIC)) .filter(method -> !method.isAnnotatedWith(annotation)) .forEach(method -> { conditionEvents.add(new SimpleConditionEvent(javaClass, false, "method " + method.getFullName() + " is not annotated with @" + annotation .getSimpleName())); }); } }; } private static DescribedPredicate<JavaClass> notBe(Class clazz) { return new DescribedPredicate<JavaClass>("Class " + clazz.getCanonicalName()) { @Override public boolean apply(JavaClass javaClass) { return !javaClass.getName().equals(clazz.getName()); } }; } }
/* * Copyright (C) 2004 Derek James and Philip Tucker * * This file is part of ANJI (Another NEAT Java Implementation). * * ANJI is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; if * not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * created by Derek James on Jul 6, 2004 */ package com.anji.imaging; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.anji.Copyright; /** * class CanvasEnlarger */ public class CanvasEnlarger { /** * @param args * @throws Exception */ public static void main( String[] args ) throws Exception { System.out.println( Copyright.STRING ); CanvasEnlarger ce = new CanvasEnlarger(); ce.transformFiles(); } /** * @throws Exception */ public void transformFiles() throws Exception { // Read from a file File dir = new File( "images/original_matches/" ); String s[] = dir.list(); for ( int i = 0; i < s.length; i++ ) { Image image = null; Image bg = null; try { StringBuffer sb1 = new StringBuffer( s[ i ].length() ); sb1.append( "images/original_matches/" ); sb1.append( s[ i ] ); System.out.println( "transforming: " + sb1.toString() ); StringBuffer sb2 = new StringBuffer( s[ i ].length() ); sb2.append( "images/matches/" ); sb2.append( s[ i ] ); String bgwhite = new String( "images/bgwhite.tif" ); File file = new File( sb1.toString() ); image = ImageIO.read( file ); File file2 = new File( bgwhite ); bg = ImageIO.read( file2 ); BufferedImage bi = new BufferedImage( ( image.getWidth( null ) * 2 ), ( image .getHeight( null ) * 2 ), BufferedImage.TYPE_INT_RGB ); Graphics g = bi.createGraphics(); g.drawImage( bg, 0, 0, null ); g .drawImage( image, ( image.getWidth( null ) / 2 ), ( image.getHeight( null ) / 2 ), null ); g.dispose(); File fileOut = new File( sb2.toString() ); ImageIO.write( bi, "tif", fileOut ); } catch ( IOException e ) { throw e; } } } }
/* Copyright 2018 The TensorFlow Authors. 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. =======================================================================*/ // This class has been generated, DO NOT EDIT! package org.tensorflow.op.math; import org.tensorflow.DataType; import org.tensorflow.Operand; import org.tensorflow.Operation; import org.tensorflow.OperationBuilder; import org.tensorflow.Output; import org.tensorflow.op.RawOp; import org.tensorflow.op.Scope; import org.tensorflow.op.annotation.Endpoint; import org.tensorflow.op.annotation.Operator; import org.tensorflow.types.TFloat32; import org.tensorflow.types.family.TType; /** * Requantizes input with min and max values known per channel. * * @param <U> data type for {@code output()} output */ public final class RequantizePerChannel<U extends TType> extends RawOp { /** * Factory method to create a class wrapping a new RequantizePerChannel operation. * * @param scope current scope * @param input The original input tensor. * @param inputMin The minimum value of the input tensor * @param inputMax The maximum value of the input tensor. * @param requestedOutputMin The minimum value of the output tensor requested. * @param requestedOutputMax The maximum value of the output tensor requested. * @param outType The quantized type of output tensor that needs to be converted. * @return a new instance of RequantizePerChannel */ @Endpoint(describeByClass = true) public static <U extends TType, T extends TType> RequantizePerChannel<U> create(Scope scope, Operand<T> input, Operand<TFloat32> inputMin, Operand<TFloat32> inputMax, Operand<TFloat32> requestedOutputMin, Operand<TFloat32> requestedOutputMax, DataType<U> outType) { OperationBuilder opBuilder = scope.env().opBuilder("RequantizePerChannel", scope.makeOpName("RequantizePerChannel")); opBuilder.addInput(input.asOutput()); opBuilder.addInput(inputMin.asOutput()); opBuilder.addInput(inputMax.asOutput()); opBuilder.addInput(requestedOutputMin.asOutput()); opBuilder.addInput(requestedOutputMax.asOutput()); opBuilder = scope.applyControlDependencies(opBuilder); opBuilder.setAttr("out_type", outType); return new RequantizePerChannel<U>(opBuilder.build()); } /** * Output tensor. */ public Output<U> output() { return output; } /** * The minimum value of the final output tensor */ public Output<TFloat32> outputMin() { return outputMin; } /** * The maximum value of the final output tensor. */ public Output<TFloat32> outputMax() { return outputMax; } private Output<U> output; private Output<TFloat32> outputMin; private Output<TFloat32> outputMax; private RequantizePerChannel(Operation operation) { super(operation); int outputIdx = 0; output = operation.output(outputIdx++); outputMin = operation.output(outputIdx++); outputMax = operation.output(outputIdx++); } }
package org.fengfei.lanparoxy.client.test; import java.util.Arrays; import org.fengfei.lanproxy.client.ProxyClientContainer; import org.fengfei.lanproxy.common.container.Container; import org.fengfei.lanproxy.common.container.ContainerHelper; public class TestMain { public static void main(String[] args) { ContainerHelper.start(Arrays.asList(new Container[] { new ProxyClientContainer() })); } }
/** * 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.hadoop.hbase.regionserver.wal; import org.apache.hadoop.hbase.metrics.BaseSource; /** * Interface of the source that will export metrics about log replay statistics when recovering a * region server in distributedLogReplay mode */ public interface MetricsEditsReplaySource extends BaseSource { /** * The name of the metrics */ String METRICS_NAME = "replay"; /** * The name of the metrics context that metrics will be under. */ String METRICS_CONTEXT = "regionserver"; /** * Description */ String METRICS_DESCRIPTION = "Metrics about HBase RegionServer HLog Edits Replay"; /** * The name of the metrics context that metrics will be under in jmx */ String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String REPLAY_TIME_NAME = "replayTime"; String REPLAY_TIME_DESC = "Time an replay operation took."; String REPLAY_BATCH_SIZE_NAME = "replayBatchSize"; String REPLAY_BATCH_SIZE_DESC = "Number of changes in each replay batch."; String REPLAY_DATA_SIZE_NAME = "replayDataSize"; String REPLAY_DATA_SIZE_DESC = "Size (in bytes) of the data of each replay."; /** * Add the time a replay command took */ void updateReplayTime(long time); /** * Add the batch size of each replay */ void updateReplayBatchSize(long size); /** * Add the payload data size of each replay */ void updateReplayDataSize(long size); }
package com.atoito.clap.test; import org.assertj.core.api.Assertions; import com.atoito.clap.api.CommandResult; /** * Clap Fest assertions module: extending make all standard Fest assertions available. * */ public class ClapAssertions extends Assertions { public static CommandResultAssert assertThat(CommandResult actual) { return new CommandResultAssert(actual); } }
package org.ko.prototype.rest.menu.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import org.ko.prototype.data.entity.Menu; import org.ko.prototype.rest.menu.condition.QueryMenuCondition; import org.ko.prototype.rest.menu.dto.MenuDTO; import java.util.List; public interface MenuService extends IService<Menu> { /** * <p>查询菜单列表</p> * @param condition * @return */ IPage<MenuDTO> queryMenuList(QueryMenuCondition condition); /** * <p>通过主键查询菜单</p> * @param id * @return */ Menu queryMenuInfo(Long id); List<MenuDTO> queryMenuByParentId(Long parentId); /** * <p>创建新的菜单</p> * @param menu */ Long createMenu(Menu menu); /** * <p>通过ID更新菜单</p> * @param id Menu Id * @param menu 菜单对象 * @return */ Menu updateMenu(Long id, Menu menu); /** * <p>删除菜单</p> * @param id Menu主键id * @return */ Long deleteMenu(Long id); /** * 通过权限ID查询菜单列表 * @param roleCode * @return */ List<MenuDTO> queryMenuByRoleCode(String roleCode); }
/** * @license * Copyright 2013 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 foam.core; import java.util.HashMap; import java.util.Map; public abstract class AbstractModel implements Model { final Property[] properties_; final Relationship[] relationships_; final Map<String, Property> pMap_ = new HashMap<>(); final Map<String, Relationship> rMap_ = new HashMap<>(); final Model parent_; public AbstractModel(Property[] properties, Relationship[] relationships) { this(null, properties, relationships); } public AbstractModel(Model parent, Property[] properties, Relationship[] relationships) { parent_ = parent; properties_ = properties; relationships_ = relationships; for ( Property p : properties ) { pMap_.put(p.getName(), p); } for (Relationship r : relationships) { rMap_.put(r.getName(), r); } } public Model getParent() { return parent_; } public Property[] getProperties() { return properties_; } public Property getProperty(String propertyName) { Property p = pMap_.get(propertyName); if (p == null && parent_ != null) p = parent_.getProperty(propertyName); return p; } public Relationship[] getRelationships() { return relationships_; } public Relationship getRelationship(String name) { return rMap_.get(name); } public Feature getFeature(String name) { Feature f = pMap_.get(name); if (f == null) f = rMap_.get(name); return f; } }
package com.kuta.base.util; import java.nio.ByteBuffer; import java.util.Base64; import java.util.Collection; import java.util.Map; public class KutaUtil { /** * 检查值是否为null,如果为null返回true,不为null返回false * * @param obj 展开的对象数组 * @return 是否为空 */ public static boolean isValueNull(Object... obj) { for (int i = 0; i < obj.length; i++) { if (obj[i] == null || "".equals(obj[i])) { return true; } } return false; } /** * 检查字符串是否为空或者null,如果为空或者null返回true,否则返回false * * @param s 字符串 * @return 是否为空或者null */ public static boolean isEmptyString(String s) { if(null==s || s.equals("")) { return true; } return false; } /** * 检查Map是否为空或者null,如果为空或者null返回true,否则返回false * * @param s map * @return 是否为空或者null */ public static boolean isEmptyMap(Map<?,?> map) { if(map == null || map.size() == 0) { return true; } return false; } /** * 检查Collection是否为空或者null,如果为空或者null返回true,否则返回false * * @param coll 集合 * @return 是否为空或者null */ public static boolean isEmptyColl(Collection<?> coll) { if(coll == null || coll.size() == 0) { return true; } return false; } /** * 将int转换为byte数组 * @param i int值 * @return byte数组 * */ public static byte[] intToBytes(int i) { byte[] targets = new byte[4]; targets[3] = (byte) (i & 0xFF); targets[2] = (byte) (i >> 8 & 0xFF); targets[1] = (byte) (i >> 16 & 0xFF); targets[0] = (byte) (i >> 24 & 0xFF); return targets; } /** * 将byte数组转换为int * * @param b byte数组 * @return int值 * */ public static int bytesToInt(byte[] b) { return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24; } /** * 将long转换为byte数组 * @param x long值 * @return byte数组 * */ public static byte[] longToBytes(long x) { ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(0, x); return buffer.array(); } /** * 将byte数组转换为long * * @param b byte数组 * @return long值 * */ public static long bytesToLong(byte[] bytes) { ByteBuffer buf = ByteBuffer.allocate(bytes.length).put(bytes); buf.flip();//need flip return buf.getLong(); } /** * 将int转换为Base64字符串 * <p>使用此方法转换后的Base64字符串是等长的</p> * <p>可用于redis中键设置</p> * @param i int值 * @return String类型值 * */ public static String intToBase64(int i) { return new String(Base64.getEncoder().encode(intToBytes(i))); } /** * 将Base64字符串转换为Integer * @param base64Str base64字符串 * @return Integer值 * */ public static Integer base64ToInt(String base64Str) { return bytesToInt(Base64.getDecoder().decode(base64Str)); } /** * 将long转换为Base64字符串 * <p>使用此方法转换后的Base64字符串是等长的</p> * <p>可用于redis中键设置</p> * @param l long值 * @return String类型值 * */ public static String longToBase64(long l) { return new String(Base64.getEncoder().encode(longToBytes(l))); } /** * 将Base64字符串转换为Long * @param base64Str base64字符串 * @return Long值 * */ public static Long base64ToLong(String base64Str) { return bytesToLong(Base64.getDecoder().decode(base64Str)); } }
package com.google.inject.servlet; import static org.easymock.EasyMock.createMock; import com.google.inject.Guice; import com.google.inject.Scopes; import com.google.inject.Singleton; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import junit.framework.TestCase; /** * Ensures that an error is thrown if a Servlet or Filter is bound under any scope other than * singleton, explicitly. * * @author dhanji@gmail.com */ public class InvalidScopeBindingTest extends TestCase { @Override protected void tearDown() throws Exception { GuiceFilter.reset(); } public final void testServletInNonSingletonScopeThrowsServletException() { GuiceFilter guiceFilter = new GuiceFilter(); Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { serve("/*").with(MyNonSingletonServlet.class); } }); ServletException se = null; try { guiceFilter.init(createMock(FilterConfig.class)); } catch (ServletException e) { se = e; } finally { assertNotNull("Servlet exception was not thrown with wrong scope binding", se); } } public final void testFilterInNonSingletonScopeThrowsServletException() { GuiceFilter guiceFilter = new GuiceFilter(); Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { filter("/*").through(MyNonSingletonFilter.class); } }); ServletException se = null; try { guiceFilter.init(createMock(FilterConfig.class)); } catch (ServletException e) { se = e; } finally { assertNotNull("Servlet exception was not thrown with wrong scope binding", se); } } public final void testHappyCaseFilter() { GuiceFilter guiceFilter = new GuiceFilter(); Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { // Annotated scoping variant. filter("/*").through(MySingletonFilter.class); // Explicit scoping variant. bind(DummyFilterImpl.class).in(Scopes.SINGLETON); filter("/*").through(DummyFilterImpl.class); } }); ServletException se = null; try { guiceFilter.init(createMock(FilterConfig.class)); } catch (ServletException e) { se = e; } finally { assertNull("Servlet exception was thrown with correct scope binding", se); } } @RequestScoped public static class MyNonSingletonServlet extends HttpServlet {} @SessionScoped public static class MyNonSingletonFilter extends DummyFilterImpl {} @Singleton public static class MySingletonFilter extends DummyFilterImpl {} }
/* * The contents of this file are subject to the OpenMRS Public License * Version 1.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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.mobile.activities.formentrypatientlist; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import org.openmrs.mobile.R; import org.openmrs.mobile.activities.ACBaseActivity; import org.openmrs.mobile.application.OpenMRS; public class FormEntryPatientListActivity extends ACBaseActivity { private FormEntryPatientListContract.Presenter mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_form_entry_patient_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // Create fragment FormEntryPatientListFragment formEntryPatientListFragment = (FormEntryPatientListFragment) getSupportFragmentManager().findFragmentById(R.id.formEntryPatientListContentFrame); if (formEntryPatientListFragment == null) { formEntryPatientListFragment = FormEntryPatientListFragment.newInstance(); } if (!formEntryPatientListFragment.isActive()) { addFragmentToActivity(getSupportFragmentManager(), formEntryPatientListFragment, R.id.formEntryPatientListContentFrame); } // Create the presenter mPresenter = new FormEntryPatientListPresenter (formEntryPatientListFragment); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.form_entry_patient_list_menu, menu); final SearchView findPatientView; MenuItem mFindPatientMenuItem = menu.findItem(R.id.actionSearchRemoteFormEntry); findPatientView = (SearchView) mFindPatientMenuItem.getActionView(); // Search function findPatientView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { findPatientView.clearFocus(); return true; } @Override public boolean onQueryTextChange(String query) { mPresenter.setQuery(query); mPresenter.updatePatientsList(); return true; } }); return true; } }
package uk.gov.pay.connector.wallets; import uk.gov.pay.connector.charge.model.domain.ChargeEntity; import uk.gov.pay.connector.gateway.model.request.AuthorisationGatewayRequest; import uk.gov.pay.connector.wallets.model.WalletAuthorisationData; import java.util.Map; public class WalletAuthorisationGatewayRequest extends AuthorisationGatewayRequest { private WalletAuthorisationData walletAuthorisationData; public WalletAuthorisationGatewayRequest(ChargeEntity charge, WalletAuthorisationData walletAuthorisationData) { super(charge); this.walletAuthorisationData = walletAuthorisationData; } public WalletAuthorisationData getWalletAuthorisationData() { return walletAuthorisationData; } public static WalletAuthorisationGatewayRequest valueOf(ChargeEntity charge, WalletAuthorisationData applePaymentData) { return new WalletAuthorisationGatewayRequest(charge, applePaymentData); } @Override public Map<String, String> getGatewayCredentials() { return charge.getGatewayAccountCredentialsEntity().getCredentials(); } }
/* * Copyright 2016-2021 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.clouddirectory.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.clouddirectory.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * PolicyAttachment JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PolicyAttachmentJsonUnmarshaller implements Unmarshaller<PolicyAttachment, JsonUnmarshallerContext> { public PolicyAttachment unmarshall(JsonUnmarshallerContext context) throws Exception { PolicyAttachment policyAttachment = new PolicyAttachment(); 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("PolicyId", targetDepth)) { context.nextToken(); policyAttachment.setPolicyId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ObjectIdentifier", targetDepth)) { context.nextToken(); policyAttachment.setObjectIdentifier(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("PolicyType", targetDepth)) { context.nextToken(); policyAttachment.setPolicyType(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 policyAttachment; } private static PolicyAttachmentJsonUnmarshaller instance; public static PolicyAttachmentJsonUnmarshaller getInstance() { if (instance == null) instance = new PolicyAttachmentJsonUnmarshaller(); return instance; } }
package com.potxxx.firstim.PO; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor @TableName("group_user") public class GroupUser implements Serializable { @TableId(value = "id") private int id; @TableField(value = "group_id") private String groupId; @TableField(value = "use_id") private String useId; }
/* * Copyright 2012-2017 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.iot.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.iot.model.*; import com.amazonaws.protocol.json.*; /** * DynamoDBv2ActionMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DynamoDBv2ActionJsonMarshaller { /** * Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall(DynamoDBv2Action dynamoDBv2Action, StructuredJsonGenerator jsonGenerator) { if (dynamoDBv2Action == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (dynamoDBv2Action.getRoleArn() != null) { jsonGenerator.writeFieldName("roleArn").writeValue(dynamoDBv2Action.getRoleArn()); } if (dynamoDBv2Action.getPutItem() != null) { jsonGenerator.writeFieldName("putItem"); PutItemInputJsonMarshaller.getInstance().marshall(dynamoDBv2Action.getPutItem(), jsonGenerator); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } } private static DynamoDBv2ActionJsonMarshaller instance; public static DynamoDBv2ActionJsonMarshaller getInstance() { if (instance == null) instance = new DynamoDBv2ActionJsonMarshaller(); return instance; } }
package com.odysee.app.tasks.lbryinc; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.AsyncTask; import java.util.HashMap; import java.util.Map; import com.odysee.app.MainActivity; import com.odysee.app.data.DatabaseHelper; import com.odysee.app.exceptions.LbryioRequestException; import com.odysee.app.exceptions.LbryioResponseException; import com.odysee.app.model.lbryinc.Subscription; import com.odysee.app.utils.Lbryio; public class ChannelSubscribeTask extends AsyncTask<Void, Void, Boolean> { private final Context context; private final String channelClaimId; private final Subscription subscription; private final ChannelSubscribeHandler handler; private Exception error; private final boolean isUnsubscribing; public ChannelSubscribeTask(Context context, String channelClaimId, Subscription subscription, boolean isUnsubscribing, ChannelSubscribeHandler handler) { this.context = context; this.channelClaimId = channelClaimId; this.subscription = subscription; this.handler = handler; this.isUnsubscribing = isUnsubscribing; } protected Boolean doInBackground(Void... params) { SQLiteDatabase db = null; try { // Save to (or delete from) local store if (context instanceof MainActivity) { db = ((MainActivity) context).getDbHelper().getWritableDatabase(); } if (db != null) { if (!isUnsubscribing) { DatabaseHelper.createOrUpdateSubscription(subscription, db); } else { DatabaseHelper.deleteSubscription(subscription, db); } } // Save with Lbryio Map<String, String> options = new HashMap<>(); options.put("claim_id", channelClaimId); if (!isUnsubscribing) { options.put("channel_name", subscription.getChannelName()); options.put("notifications_disabled", String.valueOf(subscription.isNotificationsDisabled()).toLowerCase()); } String action = isUnsubscribing ? "delete" : "new"; Object response = Lbryio.parseResponse(Lbryio.call("subscription", action, options, context)); if (!isUnsubscribing) { Lbryio.addSubscription(subscription); } else { Lbryio.removeSubscription(subscription); } } catch (LbryioRequestException | LbryioResponseException | SQLiteException ex) { error = ex; return false; } return true; } protected void onPostExecute(Boolean success) { if (handler != null) { if (success) { handler.onSuccess(); } else { handler.onError(error); } } } public interface ChannelSubscribeHandler { void onSuccess(); void onError(Exception exception); } }
/*___Generated_by_IDEA___*/ package org.jetbrains.anko; /* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */ public final class Manifest { }
/* * 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.uima.lucas.indexer; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashSet; import java.util.Properties; import java.util.Random; import java.util.Set; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriter.MaxFieldLength; import org.apache.lucene.store.LockObtainFailedException; import org.apache.uima.resource.DataResource; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.SharedResourceObject; public class IndexWriterProviderImpl implements IndexWriterProvider, SharedResourceObject{ public static final String USE_COMPOUND_FILE_FORMAT_PROPERTY = "useCompoundFileFormat"; public static final String RAMBUFFER_SIZE_PROPERTY = "RAMBufferSize"; public static final String INDEX_PATH_PROPERTY = "indexPath"; public static final String CREATE_INDEX_PROPERTY = "createIndex"; public static final String MAX_FIELD_LENGTH_PROPERTY = "maxFieldLength"; public static final String UNIQUE_INDEX_PROPERTY = "uniqueIndex"; private static Set<Integer> randomNumbers = new HashSet<Integer>(); public IndexWriter indexWriter; public IndexWriter getIndexWriter() { return indexWriter; } public void load(DataResource dataResource) throws ResourceInitializationException { Properties properties = loadProperties(dataResource); String indexPath = getIndexPath(properties); if (getUniqueIndexOrDefault(properties)) indexPath = createUniqueIndexPath(indexPath); MaxFieldLength maxFieldLength = getMaxFieldLengthOrDefault(properties); boolean createIndex = getCreateIndexOrDefault(properties); createIndexWriter(indexPath, maxFieldLength, createIndex); Double ramBufferSize = getRAMBufferSizeOrDefault(properties); Boolean useCompoundFileFormat = getUseCompoundFormatOrDefault(properties); configureIndexWriter(ramBufferSize, useCompoundFileFormat); } private Properties loadProperties(DataResource dataResource) throws ResourceInitializationException { Properties properties = new Properties(); try { properties.load(dataResource.getInputStream()); } catch (IOException e) { throw new ResourceInitializationException(e); } return properties; } private Boolean getUseCompoundFormatOrDefault(Properties properties) { String useCompoundFileFormatAsString = properties.getProperty(USE_COMPOUND_FILE_FORMAT_PROPERTY); Boolean useCompoundFileFormat = true; if( useCompoundFileFormatAsString != null ) useCompoundFileFormat = new Boolean(useCompoundFileFormatAsString); return useCompoundFileFormat; } private String getIndexPath(Properties properties){ return properties.getProperty(INDEX_PATH_PROPERTY); } private synchronized int createRandom() { Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(1000000); while (randomNumbers.contains(randomInt)) { randomInt = randomGenerator.nextInt(1000000); } randomNumbers.add(randomInt); return randomInt; } private String createUniqueIndexPath(String indexPath){ String uniqueIndexPath = indexPath + "-" + getHostName() + "-" + getPID() + "-" + createRandom(); return uniqueIndexPath; } private Boolean getUniqueIndexOrDefault(Properties properties) { String uniqueIndexAsString = properties.getProperty(UNIQUE_INDEX_PROPERTY); Boolean uniqueIndex = false; if( uniqueIndexAsString != null ) uniqueIndex = new Boolean(uniqueIndexAsString); return uniqueIndex; } private Double getRAMBufferSizeOrDefault(Properties properties) { String ramBufferSizeAsString = properties.getProperty(RAMBUFFER_SIZE_PROPERTY); Double ramBufferSize = IndexWriter.DEFAULT_RAM_BUFFER_SIZE_MB; if( ramBufferSizeAsString != null ) ramBufferSize = new Double(ramBufferSizeAsString); return ramBufferSize; } private MaxFieldLength getMaxFieldLengthOrDefault(Properties properties) { String maxFieldLengthAsString = properties.getProperty(MAX_FIELD_LENGTH_PROPERTY); if( maxFieldLengthAsString == null ) return IndexWriter.MaxFieldLength.UNLIMITED; else{ Integer maxFieldLength = new Integer(maxFieldLengthAsString); return new MaxFieldLength(maxFieldLength); } } private boolean getCreateIndexOrDefault(Properties properties) { String createIndexAsString = properties.getProperty(CREATE_INDEX_PROPERTY); if (createIndexAsString != null) { return Boolean.parseBoolean(createIndexAsString); } else { // Thats the default before this property was introduced return true; } } private void createIndexWriter(String indexPath, MaxFieldLength maxFieldLength, boolean create) throws ResourceInitializationException { try { indexWriter = new IndexWriter(indexPath, new StandardAnalyzer(), create, maxFieldLength); } catch (CorruptIndexException e) { throw new ResourceInitializationException(e); } catch (LockObtainFailedException e) { throw new ResourceInitializationException(e); } catch (IOException e) { throw new ResourceInitializationException(e); } } private void configureIndexWriter(Double ramBufferSize, Boolean useCompoundFileFormat) { indexWriter.setRAMBufferSizeMB(ramBufferSize); indexWriter.setUseCompoundFile(true); } private String getPID() { String id = ManagementFactory.getRuntimeMXBean().getName(); return id.substring(0, id.indexOf("@")); } private String getHostName() { InetAddress address; String hostName; try { address = InetAddress.getLocalHost(); hostName = address.getHostName(); } catch (UnknownHostException e) { throw new IllegalStateException(e); } return hostName; } }
/* * Copyright (c) 2019 Gili Tzabari * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 */ package com.github.cowwoc.requirements.java.internal.extension; import com.github.cowwoc.requirements.java.ValidationFailure; import com.github.cowwoc.requirements.java.extension.ExtensibleNumberValidator; import com.github.cowwoc.requirements.java.extension.ExtensiblePrimitiveValidator; import java.util.List; /** * An {@code ExtensiblePrimitiveNumberValidator} that does nothing. A validator that ignores all subsequent * failures because they are guaranteed to fail and would add any value to the end-user. For example, an * attempt was made to dereference null or cast the value to an incompatible type. * * @param <S> the type of validator returned by the methods * @param <T> the type of the value being validated */ public abstract class AbstractPrimitiveNumberValidatorNoOp<S, T extends Number & Comparable<? super T>> extends AbstractObjectValidatorNoOp<S, T> implements ExtensiblePrimitiveValidator<S, T>, ExtensibleNumberValidator<S, T> { /** * @param failures the list of validation failures * @throws AssertionError if {@code failures} is null */ public AbstractPrimitiveNumberValidatorNoOp(List<ValidationFailure> failures) { super(failures); } @Override @Deprecated public S isNull() { return getThis(); } @Override @Deprecated public S isNotNull() { return getThis(); } @Override public S isLessThan(T value) { return getThis(); } @Override public S isLessThan(T value, String name) { return getThis(); } @Override public S isLessThanOrEqualTo(T value) { return getThis(); } @Override public S isLessThanOrEqualTo(T value, String name) { return getThis(); } @Override public S isGreaterThan(T value) { return getThis(); } @Override public S isGreaterThan(T value, String name) { return getThis(); } @Override public S isGreaterThanOrEqualTo(T value) { return getThis(); } @Override public S isGreaterThanOrEqualTo(T value, String name) { return getThis(); } @Override public S isComparableTo(T expected) { return getThis(); } @Override public S isComparableTo(T expected, String name) { return getThis(); } @Override public S isNotComparableTo(T value) { return getThis(); } @Override public S isNotComparableTo(T other, String name) { return getThis(); } @Override public S isBetween(T startInclusive, T endExclusive) { return getThis(); } @Override public S isBetweenClosed(T startInclusive, T endInclusive) { return getThis(); } @Override public S isNegative() { return getThis(); } @Override public S isNotNegative() { return getThis(); } @Override public S isZero() { return getThis(); } @Override public S isNotZero() { return getThis(); } @Override public S isPositive() { return getThis(); } @Override public S isNotPositive() { return getThis(); } @Override public S isWholeNumber() { return getThis(); } @Override public S isNotWholeNumber() { return getThis(); } @Override public S isMultipleOf(T divisor) { return getThis(); } @Override public S isMultipleOf(T divisor, String name) { return getThis(); } @Override public S isNotMultipleOf(T divisor) { return getThis(); } @Override public S isNotMultipleOf(T divisor, String name) { return getThis(); } }
package cn.leancloud.chatkit.viewholder; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; /** * Created by wli on 15/8/25. * RecyclerView.ViewHolder 的公共类,做了一些封装。目的: * ViewHolder 与 Adapter 解耦,和 ViewHolder 相关的逻辑都放到 ViewHolder 里边,避免 Adapter 有相关逻辑 */ public abstract class LCIMCommonViewHolder<T> extends RecyclerView.ViewHolder { public LCIMCommonViewHolder(Context context, ViewGroup root, int layoutRes) { super(LayoutInflater.from(context).inflate(layoutRes, root, false)); } public Context getContext() { return itemView.getContext(); } /** * 用给定的 data 对 holder 的 view 进行赋值 */ public abstract void bindData(T t); public void setData(T t) { bindData(t); } /** * 因为 CommonListAdapter 里边无法对于未知类型的 Class 进行实例化 * 所以需要如果想用 CommonListAdapter,必须要在对应的 CommonViewHolder 实例化一个 HOLDER_CREATOR * 注意:public static ViewHolderCreator HOLDER_CREATOR,名字与修饰符都不能更改,否则有可能引发失败 * 具体样例可参见 DiscoverItemHolder * 如果不使用 CommonListAdapter,则不需要实例化 ViewHolderCreator * * @param <VH> */ public interface ViewHolderCreator<VH extends LCIMCommonViewHolder> { public VH createByViewGroupAndType(ViewGroup parent, int viewType); } }
package org.csuc.service.analyse; import com.auth0.jwk.JwkException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.csuc.client.Client; import org.csuc.dao.AnalyseDAO; import org.csuc.dao.impl.AnalyseDAOImpl; import org.csuc.entities.Analyse; import org.csuc.utils.authorization.Authoritzation; import org.csuc.utils.parser.ParserType; import org.csuc.utils.response.ResponseEchoes; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.util.List; import java.util.Objects; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; /** * @author amartinez */ @Path("/analyse") public class Type { private static Logger logger = LogManager.getLogger(Type.class); @Context private UriInfo uriInfo; @Context private HttpServletRequest servletRequest; @Inject private Client client; @GET @Path("/user/{user}/type/{type}") @Produces(APPLICATION_JSON + "; charset=utf-8") public Response getParserByType(@PathParam("user") String user, @PathParam("type") String type, @DefaultValue("50") @QueryParam("pagesize") int pagesize, @DefaultValue("0") @QueryParam("page") int page, @HeaderParam("Authorization") String authorization) { if (Objects.isNull(user)) { throw new WebApplicationException( Response.status(Response.Status.BAD_REQUEST) .entity("user is mandatory") .build() ); } if (Objects.isNull(type)) { throw new WebApplicationException( Response.status(Response.Status.BAD_REQUEST) .entity("type is mandatory") .build() ); } ParserType parserType = ParserType.convert(type); if (Objects.isNull(parserType)) { throw new WebApplicationException( Response.status(Response.Status.BAD_REQUEST) .entity("invalid type") .build() ); } Authoritzation authoritzation = new Authoritzation(user, authorization.split("\\s")[1]); try { authoritzation.execute(); } catch (JwkException e) { return Response.status(Response.Status.UNAUTHORIZED).build(); } try { AnalyseDAO analyseDAO = new AnalyseDAOImpl(Analyse.class, client.getDatastore()); List<Analyse> queryResults = analyseDAO.getByType(parserType, user, page, pagesize); double count = new Long(analyseDAO.countByType(parserType, user)).doubleValue(); ResponseEchoes response = new ResponseEchoes(type, (int) count, (int) Math.ceil(count / new Long(pagesize).doubleValue()), queryResults.size(), queryResults); logger.debug(response); return Response.status(Response.Status.ACCEPTED).entity(response).build(); } catch (Exception e) { logger.error(e); return Response.status(Response.Status.BAD_REQUEST).build(); } } }