code
stringlengths
10
749k
repo_name
stringlengths
5
108
path
stringlengths
7
333
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
10
749k
/* * Copyright (c) 1997, 2009, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 com.sun.crypto.provider; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactorySpi; import javax.crypto.spec.DESedeKeySpec; import java.security.InvalidKeyException; import java.security.spec.KeySpec; import java.security.spec.InvalidKeySpecException; /** * This class implements the DES-EDE key factory of the Sun provider. * * @author Jan Luehe * */ public final class DESedeKeyFactory extends SecretKeyFactorySpi { /** * Empty constructor */ public DESedeKeyFactory() { } /** * Generates a <code>SecretKey</code> object from the provided key * specification (key material). * * @param keySpec the specification (key material) of the secret key * * @return the secret key * * @exception InvalidKeySpecException if the given key specification * is inappropriate for this key factory to produce a public key. */ protected SecretKey engineGenerateSecret(KeySpec keySpec) throws InvalidKeySpecException { DESedeKey desEdeKey = null; try { if (keySpec instanceof DESedeKeySpec) { DESedeKeySpec desEdeKeySpec = (DESedeKeySpec)keySpec; desEdeKey = new DESedeKey(desEdeKeySpec.getKey()); } else { throw new InvalidKeySpecException ("Inappropriate key specification"); } } catch (InvalidKeyException e) { } return desEdeKey; } /** * Returns a specification (key material) of the given key * in the requested format. * * @param key the key * * @param keySpec the requested format in which the key material shall be * returned * * @return the underlying key specification (key material) in the * requested format * * @exception InvalidKeySpecException if the requested key specification is * inappropriate for the given key, or the given key cannot be processed * (e.g., the given key has an unrecognized algorithm or format). */ protected KeySpec engineGetKeySpec(SecretKey key, Class keySpec) throws InvalidKeySpecException { try { if ((key instanceof SecretKey) && (key.getAlgorithm().equalsIgnoreCase("DESede")) && (key.getFormat().equalsIgnoreCase("RAW"))) { // Check if requested key spec is amongst the valid ones if (DESedeKeySpec.class.isAssignableFrom(keySpec)) { return new DESedeKeySpec(key.getEncoded()); } else { throw new InvalidKeySpecException ("Inappropriate key specification"); } } else { throw new InvalidKeySpecException ("Inappropriate key format/algorithm"); } } catch (InvalidKeyException e) { throw new InvalidKeySpecException("Secret key has wrong size"); } } /** * Translates a <code>SecretKey</code> object, whose provider may be * unknown or potentially untrusted, into a corresponding * <code>SecretKey</code> object of this key factory. * * @param key the key whose provider is unknown or untrusted * * @return the translated key * * @exception InvalidKeyException if the given key cannot be processed by * this key factory. */ protected SecretKey engineTranslateKey(SecretKey key) throws InvalidKeyException { try { if ((key != null) && (key.getAlgorithm().equalsIgnoreCase("DESede")) && (key.getFormat().equalsIgnoreCase("RAW"))) { // Check if key originates from this factory if (key instanceof com.sun.crypto.provider.DESedeKey) { return key; } // Convert key to spec DESedeKeySpec desEdeKeySpec = (DESedeKeySpec)engineGetKeySpec(key, DESedeKeySpec.class); // Create key from spec, and return it return engineGenerateSecret(desEdeKeySpec); } else { throw new InvalidKeyException ("Inappropriate key format/algorithm"); } } catch (InvalidKeySpecException e) { throw new InvalidKeyException("Cannot translate key"); } } }
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java
Java
mit
5,724
package p; class Generic<E> { enum A { ONE { A getSquare() { return ONE; } }, TWO { A getSquare() { return MANY; } }, MANY { A getSquare() { return MANY; } }; abstract A getSquare(); } }
kaloyan-raev/che
plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/resources/RenameVirtualMethodInClass/testEnum2/in/A.java
Java
epl-1.0
372
/* * Copyright 2010-2015 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.cloudfront_2012_03_15.model; import com.amazonaws.AmazonServiceException; /** * <p> * You have exceeded the maximum number of allowable InProgress * invalidation batch requests, or invalidation objects. * </p> */ public class TooManyInvalidationsInProgressException extends AmazonServiceException { private static final long serialVersionUID = 1L; /** * Constructs a new TooManyInvalidationsInProgressException with the specified error * message. * * @param message Describes the error encountered. */ public TooManyInvalidationsInProgressException(String message) { super(message); } }
priyatransbit/aws-sdk-java
aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront_2012_03_15/model/TooManyInvalidationsInProgressException.java
Java
apache-2.0
1,286
/** * 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.thrift; import java.io.Serializable; import java.nio.ByteBuffer; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.Collection; public final class TBaseHelper { private TBaseHelper(){} private static final Comparator comparator = new NestedStructureComparator(); public static int compareTo(Object o1, Object o2) { if (o1 instanceof Comparable) { return compareTo((Comparable)o1, (Comparable)o2); } else if (o1 instanceof List) { return compareTo((List)o1, (List)o2); } else if (o1 instanceof Set) { return compareTo((Set)o1, (Set)o2); } else if (o1 instanceof Map) { return compareTo((Map)o1, (Map)o2); } else if (o1 instanceof byte[]) { return compareTo((byte[])o1, (byte[])o2); } else { throw new IllegalArgumentException("Cannot compare objects of type " + o1.getClass()); } } public static int compareTo(boolean a, boolean b) { return Boolean.valueOf(a).compareTo(b); } public static int compareTo(byte a, byte b) { if (a < b) { return -1; } else if (b < a) { return 1; } else { return 0; } } public static int compareTo(short a, short b) { if (a < b) { return -1; } else if (b < a) { return 1; } else { return 0; } } public static int compareTo(int a, int b) { if (a < b) { return -1; } else if (b < a) { return 1; } else { return 0; } } public static int compareTo(long a, long b) { if (a < b) { return -1; } else if (b < a) { return 1; } else { return 0; } } public static int compareTo(double a, double b) { if (a < b) { return -1; } else if (b < a) { return 1; } else { return 0; } } public static int compareTo(String a, String b) { return a.compareTo(b); } public static int compareTo(byte[] a, byte[] b) { int sizeCompare = compareTo(a.length, b.length); if (sizeCompare != 0) { return sizeCompare; } for (int i = 0; i < a.length; i++) { int byteCompare = compareTo(a[i], b[i]); if (byteCompare != 0) { return byteCompare; } } return 0; } public static int compareTo(Comparable a, Comparable b) { return a.compareTo(b); } public static int compareTo(List a, List b) { int lastComparison = compareTo(a.size(), b.size()); if (lastComparison != 0) { return lastComparison; } for (int i = 0; i < a.size(); i++) { lastComparison = comparator.compare(a.get(i), b.get(i)); if (lastComparison != 0) { return lastComparison; } } return 0; } public static int compareTo(Set a, Set b) { int lastComparison = compareTo(a.size(), b.size()); if (lastComparison != 0) { return lastComparison; } SortedSet sortedA = new TreeSet(comparator); sortedA.addAll(a); SortedSet sortedB = new TreeSet(comparator); sortedB.addAll(b); Iterator iterA = sortedA.iterator(); Iterator iterB = sortedB.iterator(); // Compare each item. while (iterA.hasNext() && iterB.hasNext()) { lastComparison = comparator.compare(iterA.next(), iterB.next()); if (lastComparison != 0) { return lastComparison; } } return 0; } public static int compareTo(Map a, Map b) { int lastComparison = compareTo(a.size(), b.size()); if (lastComparison != 0) { return lastComparison; } // Sort a and b so we can compare them. SortedMap sortedA = new TreeMap(comparator); sortedA.putAll(a); Iterator<Map.Entry> iterA = sortedA.entrySet().iterator(); SortedMap sortedB = new TreeMap(comparator); sortedB.putAll(b); Iterator<Map.Entry> iterB = sortedB.entrySet().iterator(); // Compare each item. while (iterA.hasNext() && iterB.hasNext()) { Map.Entry entryA = iterA.next(); Map.Entry entryB = iterB.next(); lastComparison = comparator.compare(entryA.getKey(), entryB.getKey()); if (lastComparison != 0) { return lastComparison; } lastComparison = comparator.compare(entryA.getValue(), entryB.getValue()); if (lastComparison != 0) { return lastComparison; } } return 0; } /** * Comparator to compare items inside a structure (e.g. a list, set, or map). */ private static class NestedStructureComparator implements Comparator, Serializable { public int compare(Object oA, Object oB) { if (oA == null && oB == null) { return 0; } else if (oA == null) { return -1; } else if (oB == null) { return 1; } else if (oA instanceof List) { return compareTo((List)oA, (List)oB); } else if (oA instanceof Set) { return compareTo((Set)oA, (Set)oB); } else if (oA instanceof Map) { return compareTo((Map)oA, (Map)oB); } else if (oA instanceof byte[]) { return compareTo((byte[])oA, (byte[])oB); } else { return compareTo((Comparable)oA, (Comparable)oB); } } } public static void toString(Collection<ByteBuffer> bbs, StringBuilder sb) { Iterator<ByteBuffer> it = bbs.iterator(); if (!it.hasNext()) { sb.append("[]"); } else { sb.append("["); while (true) { ByteBuffer bb = it.next(); org.apache.thrift.TBaseHelper.toString(bb, sb); if (!it.hasNext()) { sb.append("]"); return; } else { sb.append(", "); } } } } public static void toString(ByteBuffer bb, StringBuilder sb) { byte[] buf = bb.array(); int arrayOffset = bb.arrayOffset(); int offset = arrayOffset + bb.position(); int origLimit = arrayOffset + bb.limit(); int limit = (origLimit - offset > 128) ? offset + 128 : origLimit; for (int i = offset; i < limit; i++) { if (i > offset) { sb.append(" "); } sb.append(paddedByteString(buf[i])); } if (origLimit != limit) { sb.append("..."); } } public static String paddedByteString(byte b) { int extended = (b | 0x100) & 0x1ff; return Integer.toHexString(extended).toUpperCase().substring(1); } public static byte[] byteBufferToByteArray(ByteBuffer byteBuffer) { if (wrapsFullArray(byteBuffer)) { return byteBuffer.array(); } byte[] target = new byte[byteBuffer.remaining()]; byteBufferToByteArray(byteBuffer, target, 0); return target; } public static boolean wrapsFullArray(ByteBuffer byteBuffer) { return byteBuffer.hasArray() && byteBuffer.position() == 0 && byteBuffer.arrayOffset() == 0 && byteBuffer.remaining() == byteBuffer.capacity(); } public static int byteBufferToByteArray(ByteBuffer byteBuffer, byte[] target, int offset) { int remaining = byteBuffer.remaining(); System.arraycopy(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), target, offset, remaining); return remaining; } public static ByteBuffer rightSize(ByteBuffer in) { if (in == null) { return null; } if (wrapsFullArray(in)) { return in; } return ByteBuffer.wrap(byteBufferToByteArray(in)); } public static ByteBuffer copyBinary(final ByteBuffer orig) { if (orig == null) { return null; } ByteBuffer copy = ByteBuffer.wrap(new byte[orig.remaining()]); if (orig.hasArray()) { System.arraycopy(orig.array(), orig.arrayOffset() + orig.position(), copy.array(), 0, orig.remaining()); } else { orig.slice().get(copy.array()); } return copy; } public static byte[] copyBinary(final byte[] orig) { if (orig == null) { return null; } byte[] copy = new byte[orig.length]; System.arraycopy(orig, 0, copy, 0, orig.length); return copy; } public static int hashCode(long value) { int low = (int) value; int high = (int) (value >>> 32); return high * 127 + low; } public static int hashCode(double value) { return hashCode(Double.doubleToRawLongBits(value)); } }
jcgruenhage/dendrite
vendor/src/github.com/apache/thrift/lib/java/src/org/apache/thrift/TBaseHelper.java
Java
apache-2.0
9,155
/* * Copyright (C) 2013 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 com.example.dagger.activitygraphs; import android.content.Context; import com.example.dagger.activitygraphs.ui.ActivityTitleController; import com.example.dagger.activitygraphs.ui.HomeActivity; import com.example.dagger.activitygraphs.ui.HomeFragment; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; /** * This module represents objects which exist only for the scope of a single activity. We can * safely create singletons using the activity instance because the entire object graph will only * ever exist inside of that activity. */ @Module( injects = { HomeActivity.class, HomeFragment.class }, addsTo = AndroidModule.class, library = true ) public class ActivityModule { private final DemoBaseActivity activity; public ActivityModule(DemoBaseActivity activity) { this.activity = activity; } /** * Allow the activity context to be injected but require that it be annotated with * {@link ForActivity @ForActivity} to explicitly differentiate it from application context. */ @Provides @Singleton @ForActivity Context provideActivityContext() { return activity; } @Provides @Singleton ActivityTitleController provideTitleController() { return new ActivityTitleController(activity); } }
CyanogenMod/android_external_square_dagger
examples/android-activity-graphs/src/main/java/com/example/dagger/activitygraphs/ActivityModule.java
Java
apache-2.0
1,897
/* * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * THIS FILE WAS MODIFIED BY SUN MICROSYSTEMS, INC. */ package com.sun.xml.internal.fastinfoset.vocab; public abstract class Vocabulary { public static final int RESTRICTED_ALPHABET = 0; public static final int ENCODING_ALGORITHM = 1; public static final int PREFIX = 2; public static final int NAMESPACE_NAME = 3; public static final int LOCAL_NAME = 4; public static final int OTHER_NCNAME = 5; public static final int OTHER_URI = 6; public static final int ATTRIBUTE_VALUE = 7; public static final int OTHER_STRING = 8; public static final int CHARACTER_CONTENT_CHUNK = 9; public static final int ELEMENT_NAME = 10; public static final int ATTRIBUTE_NAME = 11; protected boolean _hasInitialReadOnlyVocabulary; protected String _referencedVocabularyURI; public boolean hasInitialVocabulary() { return _hasInitialReadOnlyVocabulary; } protected void setInitialReadOnlyVocabulary(boolean hasInitialReadOnlyVocabulary) { _hasInitialReadOnlyVocabulary = hasInitialReadOnlyVocabulary; } public boolean hasExternalVocabulary() { return _referencedVocabularyURI != null; } public String getExternalVocabularyURI() { return _referencedVocabularyURI; } protected void setExternalVocabularyURI(String referencedVocabularyURI) { _referencedVocabularyURI = referencedVocabularyURI; } }
rokn/Count_Words_2015
testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/xml/internal/fastinfoset/vocab/Vocabulary.java
Java
mit
2,636
/* * 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.client.ml; import org.elasticsearch.client.ml.job.config.MlFilter; import org.elasticsearch.client.ml.job.config.MlFilterTests; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.AbstractXContentTestCase; public class PutFilterRequestTests extends AbstractXContentTestCase<PutFilterRequest> { @Override protected PutFilterRequest createTestInstance() { return new PutFilterRequest(MlFilterTests.createRandom()); } @Override protected PutFilterRequest doParseInstance(XContentParser parser) { return new PutFilterRequest(MlFilter.PARSER.apply(parser, null).build()); } @Override protected boolean supportsUnknownFields() { return false; } }
gingerwizard/elasticsearch
client/rest-high-level/src/test/java/org/elasticsearch/client/ml/PutFilterRequestTests.java
Java
apache-2.0
1,557
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.tests.utils; import org.apache.cassandra.service.CassandraDaemon; import org.apache.ignite.IgniteLogger; import org.apache.ignite.lifecycle.LifecycleBean; import org.apache.ignite.lifecycle.LifecycleEventType; import org.apache.ignite.resources.LoggerResource; /** * Implementation of {@link LifecycleBean} to start embedded Cassandra instance on Ignite cluster startup */ public class CassandraLifeCycleBean implements LifecycleBean { /** System property specifying Cassandra jmx port */ private static final String CASSANDRA_JMX_PORT_PROP = "cassandra.jmx.local.port"; /** System property specifying Cassandra YAML config file */ private static final String CASSANDRA_CONFIG_PROP = "cassandra.config"; /** Prefix for file path syntax */ private static final String FILE_PREFIX = "file:///"; /** Auto-injected logger instance. */ @LoggerResource private IgniteLogger log; /** Instance of embedded Cassandra database */ private CassandraDaemon embeddedCassandraDaemon; /** JMX port for embedded Cassandra instance */ private String jmxPort; /** YAML config file for embedded Cassandra */ private String cassandraCfgFile; /** * Returns JMX port for embedded Cassandra * @return JMX port */ public String getJmxPort() { return jmxPort; } /** * Setter for embedded Cassandra JMX port * @param jmxPort embedded Cassandra JMX port */ public void setJmxPort(String jmxPort) { this.jmxPort = jmxPort; } /** * Returns embedded Cassandra YAML config file * @return YAML config file */ public String getCassandraConfigFile() { return cassandraCfgFile; } /** * Setter for embedded Cassandra YAML config file * @param cassandraCfgFile YAML config file */ public void setCassandraConfigFile(String cassandraCfgFile) { this.cassandraCfgFile = cassandraCfgFile; } /** {@inheritDoc} */ @Override public void onLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.BEFORE_NODE_START) startEmbeddedCassandra(); else if (evt == LifecycleEventType.BEFORE_NODE_STOP) stopEmbeddedCassandra(); } /** * Starts embedded Cassandra instance */ private void startEmbeddedCassandra() { if (log != null) { log.info("-------------------------------"); log.info("| Starting embedded Cassandra |"); log.info("-------------------------------"); } try { if (jmxPort != null) System.setProperty(CASSANDRA_JMX_PORT_PROP, jmxPort); if (cassandraCfgFile != null) System.setProperty(CASSANDRA_CONFIG_PROP, FILE_PREFIX + cassandraCfgFile); embeddedCassandraDaemon = new CassandraDaemon(true); embeddedCassandraDaemon.init(null); embeddedCassandraDaemon.start(); } catch (Exception e) { throw new RuntimeException("Failed to start embedded Cassandra", e); } if (log != null) { log.info("------------------------------"); log.info("| Embedded Cassandra started |"); log.info("------------------------------"); } } /** * Stops embedded Cassandra instance */ private void stopEmbeddedCassandra() { if (log != null) { log.info("-------------------------------"); log.info("| Stopping embedded Cassandra |"); log.info("-------------------------------"); } if (embeddedCassandraDaemon != null) { try { embeddedCassandraDaemon.deactivate(); } catch (Throwable e) { throw new RuntimeException("Failed to stop embedded Cassandra", e); } } if (log != null) { log.info("------------------------------"); log.info("| Embedded Cassandra stopped |"); log.info("------------------------------"); } } }
irudyak/ignite
modules/cassandra/store/src/test/java/org/apache/ignite/tests/utils/CassandraLifeCycleBean.java
Java
apache-2.0
4,951
/* * Copyright 2014 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.internal.android; import android.util.Base64; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JsonUtils { private static Pattern jsonDate = Pattern.compile("/Date\\((\\d*)\\)/"); /** * Converts a Json string to a Java Date object. Currently supports 2 types: * - "<long>" * - "/Date(<long>)/" * * @param date String input of date of the the supported types. * @return Date object or null if invalid input. * * @throws NumberFormatException If date is not a proper long or has an illegal format. */ public static Date stringToDate(String date) { if (date == null || date.length() == 0) return null; Matcher matcher = jsonDate.matcher(date); if (matcher.matches()) { return new Date(Long.parseLong(matcher.group(1))); } else { return new Date(Long.parseLong(date)); } } /** * Converts a Json string to byte[]. String must be Base64 encoded. * * @param str Base 64 encoded bytes. * @return Byte array or empty byte array */ public static byte[] stringToBytes(String str) { if (str == null || str.length() == 0) return new byte[0]; return Base64.decode(str, Base64.DEFAULT); } }
yuuki1224/realm-java
realm/src/main/java/io/realm/internal/android/JsonUtils.java
Java
apache-2.0
1,922
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.tableexists; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; import org.pentaho.di.trans.step.StepDataInterface; /** * @author Samatar * @since 03-Juin-2008 * */ public class TableExistsData extends BaseStepData implements StepDataInterface { public Database db; public int indexOfTablename; public String realSchemaname; public RowMetaInterface outputRowMeta; public TableExistsData() { super(); indexOfTablename = -1; realSchemaname = null; db = null; } }
tkafalas/pentaho-kettle
engine/src/main/java/org/pentaho/di/trans/steps/tableexists/TableExistsData.java
Java
apache-2.0
1,537
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.quickstart.xml.upload; import java.io.InputStream; import java.io.Serializable; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.Produces; import javax.inject.Inject; import javax.inject.Named; import org.jboss.as.quickstart.xml.Book; import org.jboss.as.quickstart.xml.Errors; import org.jboss.as.quickstart.xml.XMLParser; /** * Backing bean to provide example with required logic to parse provided XML file.<br> * * @author baranowb * */ /* * Annotated as: - SessionScope bean to tie its lifecycle to session. This is required to make it shared between UploadServlet * invocation and JSF actions. */ @SessionScoped public class FileUploadBean implements Serializable { /** * */ private static final long serialVersionUID = -4542914921835861304L; // data, catalog which is displayed in h:dataTable private List<Book> catalog; @Inject private Errors errors; /* * Inject XMLParsor with 'Catalog' as type. Instance is created by container. Implementation alternative is controlled in * beans.xml */ @Inject private XMLParser xmlParser; /** * Getter for books catalog. */ @Produces @Named public List<Book> getCatalog() { return catalog; } /** * Action method invoked from UploadServlet once it parses request with 'multipart/form-data' form data and fetches uploaded * file. */ public void parseUpload(InputStream is) { try { // Trigger parser and clear errors this.errors.getErrorMessages().clear(); this.catalog = xmlParser.parse(is); } catch (Exception e) { this.errors.addErrorMessage("warning", e); return; } } }
rfhl93/quickstart
xml-jaxp/src/main/java/org/jboss/as/quickstart/xml/upload/FileUploadBean.java
Java
apache-2.0
2,615
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.core; import android.app.Application; import android.content.Context; import android.content.res.Resources; /** * This class is deprecated. * * XWalkApplication is to support cross package resource loading. * It provides method to allow overriding getResources() behavior. */ public class XWalkApplication extends Application { private static XWalkApplication gApp = null; private Resources mRes = null; @Override public void onCreate(){ super.onCreate(); gApp = this; } /** * In embedded mode, returns a Resources instance for the application's package. In shared mode, * returns a mised Resources instance that can get resources not only from the application but * also from the shared library across package. */ @Override public Resources getResources() { return mRes == null ? super.getResources() : mRes; } void addResource(Resources res) { if (mRes != null) return; mRes = new XWalkMixedResources(super.getResources(), res); } static XWalkApplication getApplication() { return gApp; } }
jpike88/crosswalk
runtime/android/core/src/org/xwalk/core/XWalkApplication.java
Java
bsd-3-clause
1,309
/* * The Trustees of Columbia University in the City of New York * licenses this file to you under the Educational Community License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the * License at: * * http://opensource.org/licenses/ecl2.txt * * 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.sakaiproject.delegatedaccess.jobs; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import lombok.Getter; import lombok.Setter; import org.apache.log4j.Logger; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.StatefulJob; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.delegatedaccess.logic.ProjectLogic; import org.sakaiproject.delegatedaccess.logic.SakaiProxy; import org.sakaiproject.delegatedaccess.model.NodeModel; import org.sakaiproject.delegatedaccess.util.DelegatedAccessConstants; import org.sakaiproject.delegatedaccess.util.DelegatedAccessMutableTreeNode; import org.sakaiproject.api.app.scheduler.ScheduledInvocationCommand; /** * This is the job that will populate the shopping period access tree. It should be ran every morning (sometime after midnight). * This is used to open and close the shopping period for sites based on their open and close dates. * * @author Bryan Holladay * */ public class DelegatedAccessShoppingPeriodJob implements StatefulJob, ScheduledInvocationCommand { private static final Logger log = Logger.getLogger(DelegatedAccessShoppingPeriodJob.class); @Getter @Setter private ProjectLogic projectLogic; @Getter @Setter private SakaiProxy sakaiProxy; public void init() { } public void execute(JobExecutionContext arg0) throws JobExecutionException { execute(""); } public void execute(String nodeId){ if(nodeId != null){ nodeId = nodeId.trim(); } try{ Map<String, String> errors = new HashMap<String, String>(); log.info("DelegatedAccessShoppingPeriodJob started. NodeId: " + nodeId); long startTime = System.currentTimeMillis(); SecurityAdvisor advisor = sakaiProxy.addSiteUpdateSecurityAdvisor(); DefaultMutableTreeNode treeNode = null; if(nodeId == null || "".equals(nodeId)){ TreeModel treeModel = projectLogic.getEntireTreePlusUserPerms(DelegatedAccessConstants.SHOPPING_PERIOD_USER); if (treeModel != null && treeModel.getRoot() != null) { treeNode = (DefaultMutableTreeNode) treeModel.getRoot(); } }else{ NodeModel nodeModel = projectLogic.getNodeModel(nodeId, DelegatedAccessConstants.SHOPPING_PERIOD_USER); treeNode = new DelegatedAccessMutableTreeNode(); treeNode.setUserObject(nodeModel); } if(treeNode != null){ projectLogic.updateShoppingPeriodSettings(treeNode); sakaiProxy.popSecurityAdvisor(advisor); log.info("DelegatedAccessShoppingPeriodJob finished in " + (System.currentTimeMillis() - startTime) + " ms"); if(errors.size() > 0){ String warning = "The following sites had errors: \n\n"; for(Entry entry : errors.entrySet()){ warning += entry.getKey() + ": " + entry.getValue() + "\n"; } log.warn(warning); sakaiProxy.sendEmail("DelegatedAccessShoppingPeriodJob error", warning); } } }catch (Exception e) { log.error(e.getMessage(), e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); sakaiProxy.sendEmail("DelegatedAccessShoppingPeriodJob error", sw.toString()); } } }
sakai-mirror/delegatedaccess
impl/src/java/org/sakaiproject/delegatedaccess/jobs/DelegatedAccessShoppingPeriodJob.java
Java
apache-2.0
3,935
/* * 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.common.bytes; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefIterator; import org.elasticsearch.common.io.stream.StreamInput; import java.io.EOFException; import java.io.IOException; /** * A StreamInput that reads off a {@link BytesRefIterator}. This is used to provide * generic stream access to {@link BytesReference} instances without materializing the * underlying bytes reference. */ final class BytesReferenceStreamInput extends StreamInput { private final BytesRefIterator iterator; private int sliceOffset; private BytesRef slice; private final int length; // the total size of the stream private int offset; // the current position of the stream BytesReferenceStreamInput(BytesRefIterator iterator, final int length) throws IOException { this.iterator = iterator; this.slice = iterator.next(); this.length = length; this.offset = 0; this.sliceOffset = 0; } @Override public byte readByte() throws IOException { if (offset >= length) { throw new EOFException(); } maybeNextSlice(); byte b = slice.bytes[slice.offset + (sliceOffset++)]; offset++; return b; } private void maybeNextSlice() throws IOException { while (sliceOffset == slice.length) { slice = iterator.next(); sliceOffset = 0; if (slice == null) { throw new EOFException(); } } } @Override public void readBytes(byte[] b, int bOffset, int len) throws IOException { if (offset + len > length) { throw new IndexOutOfBoundsException("Cannot read " + len + " bytes from stream with length " + length + " at offset " + offset); } read(b, bOffset, len); } @Override public int read() throws IOException { if (offset >= length) { return -1; } return Byte.toUnsignedInt(readByte()); } @Override public int read(final byte[] b, final int bOffset, final int len) throws IOException { if (offset >= length) { return -1; } final int numBytesToCopy = Math.min(len, length - offset); int remaining = numBytesToCopy; // copy the full length or the remaining part int destOffset = bOffset; while (remaining > 0) { maybeNextSlice(); final int currentLen = Math.min(remaining, slice.length - sliceOffset); assert currentLen > 0 : "length has to be > 0 to make progress but was: " + currentLen; System.arraycopy(slice.bytes, slice.offset + sliceOffset, b, destOffset, currentLen); destOffset += currentLen; remaining -= currentLen; sliceOffset += currentLen; offset += currentLen; assert remaining >= 0 : "remaining: " + remaining; } return numBytesToCopy; } @Override public void close() throws IOException { // do nothing } @Override public int available() throws IOException { return length - offset; } @Override protected void ensureCanReadBytes(int bytesToRead) throws EOFException { int bytesAvailable = length - offset; if (bytesAvailable < bytesToRead) { throw new EOFException("tried to read: " + bytesToRead + " bytes but only " + bytesAvailable + " remaining"); } } @Override public long skip(long n) throws IOException { final int skip = (int) Math.min(Integer.MAX_VALUE, n); final int numBytesSkipped = Math.min(skip, length - offset); int remaining = numBytesSkipped; while (remaining > 0) { maybeNextSlice(); int currentLen = Math.min(remaining, slice.length - (slice.offset + sliceOffset)); remaining -= currentLen; sliceOffset += currentLen; offset += currentLen; assert remaining >= 0 : "remaining: " + remaining; } return numBytesSkipped; } int getOffset() { return offset; } }
fernandozhu/elasticsearch
core/src/main/java/org/elasticsearch/common/bytes/BytesReferenceStreamInput.java
Java
apache-2.0
4,970
/* * Copyright (c) 1996, 2004, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 sun.net.www.protocol.gopher; import java.io.*; import java.util.*; import java.net.*; import sun.net.www.*; import sun.net.NetworkClient; import java.net.URL; import java.net.URLStreamHandler; import sun.security.action.GetBooleanAction; /** Class to maintain the state of a gopher fetch and handle the protocol */ public class GopherClient extends NetworkClient implements Runnable { /* The following three data members are left in for binary * backwards-compatibility. Unfortunately, HotJava sets them directly * when it wants to change the settings. The new design has us not * cache these, so this is unnecessary, but eliminating the data members * would break HJB 1.1 under JDK 1.2. * * These data members are not used, and their values are meaningless. * REMIND: Take them out for JDK 2.0! */ /** * @deprecated */ @Deprecated public static boolean useGopherProxy; /** * @deprecated */ @Deprecated public static String gopherProxyHost; /** * @deprecated */ @Deprecated public static int gopherProxyPort; static { useGopherProxy = java.security.AccessController.doPrivileged( new sun.security.action.GetBooleanAction("gopherProxySet")) .booleanValue(); gopherProxyHost = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("gopherProxyHost")); gopherProxyPort = java.security.AccessController.doPrivileged( new sun.security.action.GetIntegerAction("gopherProxyPort", 80)) .intValue(); } PipedOutputStream os; URL u; int gtype; String gkey; sun.net.www.URLConnection connection; GopherClient(sun.net.www.URLConnection connection) { this.connection = connection; } /** * @return true if gopher connections should go through a proxy, according * to system properties. */ public static boolean getUseGopherProxy() { return java.security.AccessController.doPrivileged( new GetBooleanAction("gopherProxySet")).booleanValue(); } /** * @return the proxy host to use, or null if nothing is set. */ public static String getGopherProxyHost() { String host = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("gopherProxyHost")); if ("".equals(host)) { host = null; } return host; } /** * @return the proxy port to use. Will default reasonably. */ public static int getGopherProxyPort() { return java.security.AccessController.doPrivileged( new sun.security.action.GetIntegerAction("gopherProxyPort", 80)) .intValue(); } /** Given a url, setup to fetch the gopher document it refers to */ InputStream openStream(URL u) throws IOException { this.u = u; this.os = os; int i = 0; String s = u.getFile(); int limit = s.length(); int c = '1'; while (i < limit && (c = s.charAt(i)) == '/') i++; gtype = c == '/' ? '1' : c; if (i < limit) i++; gkey = s.substring(i); openServer(u.getHost(), u.getPort() <= 0 ? 70 : u.getPort()); MessageHeader msgh = new MessageHeader(); switch (gtype) { case '0': case '7': msgh.add("content-type", "text/plain"); break; case '1': msgh.add("content-type", "text/html"); break; case 'g': case 'I': msgh.add("content-type", "image/gif"); break; default: msgh.add("content-type", "content/unknown"); break; } if (gtype != '7') { serverOutput.print(decodePercent(gkey) + "\r\n"); serverOutput.flush(); } else if ((i = gkey.indexOf('?')) >= 0) { serverOutput.print(decodePercent(gkey.substring(0, i) + "\t" + gkey.substring(i + 1) + "\r\n")); serverOutput.flush(); msgh.add("content-type", "text/html"); } else { msgh.add("content-type", "text/html"); } connection.setProperties(msgh); if (msgh.findValue("content-type") == "text/html") { os = new PipedOutputStream(); PipedInputStream ret = new PipedInputStream(); ret.connect(os); new Thread(this).start(); return ret; } return new GopherInputStream(this, serverInput); } /** Translate all the instances of %NN into the character they represent */ private String decodePercent(String s) { if (s == null || s.indexOf('%') < 0) return s; int limit = s.length(); char d[] = new char[limit]; int dp = 0; for (int sp = 0; sp < limit; sp++) { int c = s.charAt(sp); if (c == '%' && sp + 2 < limit) { int s1 = s.charAt(sp + 1); int s2 = s.charAt(sp + 2); if ('0' <= s1 && s1 <= '9') s1 = s1 - '0'; else if ('a' <= s1 && s1 <= 'f') s1 = s1 - 'a' + 10; else if ('A' <= s1 && s1 <= 'F') s1 = s1 - 'A' + 10; else s1 = -1; if ('0' <= s2 && s2 <= '9') s2 = s2 - '0'; else if ('a' <= s2 && s2 <= 'f') s2 = s2 - 'a' + 10; else if ('A' <= s2 && s2 <= 'F') s2 = s2 - 'A' + 10; else s2 = -1; if (s1 >= 0 && s2 >= 0) { c = (s1 << 4) | s2; sp += 2; } } d[dp++] = (char) c; } return new String(d, 0, dp); } /** Turn special characters into the %NN form */ private String encodePercent(String s) { if (s == null) return s; int limit = s.length(); char d[] = null; int dp = 0; for (int sp = 0; sp < limit; sp++) { int c = s.charAt(sp); if (c <= ' ' || c == '"' || c == '%') { if (d == null) d = s.toCharArray(); if (dp + 3 >= d.length) { char nd[] = new char[dp + 10]; System.arraycopy(d, 0, nd, 0, dp); d = nd; } d[dp] = '%'; int dig = (c >> 4) & 0xF; d[dp + 1] = (char) (dig < 10 ? '0' + dig : 'A' - 10 + dig); dig = c & 0xF; d[dp + 2] = (char) (dig < 10 ? '0' + dig : 'A' - 10 + dig); dp += 3; } else { if (d != null) { if (dp >= d.length) { char nd[] = new char[dp + 10]; System.arraycopy(d, 0, nd, 0, dp); d = nd; } d[dp] = (char) c; } dp++; } } return d == null ? s : new String(d, 0, dp); } /** This method is run as a seperate thread when an incoming gopher document requires translation to html */ public void run() { int qpos = -1; try { if (gtype == '7' && (qpos = gkey.indexOf('?')) < 0) { PrintStream ps = new PrintStream(os, false, encoding); ps.print("<html><head><title>Searchable Gopher Index</title></head>\n<body><h1>Searchable Gopher Index</h1><isindex>\n</body></html>\n"); } else if (gtype != '1' && gtype != '7') { byte buf[] = new byte[2048]; try { int n; while ((n = serverInput.read(buf)) >= 0) os.write(buf, 0, n); } catch(Exception e) { } } else { PrintStream ps = new PrintStream(os, false, encoding); String title = null; if (gtype == '7') title = "Results of searching for \"" + gkey.substring(qpos + 1) + "\" on " + u.getHost(); else title = "Gopher directory " + gkey + " from " + u.getHost(); ps.print("<html><head><title>"); ps.print(title); ps.print("</title></head>\n<body>\n<H1>"); ps.print(title); ps.print("</h1><dl compact>\n"); DataInputStream ds = new DataInputStream(serverInput); String s; while ((s = ds.readLine()) != null) { int len = s.length(); while (len > 0 && s.charAt(len - 1) <= ' ') len--; if (len <= 0) continue; int key = s.charAt(0); int t1 = s.indexOf('\t'); int t2 = t1 > 0 ? s.indexOf('\t', t1 + 1) : -1; int t3 = t2 > 0 ? s.indexOf('\t', t2 + 1) : -1; if (t3 < 0) { // ps.print("<br><i>"+s+"</i>\n"); continue; } String port = t3 + 1 < len ? ":" + s.substring(t3 + 1, len) : ""; String host = t2 + 1 < t3 ? s.substring(t2 + 1, t3) : u.getHost(); ps.print("<dt><a href=\"gopher://" + host + port + "/" + s.substring(0, 1) + encodePercent(s.substring(t1 + 1, t2)) + "\">\n"); ps.print("<img align=middle border=0 width=25 height=32 src="); switch (key) { default: ps.print(System.getProperty("java.net.ftp.imagepath.file")); break; case '0': ps.print(System.getProperty("java.net.ftp.imagepath.text")); break; case '1': ps.print(System.getProperty("java.net.ftp.imagepath.directory")); break; case 'g': ps.print(System.getProperty("java.net.ftp.imagepath.gif")); break; } ps.print(".gif align=middle><dd>\n"); ps.print(s.substring(1, t1) + "</a>\n"); } ps.print("</dl></body>\n"); ps.close(); } } catch (UnsupportedEncodingException e) { throw new InternalError(encoding+ " encoding not found"); } catch (IOException e) { } finally { try { closeServer(); os.close(); } catch (IOException e2) { } } } } /** An input stream that does nothing more than hold on to the NetworkClient that created it. This is used when only the input stream is needed, and the network client needs to be closed when the input stream is closed. */ class GopherInputStream extends FilterInputStream { NetworkClient parent; GopherInputStream(NetworkClient o, InputStream fd) { super(fd); parent = o; } public void close() { try { parent.closeServer(); super.close(); } catch (IOException e) { } } }
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/sun/net/www/protocol/gopher/GopherClient.java
Java
mit
12,942
/* * 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.activemq.artemis.api.core; /** * A PropertyConversionException is thrown by {@code org.apache.activemq.artemis.api.core.Message} methods when a * property can not be converted to the expected type. */ public final class ActiveMQPropertyConversionException extends RuntimeException { private static final long serialVersionUID = -3010008708334904332L; public ActiveMQPropertyConversionException(final String message) { super(message); } }
jbertram/activemq-artemis
artemis-commons/src/main/java/org/apache/activemq/artemis/api/core/ActiveMQPropertyConversionException.java
Java
apache-2.0
1,278
/* * 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.codehaus.groovy.antlr.treewalker; import groovy.lang.GroovyShell; import groovy.lang.Script; import groovy.util.GroovyTestCase; /** * This tests code that is valid in parser, but has issues further down the line. * * @author <a href="mailto:[email protected]">Jeremy Rayner</a> */ public class UnimplementedSyntaxTest extends GroovyTestCase { // ------------------------------ // feature: Annotation Definition // ------------------------------ public void test_AnnotationDef1_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: ANNOTATION_DEF assertNotNull(compile("public @interface Foo{}")); } public void test_AnnotationDef2_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: ANNOTATION_DEF assertNotNull(compile("public @interface Foo{int bar() default 123}")); } // ------------------------------ // bug: Qualified Exception Types // ------------------------------ public void test_QualifiedExceptionTypes_FAILS() throws Exception { if (notYetImplemented()) return; // Unexpected node type: '.' found when expecting type: an identifier assertNotNull(compile("def foo() throws bar.MookyException{}")); // fails after parser } // ------------------------------ // feature: classic Java for loop // ------------------------------ public void test_ClassicJavaForLoop1_FAILS() throws Exception { if (notYetImplemented()) return; // For statement contains unexpected tokens. Possible attempt to use unsupported Java-style for loop. // This syntax now replaced with closure list i.e. for (i=0;j=2;i<10;i++;j--) {... assertNotNull(compile("for (i = 0,j = 2;i < 10; i++, j--) {print i}")); // fails after parser } public void test_ClassicJavaForLoop2() throws Exception { // For statement contains unexpected tokens. Possible attempt to use unsupported Java-style for loop. assertNotNull(compile("for (i=0;i<10;i++) {println i}")); // fails after parser } // ------------------------------ // feature: Enum Definitions // ------------------------------ public void test_EnumDef1_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: ENUM_DEF assertNotNull(compile("enum Coin {PENNY(1), DIME(10), QUARTER(25)}")); // fails after parser } public void test_EnumDef2_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: ENUM_DEF assertNotNull(compile("enum Season{WINTER,SPRING,SUMMER,AUTUMN}")); // fails after parser } public void test_EnumDef3_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: ENUM_DEF assertNotNull(compile("enum Operation {ADDITION {double eval(x,y) {return x + y}}}")); // fails after parser } public void test_EnumDef4_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: ENUM_DEF assertNotNull(compile("enum EarthSeason implements Season{SPRING}")); // fails after parser } // ------------------------------------------------ // deprecate in parser?: 'break' allowed in methods // ------------------------------------------------ public void test_BreakAllowedInMethods_FAILS() throws Exception { if (notYetImplemented()) return; // the break statement is only allowed inside loops or switches assertNotNull(compile("def myMethod(){break}")); // fails after parser } // ---------------------------------------------------- // deprecate in parser?: 'continue' allowed in closures // ---------------------------------------------------- public void test_ContinueAllowedInClosures_FAILS() throws Exception { if (notYetImplemented()) return; // the continue statement is only allowed inside loops assertNotNull(compile("[1,2,3].each{continue}")); // fails after parser } // ---------------------------------------------------- // feature?: allow break/continue with value from loops? // ---------------------------------------------------- public void test_BreakWithValueAllowedInLoops_FAILS() throws Exception { if (notYetImplemented()) return; // Unexpected node type: a numeric literal found when expecting type: an identifier assertNotNull(compile("for (i in 1..100) {break 2}")); // fails after parser } public void test_ContinueWithValueAllowedInLoops_FAILS() throws Exception { if (notYetImplemented()) return; // Unexpected node type: a numeric literal found when expecting type: an identifier assertNotNull(compile("for (i in 1..100) {continue 2}")); // fails after parser } // --------------------------------------------------------------- // feature?: allow break/continue to labeled statement from loops? (is this even right syntax, or parser bug???) // --------------------------------------------------------------- public void test_BreakToLabeledStatementAllowedInLoops_FAILS() throws Exception { if (notYetImplemented()) return; // Unexpected node type: LABELED_STAT found when expecting type: an identifier assertNotNull(compile("for (i in 1..100) {break label1:}")); // fails after parser } public void test_ContinueToLabeledStatementAllowedInLoops_FAILS() throws Exception { if (notYetImplemented()) return; // Unexpected node type: LABELED_STAT found when expecting type: an identifier assertNotNull(compile("for (i in 1..100) {continue label1:}")); // fails after parser } // ----------------------- // feature: Native Methods // ----------------------- public void test_NativeMethods1_FAILS() throws Exception { if (notYetImplemented()) return; // You defined a method without body. Try adding a body, or declare it abstract assertNotNull(compile("public class R{public native void seek(long pos)}")); // fails after parser } public void test_NativeMethods2_FAILS() throws Exception { if (notYetImplemented()) return; // You defined a method without body. Try adding a body, or declare it abstract assertNotNull(compile("native foo()")); // fails after parser } // --------------------- // feature: 'threadsafe' // --------------------- public void test_Threadsafe1_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: "threadsafe" assertNotNull(compile("threadsafe foo() {}")); // fails after parser } public void test_Threadsafe2_FAILS() throws Exception { if (notYetImplemented()) return; // Unknown type: "threadsafe" assertNotNull(compile("public static transient final native threadsafe synchronized volatile strictfp foo() {}")); // fails after parser } // -------------------------------------------------- // bugs?: spread expressions in closures and GStrings // -------------------------------------------------- public void test_SpreadExpressionInClosure_FAILS() throws Exception { if (notYetImplemented()) return; // BUG! exception in phase 'class generation' in source unit 'Script1.groovy' // SpreadExpression should not be visited here assertNotNull(compile("myList{*name}")); // fails after parser } public void test_SpreadExpressionInGString1_FAILS() throws Exception { if (notYetImplemented()) return; // BUG! exception in phase 'conversion' in source unit 'Script1.groovy' null assertNotNull(compile("\"foo$*bar\"")); // fails after parser } public void test_SpreadExpressionInGString2_FAILS() throws Exception { if (notYetImplemented()) return; // BUG! exception in phase 'class generation' in source unit 'Script1.groovy' // SpreadExpression should not be visited here assertNotNull(compile("\"foo${*bar}\"")); // fails after parser } // ----------------------- // feature: static imports // ----------------------- // TODO: move somewhere else public void test_StaticImport1() throws Exception { //GROOVY-3711: The following call now results in a valid script class node, so foo.Bar needs to get resolved. GroovyShell groovyShell = new GroovyShell(); compile("package foo; class Bar{}", groovyShell); assertNotNull(compile("import static foo.Bar.mooky", groovyShell)); } public void test_StaticImport2() throws Exception { //GROOVY-3711: The following call now results in a valid script class node, so foo.Bar needs to get resolved. GroovyShell groovyShell = new GroovyShell(); compile("package foo; class Bar{}", groovyShell); assertNotNull(compile("import static foo.Bar.*", groovyShell)); } // TODO: move somewhere else GROOVY-1874 public void test_staticBlockWithNewLines() throws Exception { assertNotNull(compile("class MyClass \n{\n\tstatic\n{\nprintln 2\n}\n}")); } public void test_staticBlockWithNoStartNewLines() throws Exception { assertNotNull(compile("class MyClass \n{\n\tstatic {\nprintln 2\n}\n}")); } public void test_staticBlockWithNoNewLines() throws Exception { assertNotNull(compile("class MyClass \n{\n\tstatic { println 2 }}")); } // ------------------------ // feature: type parameters // ------------------------ public void test_TypeParameters_FAILS() throws Exception { if (notYetImplemented()) return; // Unexpected node type: TYPE_PARAMETERS found when expecting type: OBJBLOCK assertNotNull(compile("class Foo<T extends C & I> {T t}")); // fails after parser } private Script compile(String input) throws Exception { return compile(input, new GroovyShell()); } private Script compile(String input, GroovyShell groovyShell) throws Exception { TraversalTestHelper traverser = new TraversalTestHelper(); traverser.traverse(input, SourcePrinter.class, Boolean.FALSE); return groovyShell.parse(input); } }
antoaravinth/incubator-groovy
src/test/org/codehaus/groovy/antlr/treewalker/UnimplementedSyntaxTest.java
Java
apache-2.0
11,145
/** * 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.yarn.server.nodemanager.containermanager.monitor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.UnsupportedFileSystemException; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.LocalResourceType; import org.apache.hadoop.yarn.api.records.LocalResourceVisibility; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.api.records.URL; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.Signal; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.containermanager.BaseContainerManagerTest; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.LinuxResourceCalculatorPlugin; import org.apache.hadoop.yarn.util.ProcfsBasedProcessTree; import org.apache.hadoop.yarn.util.ResourceCalculatorPlugin; import org.apache.hadoop.yarn.util.TestProcfsBasedProcessTree; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestContainersMonitor extends BaseContainerManagerTest { public TestContainersMonitor() throws UnsupportedFileSystemException { super(); } static { LOG = LogFactory.getLog(TestContainersMonitor.class); } @Before public void setup() throws IOException { conf.setClass( YarnConfiguration.NM_CONTAINER_MON_RESOURCE_CALCULATOR, LinuxResourceCalculatorPlugin.class, ResourceCalculatorPlugin.class); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, true); super.setup(); } /** * Test to verify the check for whether a process tree is over limit or not. * * @throws IOException * if there was a problem setting up the fake procfs directories or * files. */ @Test public void testProcessTreeLimits() throws IOException { // set up a dummy proc file system File procfsRootDir = new File(localDir, "proc"); String[] pids = { "100", "200", "300", "400", "500", "600", "700" }; try { TestProcfsBasedProcessTree.setupProcfsRootDir(procfsRootDir); // create pid dirs. TestProcfsBasedProcessTree.setupPidDirs(procfsRootDir, pids); // create process infos. TestProcfsBasedProcessTree.ProcessStatInfo[] procs = new TestProcfsBasedProcessTree.ProcessStatInfo[7]; // assume pids 100, 500 are in 1 tree // 200,300,400 are in another // 600,700 are in a third procs[0] = new TestProcfsBasedProcessTree.ProcessStatInfo( new String[] { "100", "proc1", "1", "100", "100", "100000" }); procs[1] = new TestProcfsBasedProcessTree.ProcessStatInfo( new String[] { "200", "proc2", "1", "200", "200", "200000" }); procs[2] = new TestProcfsBasedProcessTree.ProcessStatInfo( new String[] { "300", "proc3", "200", "200", "200", "300000" }); procs[3] = new TestProcfsBasedProcessTree.ProcessStatInfo( new String[] { "400", "proc4", "200", "200", "200", "400000" }); procs[4] = new TestProcfsBasedProcessTree.ProcessStatInfo( new String[] { "500", "proc5", "100", "100", "100", "1500000" }); procs[5] = new TestProcfsBasedProcessTree.ProcessStatInfo( new String[] { "600", "proc6", "1", "600", "600", "100000" }); procs[6] = new TestProcfsBasedProcessTree.ProcessStatInfo( new String[] { "700", "proc7", "600", "600", "600", "100000" }); // write stat files. TestProcfsBasedProcessTree.writeStatFiles(procfsRootDir, pids, procs, null); // vmem limit long limit = 700000; ContainersMonitorImpl test = new ContainersMonitorImpl(null, null, null); // create process trees // tree rooted at 100 is over limit immediately, as it is // twice over the mem limit. ProcfsBasedProcessTree pTree = new ProcfsBasedProcessTree( "100", procfsRootDir.getAbsolutePath()); pTree.updateProcessTree(); assertTrue("tree rooted at 100 should be over limit " + "after first iteration.", test.isProcessTreeOverLimit(pTree, "dummyId", limit)); // the tree rooted at 200 is initially below limit. pTree = new ProcfsBasedProcessTree("200", procfsRootDir.getAbsolutePath()); pTree.updateProcessTree(); assertFalse("tree rooted at 200 shouldn't be over limit " + "after one iteration.", test.isProcessTreeOverLimit(pTree, "dummyId", limit)); // second iteration - now the tree has been over limit twice, // hence it should be declared over limit. pTree.updateProcessTree(); assertTrue( "tree rooted at 200 should be over limit after 2 iterations", test.isProcessTreeOverLimit(pTree, "dummyId", limit)); // the tree rooted at 600 is never over limit. pTree = new ProcfsBasedProcessTree("600", procfsRootDir.getAbsolutePath()); pTree.updateProcessTree(); assertFalse("tree rooted at 600 should never be over limit.", test.isProcessTreeOverLimit(pTree, "dummyId", limit)); // another iteration does not make any difference. pTree.updateProcessTree(); assertFalse("tree rooted at 600 should never be over limit.", test.isProcessTreeOverLimit(pTree, "dummyId", limit)); } finally { FileUtil.fullyDelete(procfsRootDir); } } @Test public void testContainerKillOnMemoryOverflow() throws IOException, InterruptedException, YarnException { if (!ProcfsBasedProcessTree.isAvailable()) { return; } containerManager.start(); File scriptFile = new File(tmpDir, "scriptFile.sh"); PrintWriter fileWriter = new PrintWriter(scriptFile); File processStartFile = new File(tmpDir, "start_file.txt").getAbsoluteFile(); fileWriter.write("\numask 0"); // So that start file is readable by the // test. fileWriter.write("\necho Hello World! > " + processStartFile); fileWriter.write("\necho $$ >> " + processStartFile); fileWriter.write("\nsleep 15"); fileWriter.close(); ContainerLaunchContext containerLaunchContext = recordFactory.newRecordInstance(ContainerLaunchContext.class); // ////// Construct the Container-id ApplicationId appId = ApplicationId.newInstance(0, 0); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); ContainerId cId = ContainerId.newContainerId(appAttemptId, 0); int port = 12345; URL resource_alpha = ConverterUtils.getYarnUrlFromPath(localFS .makeQualified(new Path(scriptFile.getAbsolutePath()))); LocalResource rsrc_alpha = recordFactory.newRecordInstance(LocalResource.class); rsrc_alpha.setResource(resource_alpha); rsrc_alpha.setSize(-1); rsrc_alpha.setVisibility(LocalResourceVisibility.APPLICATION); rsrc_alpha.setType(LocalResourceType.FILE); rsrc_alpha.setTimestamp(scriptFile.lastModified()); String destinationFile = "dest_file"; Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); localResources.put(destinationFile, rsrc_alpha); containerLaunchContext.setLocalResources(localResources); List<String> commands = new ArrayList<String>(); commands.add("/bin/bash"); commands.add(scriptFile.getAbsolutePath()); containerLaunchContext.setCommands(commands); Resource r = BuilderUtils.newResource(8 * 1024 * 1024, 1); ContainerTokenIdentifier containerIdentifier = new ContainerTokenIdentifier(cId, context.getNodeId().toString(), user, r, System.currentTimeMillis() + 120000, 123, DUMMY_RM_IDENTIFIER, Priority.newInstance(0), 0); Token containerToken = BuilderUtils.newContainerToken(context.getNodeId(), containerManager.getContext().getContainerTokenSecretManager() .createPassword(containerIdentifier), containerIdentifier); StartContainerRequest scRequest = StartContainerRequest.newInstance(containerLaunchContext, containerToken); List<StartContainerRequest> list = new ArrayList<StartContainerRequest>(); list.add(scRequest); StartContainersRequest allRequests = StartContainersRequest.newInstance(list); containerManager.startContainers(allRequests); int timeoutSecs = 0; while (!processStartFile.exists() && timeoutSecs++ < 20) { Thread.sleep(1000); LOG.info("Waiting for process start-file to be created"); } Assert.assertTrue("ProcessStartFile doesn't exist!", processStartFile.exists()); // Now verify the contents of the file BufferedReader reader = new BufferedReader(new FileReader(processStartFile)); Assert.assertEquals("Hello World!", reader.readLine()); // Get the pid of the process String pid = reader.readLine().trim(); // No more lines Assert.assertEquals(null, reader.readLine()); BaseContainerManagerTest.waitForContainerState(containerManager, cId, ContainerState.COMPLETE, 60); List<ContainerId> containerIds = new ArrayList<ContainerId>(); containerIds.add(cId); GetContainerStatusesRequest gcsRequest = GetContainerStatusesRequest.newInstance(containerIds); ContainerStatus containerStatus = containerManager.getContainerStatuses(gcsRequest).getContainerStatuses().get(0); Assert.assertEquals(ContainerExitStatus.KILLED_EXCEEDED_VMEM, containerStatus.getExitStatus()); String expectedMsgPattern = "Container \\[pid=" + pid + ",containerID=" + cId + "\\] is running beyond virtual memory limits. Current usage: " + "[0-9.]+ ?[KMGTPE]?B of [0-9.]+ ?[KMGTPE]?B physical memory used; " + "[0-9.]+ ?[KMGTPE]?B of [0-9.]+ ?[KMGTPE]?B virtual memory used. " + "Killing container.\nDump of the process-tree for " + cId + " :\n"; Pattern pat = Pattern.compile(expectedMsgPattern); Assert.assertEquals("Expected message pattern is: " + expectedMsgPattern + "\n\nObserved message is: " + containerStatus.getDiagnostics(), true, pat.matcher(containerStatus.getDiagnostics()).find()); // Assert that the process is not alive anymore Assert.assertFalse("Process is still alive!", exec.signalContainer(user, pid, Signal.NULL)); } @Test(timeout = 20000) public void testContainerMonitorMemFlags() { ContainersMonitor cm = null; long expPmem = 8192 * 1024 * 1024l; long expVmem = (long) (expPmem * 2.1f); cm = new ContainersMonitorImpl(mock(ContainerExecutor.class), mock(AsyncDispatcher.class), mock(Context.class)); cm.init(getConfForCM(false, false, 8192, 2.1f)); assertEquals(expPmem, cm.getPmemAllocatedForContainers()); assertEquals(expVmem, cm.getVmemAllocatedForContainers()); assertEquals(false, cm.isPmemCheckEnabled()); assertEquals(false, cm.isVmemCheckEnabled()); cm = new ContainersMonitorImpl(mock(ContainerExecutor.class), mock(AsyncDispatcher.class), mock(Context.class)); cm.init(getConfForCM(true, false, 8192, 2.1f)); assertEquals(expPmem, cm.getPmemAllocatedForContainers()); assertEquals(expVmem, cm.getVmemAllocatedForContainers()); assertEquals(true, cm.isPmemCheckEnabled()); assertEquals(false, cm.isVmemCheckEnabled()); cm = new ContainersMonitorImpl(mock(ContainerExecutor.class), mock(AsyncDispatcher.class), mock(Context.class)); cm.init(getConfForCM(true, true, 8192, 2.1f)); assertEquals(expPmem, cm.getPmemAllocatedForContainers()); assertEquals(expVmem, cm.getVmemAllocatedForContainers()); assertEquals(true, cm.isPmemCheckEnabled()); assertEquals(true, cm.isVmemCheckEnabled()); cm = new ContainersMonitorImpl(mock(ContainerExecutor.class), mock(AsyncDispatcher.class), mock(Context.class)); cm.init(getConfForCM(false, true, 8192, 2.1f)); assertEquals(expPmem, cm.getPmemAllocatedForContainers()); assertEquals(expVmem, cm.getVmemAllocatedForContainers()); assertEquals(false, cm.isPmemCheckEnabled()); assertEquals(true, cm.isVmemCheckEnabled()); } private YarnConfiguration getConfForCM(boolean pMemEnabled, boolean vMemEnabled, int nmPmem, float vMemToPMemRatio) { YarnConfiguration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.NM_PMEM_MB, nmPmem); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, pMemEnabled); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, vMemEnabled); conf.setFloat(YarnConfiguration.NM_VMEM_PMEM_RATIO, vMemToPMemRatio); return conf; } }
ZhangXFeng/hadoop
src/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/monitor/TestContainersMonitor.java
Java
apache-2.0
15,328
/* * Copyright 2000-2015 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. */ package com.intellij.psi.usages; import com.intellij.JavaTestUtil; import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import com.intellij.usages.UsageTarget; import com.intellij.usages.impl.rules.JavaUsageTypeProvider; import com.intellij.usages.impl.rules.UsageType; /** * @author nik */ public class JavaUsageTypeProviderTest extends LightCodeInsightFixtureTestCase { public void testNestedClassAccess() throws Exception { myFixture.configureByFiles("NestedClassAccess.java", "Foo.java"); assertUsageType(UsageType.CLASS_NESTED_CLASS_ACCESS, myFixture.findClass("Foo")); } public void testStaticMethodCall() throws Exception { myFixture.configureByFiles("StaticMethodCall.java", "Foo.java"); assertUsageType(UsageType.CLASS_STATIC_MEMBER_ACCESS, myFixture.findClass("Foo")); } public void testStaticFieldUsage() throws Exception { myFixture.configureByFiles("StaticFieldUsage.java", "Foo.java"); assertUsageType(UsageType.CLASS_STATIC_MEMBER_ACCESS, myFixture.findClass("Foo")); } private void assertUsageType(UsageType expected, PsiClass target) { UsageTarget[] targets = {new PsiElement2UsageTargetAdapter(target)}; PsiElement element = myFixture.getReferenceAtCaretPositionWithAssertion().getElement(); UsageType usageType = new JavaUsageTypeProvider().getUsageType(element, targets); assertEquals(expected, usageType); } @Override protected String getBasePath() { return JavaTestUtil.getRelativeJavaTestDataPath() + "/psi/usages/"; } }
hurricup/intellij-community
java/java-tests/testSrc/com/intellij/psi/usages/JavaUsageTypeProviderTest.java
Java
apache-2.0
2,279
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.metadata; import com.facebook.presto.spi.ConnectorInsertTableHandle; import javax.inject.Inject; import static com.google.common.base.Preconditions.checkNotNull; public class InsertTableHandleJacksonModule extends AbstractTypedJacksonModule<ConnectorInsertTableHandle> { @Inject public InsertTableHandleJacksonModule(HandleResolver handleResolver) { super(ConnectorInsertTableHandle.class, "type", new InsertTableHandleJsonTypeIdResolver(handleResolver)); } private static class InsertTableHandleJsonTypeIdResolver implements JsonTypeIdResolver<ConnectorInsertTableHandle> { private final HandleResolver handleResolver; private InsertTableHandleJsonTypeIdResolver(HandleResolver handleResolver) { this.handleResolver = checkNotNull(handleResolver, "handleResolver is null"); } @Override public String getId(ConnectorInsertTableHandle tableHandle) { return handleResolver.getId(tableHandle); } @Override public Class<? extends ConnectorInsertTableHandle> getType(String id) { return handleResolver.getInsertTableHandleClass(id); } } }
kuzemchik/presto
presto-main/src/main/java/com/facebook/presto/metadata/InsertTableHandleJacksonModule.java
Java
apache-2.0
1,820
package rx.android.samples; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.View; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.android.schedulers.HandlerScheduler; import rx.exceptions.OnErrorThrowable; import rx.functions.Func0; import static android.os.Process.THREAD_PRIORITY_BACKGROUND; public class MainActivity extends Activity { private static final String TAG = "RxAndroidSamples"; private Handler backgroundHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); BackgroundThread backgroundThread = new BackgroundThread(); backgroundThread.start(); backgroundHandler = new Handler(backgroundThread.getLooper()); findViewById(R.id.scheduler_example).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRunSchedulerExampleButtonClicked(); } }); } void onRunSchedulerExampleButtonClicked() { sampleObservable() // Run on a background thread .subscribeOn(HandlerScheduler.from(backgroundHandler)) // Be notified on the main thread .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { Log.d(TAG, "onCompleted()"); } @Override public void onError(Throwable e) { Log.e(TAG, "onError()", e); } @Override public void onNext(String string) { Log.d(TAG, "onNext(" + string + ")"); } }); } static Observable<String> sampleObservable() { return Observable.defer(new Func0<Observable<String>>() { @Override public Observable<String> call() { try { // Do some long running operation Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } catch (InterruptedException e) { throw OnErrorThrowable.from(e); } return Observable.just("one", "two", "three", "four", "five"); } }); } static class BackgroundThread extends HandlerThread { BackgroundThread() { super("SchedulerSample-BackgroundThread", THREAD_PRIORITY_BACKGROUND); } } }
bensonX/RxAndroid
sample-app/src/main/java/rx/android/samples/MainActivity.java
Java
apache-2.0
2,753
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.db.compaction; import java.util.Collection; import java.util.concurrent.ExecutionException; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.cql3.QueryProcessor; import org.apache.cassandra.cql3.UntypedResultSet; import org.apache.cassandra.db.*; import org.apache.cassandra.db.partitions.ImmutableBTreePartition; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.db.partitions.PartitionUpdate; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.schema.CachingParams; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import static org.junit.Assert.*; import static org.apache.cassandra.Util.dk; public class CompactionsPurgeTest { private static final String KEYSPACE1 = "CompactionsPurgeTest1"; private static final String CF_STANDARD1 = "Standard1"; private static final String CF_STANDARD2 = "Standard2"; private static final String KEYSPACE2 = "CompactionsPurgeTest2"; private static final String KEYSPACE_CACHED = "CompactionsPurgeTestCached"; private static final String CF_CACHED = "CachedCF"; private static final String KEYSPACE_CQL = "cql_keyspace"; private static final String CF_CQL = "table1"; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD1), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD2)); SchemaLoader.createKeyspace(KEYSPACE2, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE2, CF_STANDARD1)); SchemaLoader.createKeyspace(KEYSPACE_CACHED, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE_CACHED, CF_CACHED).caching(CachingParams.CACHE_EVERYTHING)); SchemaLoader.createKeyspace(KEYSPACE_CQL, KeyspaceParams.simple(1), CFMetaData.compile("CREATE TABLE " + CF_CQL + " (" + "k int PRIMARY KEY," + "v1 text," + "v2 int" + ")", KEYSPACE_CQL)); } @Test public void testMajorCompactionPurge() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key1"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } cfs.forceBlockingFlush(); // deletes for (int i = 0; i < 10; i++) { RowUpdateBuilder.deleteRow(cfs.metadata, 1, key, String.valueOf(i)).applyUnsafe(); } cfs.forceBlockingFlush(); // resurrect one column RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, 2, key); builder.clustering(String.valueOf(5)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(); // major compact and test that all columns but the resurrected one is completely gone FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, Integer.MAX_VALUE, false)); cfs.invalidateCachedPartition(dk(key)); ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertEquals(1, partition.rowCount()); } @Test public void testMinorCompactionPurge() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE2); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); for (int k = 1; k <= 2; ++k) { String key = "key" + k; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } cfs.forceBlockingFlush(); // deletes for (int i = 0; i < 10; i++) { RowUpdateBuilder.deleteRow(cfs.metadata, 1, key, String.valueOf(i)).applyUnsafe(); } cfs.forceBlockingFlush(); } DecoratedKey key1 = Util.dk("key1"); DecoratedKey key2 = Util.dk("key2"); // flush, remember the current sstable and then resurrect one column // for first key. Then submit minor compaction on remembered sstables. cfs.forceBlockingFlush(); Collection<SSTableReader> sstablesIncomplete = cfs.getLiveSSTables(); RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, 2, "key1"); builder.clustering(String.valueOf(5)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(); cfs.getCompactionStrategyManager().getUserDefinedTask(sstablesIncomplete, Integer.MAX_VALUE).execute(null); // verify that minor compaction does GC when key is provably not // present in a non-compacted sstable Util.assertEmpty(Util.cmd(cfs, key2).build()); // verify that minor compaction still GC when key is present // in a non-compacted sstable but the timestamp ensures we won't miss anything ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key1).build()); assertEquals(1, partition.rowCount()); } /** * verify that we don't drop tombstones during a minor compaction that might still be relevant */ @Test public void testMinTimestampPurge() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE2); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key3 = "key3"; // inserts new RowUpdateBuilder(cfs.metadata, 8, key3) .clustering("c1") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); new RowUpdateBuilder(cfs.metadata, 8, key3) .clustering("c2") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(); // delete c1 RowUpdateBuilder.deleteRow(cfs.metadata, 10, key3, "c1").applyUnsafe(); cfs.forceBlockingFlush(); Collection<SSTableReader> sstablesIncomplete = cfs.getLiveSSTables(); // delete c2 so we have new delete in a diffrent SSTable RowUpdateBuilder.deleteRow(cfs.metadata, 9, key3, "c2").applyUnsafe(); cfs.forceBlockingFlush(); // compact the sstables with the c1/c2 data and the c1 tombstone cfs.getCompactionStrategyManager().getUserDefinedTask(sstablesIncomplete, Integer.MAX_VALUE).execute(null); // We should have both the c1 and c2 tombstones still. Since the min timestamp in the c2 tombstone // sstable is older than the c1 tombstone, it is invalid to throw out the c1 tombstone. ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key3).build()); assertEquals(2, partition.rowCount()); for (Row row : partition) assertFalse(row.hasLiveData(FBUtilities.nowInSeconds())); } @Test public void testCompactionPurgeOneFile() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); String cfName = "Standard2"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key1"; // inserts for (int i = 0; i < 5; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // deletes for (int i = 0; i < 5; i++) { RowUpdateBuilder.deleteRow(cfs.metadata, 1, key, String.valueOf(i)).applyUnsafe(); } cfs.forceBlockingFlush(); assertEquals(String.valueOf(cfs.getLiveSSTables()), 1, cfs.getLiveSSTables().size()); // inserts & deletes were in the same memtable -> only deletes in sstable // compact and test that the row is completely gone Util.compactAll(cfs, Integer.MAX_VALUE).get(); assertTrue(cfs.getLiveSSTables().isEmpty()); Util.assertEmpty(Util.cmd(cfs, key).build()); } @Test public void testCompactionPurgeCachedRow() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); String keyspaceName = KEYSPACE_CACHED; String cfName = CF_CACHED; Keyspace keyspace = Keyspace.open(keyspaceName); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key3"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // deletes partition Mutation rm = new Mutation(KEYSPACE_CACHED, dk(key)); rm.add(PartitionUpdate.fullPartitionDelete(cfs.metadata, dk(key), 1, FBUtilities.nowInSeconds())); rm.applyUnsafe(); // Adds another unrelated partition so that the sstable is not considered fully expired. We do not // invalidate the row cache in that latter case. new RowUpdateBuilder(cfs.metadata, 0, "key4").clustering("c").add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER).build().applyUnsafe(); // move the key up in row cache (it should not be empty since we have the partition deletion info) assertFalse(Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()).isEmpty()); // flush and major compact cfs.forceBlockingFlush(); Util.compactAll(cfs, Integer.MAX_VALUE).get(); // Since we've force purging (by passing MAX_VALUE for gc_before), the row should have been invalidated and we should have no deletion info anymore Util.assertEmpty(Util.cmd(cfs, key).build()); } @Test public void testCompactionPurgeTombstonedRow() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); String keyspaceName = KEYSPACE1; String cfName = "Standard1"; Keyspace keyspace = Keyspace.open(keyspaceName); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key3"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, i, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // deletes partition with timestamp such that not all columns are deleted Mutation rm = new Mutation(KEYSPACE1, dk(key)); rm.add(PartitionUpdate.fullPartitionDelete(cfs.metadata, dk(key), 4, FBUtilities.nowInSeconds())); rm.applyUnsafe(); ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertFalse(partition.partitionLevelDeletion().isLive()); // flush and major compact (with tombstone purging) cfs.forceBlockingFlush(); Util.compactAll(cfs, Integer.MAX_VALUE).get(); assertFalse(Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()).isEmpty()); // re-inserts with timestamp lower than delete for (int i = 0; i < 5; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata, i, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // Check that the second insert went in partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertEquals(10, partition.rowCount()); } @Test public void testRowTombstoneObservedBeforePurging() { String keyspace = "cql_keyspace"; String table = "table1"; ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(table); cfs.disableAutoCompaction(); // write a row out to one sstable QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v1, v2) VALUES (%d, '%s', %d)", keyspace, table, 1, "foo", 1)); cfs.forceBlockingFlush(); UntypedResultSet result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(1, result.size()); // write a row tombstone out to a second sstable QueryProcessor.executeInternal(String.format("DELETE FROM %s.%s WHERE k = %d", keyspace, table, 1)); cfs.forceBlockingFlush(); // basic check that the row is considered deleted assertEquals(2, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(0, result.size()); // compact the two sstables with a gcBefore that does *not* allow the row tombstone to be purged FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, (int) (System.currentTimeMillis() / 1000) - 10000, false)); // the data should be gone, but the tombstone should still exist assertEquals(1, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(0, result.size()); // write a row out to one sstable QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v1, v2) VALUES (%d, '%s', %d)", keyspace, table, 1, "foo", 1)); cfs.forceBlockingFlush(); assertEquals(2, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(1, result.size()); // write a row tombstone out to a different sstable QueryProcessor.executeInternal(String.format("DELETE FROM %s.%s WHERE k = %d", keyspace, table, 1)); cfs.forceBlockingFlush(); // compact the two sstables with a gcBefore that *does* allow the row tombstone to be purged FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, (int) (System.currentTimeMillis() / 1000) + 10000, false)); // both the data and the tombstone should be gone this time assertEquals(0, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(0, result.size()); } }
yonglehou/cassandra
test/unit/org/apache/cassandra/db/compaction/CompactionsPurgeTest.java
Java
apache-2.0
17,314
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty4.http; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.netty4.NettyConverter; import org.junit.Test; public class NettyUseRawHttpResponseTest extends BaseNettyTest { @Test public void testAccessHttpRequest() throws Exception { getMockEndpoint("mock:input").expectedBodiesReceived("Hello World"); String out = template.requestBody("netty4-http:http://localhost:{{port}}/foo", "Hello World", String.class); assertEquals("Bye World", out); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("netty4-http:http://0.0.0.0:{{port}}/foo") .to("mock:input") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, NettyConverter.toByteBuffer("Bye World".getBytes())); response.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), 9); exchange.getOut().setBody(response); } }); } }; } }
curso007/camel
components/camel-netty4-http/src/test/java/org/apache/camel/component/netty4/http/NettyUseRawHttpResponseTest.java
Java
apache-2.0
2,697
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.localfile; import com.facebook.presto.spi.PrestoException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static com.facebook.presto.localfile.LocalFileErrorCode.LOCAL_FILE_FILESYSTEM_ERROR; import static com.facebook.presto.localfile.LocalFileErrorCode.LOCAL_FILE_NO_FILES; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.nio.file.Files.newDirectoryStream; import static java.util.Objects.requireNonNull; final class DataLocation { private final File location; private final Optional<String> pattern; @SuppressWarnings("ResultOfMethodCallIgnored") @JsonCreator public DataLocation( @JsonProperty("location") String location, @JsonProperty("pattern") Optional<String> pattern) { requireNonNull(location, "location is null"); requireNonNull(pattern, "pattern is null"); File file = new File(location); if (!file.exists() && pattern.isPresent()) { file.mkdirs(); } checkArgument(file.exists(), "location does not exist"); if (pattern.isPresent() && !file.isDirectory()) { throw new IllegalArgumentException("pattern may be specified only if location is a directory"); } this.location = file; this.pattern = (!pattern.isPresent() && file.isDirectory()) ? Optional.of("*") : pattern; } @JsonProperty public File getLocation() { return location; } @JsonProperty public Optional<String> getPattern() { return pattern; } public List<File> files() { checkState(location.exists(), "location %s doesn't exist", location); if (!pattern.isPresent()) { return ImmutableList.of(location); } checkState(location.isDirectory(), "location %s is not a directory", location); try (DirectoryStream<Path> paths = newDirectoryStream(location.toPath(), pattern.get())) { ImmutableList.Builder<File> builder = ImmutableList.builder(); for (Path path : paths) { builder.add(path.toFile()); } List<File> files = builder.build(); if (files.isEmpty()) { throw new PrestoException(LOCAL_FILE_NO_FILES, "No matching files found in directory: " + location); } return files.stream() .sorted((o1, o2) -> Long.compare(o2.lastModified(), o1.lastModified())) .collect(Collectors.toList()); } catch (IOException e) { throw new PrestoException(LOCAL_FILE_FILESYSTEM_ERROR, "Error listing files in directory: " + location, e); } } }
marsorp/blog
presto166/presto-local-file/src/main/java/com/facebook/presto/localfile/DataLocation.java
Java
apache-2.0
3,673
/* * Copyright 2014 Niek Haarman * * 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.nhaarman.listviewanimations.appearance; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.nhaarman.listviewanimations.BaseAdapterDecorator; import com.nhaarman.listviewanimations.util.AnimatorUtil; import com.nhaarman.listviewanimations.util.ListViewWrapper; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.ObjectAnimator; /** * A {@link BaseAdapterDecorator} class which applies multiple {@link Animator}s at once to views when they are first shown. The Animators applied include the animations specified * in {@link #getAnimators(ViewGroup, View)}, plus an alpha transition. */ public abstract class AnimationAdapter extends BaseAdapterDecorator { /** * Saved instance state key for the ViewAniamt */ private static final String SAVEDINSTANCESTATE_VIEWANIMATOR = "savedinstancestate_viewanimator"; /** * Alpha property */ private static final String ALPHA = "alpha"; /** * The ViewAnimator responsible for animating the Views. */ @Nullable private ViewAnimator mViewAnimator; /** * Whether this instance is the root AnimationAdapter. When this is set to false, animation is not applied to the views, since the wrapper AnimationAdapter will take care of * that. */ private boolean mIsRootAdapter; /** * If the AbsListView is an instance of GridView, this boolean indicates whether the GridView is possibly measuring the view. */ private boolean mGridViewPossiblyMeasuring; /** * The position of the item that the GridView is possibly measuring. */ private int mGridViewMeasuringPosition; /** * Creates a new AnimationAdapter, wrapping given BaseAdapter. * * @param baseAdapter the BaseAdapter to wrap. */ protected AnimationAdapter(@NonNull final BaseAdapter baseAdapter) { super(baseAdapter); mGridViewPossiblyMeasuring = true; mGridViewMeasuringPosition = -1; mIsRootAdapter = true; if (baseAdapter instanceof AnimationAdapter) { ((AnimationAdapter) baseAdapter).setIsWrapped(); } } @Override public void setListViewWrapper(@NonNull final ListViewWrapper listViewWrapper) { super.setListViewWrapper(listViewWrapper); mViewAnimator = new ViewAnimator(listViewWrapper); } /** * Sets whether this instance is wrapped by another instance of AnimationAdapter. If called, this instance will not apply any animations to the views, since the wrapper * AnimationAdapter handles that. */ private void setIsWrapped() { mIsRootAdapter = false; } /** * Call this method to reset animation status on all views. The next time {@link #notifyDataSetChanged()} is called on the base adapter, all views will animate again. */ public void reset() { if (getListViewWrapper() == null) { throw new IllegalStateException("Call setAbsListView() on this AnimationAdapter first!"); } assert mViewAnimator != null; mViewAnimator.reset(); mGridViewPossiblyMeasuring = true; mGridViewMeasuringPosition = -1; if (getDecoratedBaseAdapter() instanceof AnimationAdapter) { ((AnimationAdapter) getDecoratedBaseAdapter()).reset(); } } /** * Returns the {@link com.nhaarman.listviewanimations.appearance.ViewAnimator} responsible for animating the Views in this adapter. */ @Nullable public ViewAnimator getViewAnimator() { return mViewAnimator; } @NonNull @Override public final View getView(final int position, @Nullable final View convertView, @NonNull final ViewGroup parent) { if (mIsRootAdapter) { if (getListViewWrapper() == null) { throw new IllegalStateException("Call setAbsListView() on this AnimationAdapter first!"); } assert mViewAnimator != null; if (convertView != null) { mViewAnimator.cancelExistingAnimation(convertView); } } View itemView = super.getView(position, convertView, parent); if (mIsRootAdapter) { animateViewIfNecessary(position, itemView, parent); } return itemView; } /** * Animates given View if necessary. * * @param position the position of the item the View represents. * @param view the View that should be animated. * @param parent the parent the View is hosted in. */ private void animateViewIfNecessary(final int position, @NonNull final View view, @NonNull final ViewGroup parent) { assert mViewAnimator != null; /* GridView measures the first View which is returned by getView(int, View, ViewGroup), but does not use that View. On KitKat, it does this actually multiple times. Therefore, we animate all these first Views, and reset the last animated position when we suspect GridView is measuring. */ mGridViewPossiblyMeasuring = mGridViewPossiblyMeasuring && (mGridViewMeasuringPosition == -1 || mGridViewMeasuringPosition == position); if (mGridViewPossiblyMeasuring) { mGridViewMeasuringPosition = position; mViewAnimator.setLastAnimatedPosition(-1); } Animator[] childAnimators; if (getDecoratedBaseAdapter() instanceof AnimationAdapter) { childAnimators = ((AnimationAdapter) getDecoratedBaseAdapter()).getAnimators(parent, view); } else { childAnimators = new Animator[0]; } Animator[] animators = getAnimators(parent, view); Animator alphaAnimator = ObjectAnimator.ofFloat(view, ALPHA, 0, 1); Animator[] concatAnimators = AnimatorUtil.concatAnimators(childAnimators, animators, alphaAnimator); mViewAnimator.animateViewIfNecessary(position, view, concatAnimators); } /** * Returns the Animators to apply to the views. In addition to the returned Animators, an alpha transition will be applied to the view. * * @param parent The parent of the view * @param view The view that will be animated, as retrieved by getView(). */ @NonNull public abstract Animator[] getAnimators(@NonNull ViewGroup parent, @NonNull View view); /** * Returns a Parcelable object containing the AnimationAdapter's current dynamic state. */ @NonNull public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); if (mViewAnimator != null) { bundle.putParcelable(SAVEDINSTANCESTATE_VIEWANIMATOR, mViewAnimator.onSaveInstanceState()); } return bundle; } /** * Restores this AnimationAdapter's state. * * @param parcelable the Parcelable object previously returned by {@link #onSaveInstanceState()}. */ public void onRestoreInstanceState(@Nullable final Parcelable parcelable) { if (parcelable instanceof Bundle) { Bundle bundle = (Bundle) parcelable; if (mViewAnimator != null) { mViewAnimator.onRestoreInstanceState(bundle.getParcelable(SAVEDINSTANCESTATE_VIEWANIMATOR)); } } } }
nhaarman/ListViewAnimations
lib-core/src/main/java/com/nhaarman/listviewanimations/appearance/AnimationAdapter.java
Java
apache-2.0
8,066
/*** Copyright (c) 2008-2015 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. From _The Busy Coder's Guide to Android Development_ https://commonsware.com/Android */ package com.commonsware.android.recyclerview.videolist; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; public class MainActivity extends RecyclerViewActivity implements LoaderManager.LoaderCallbacks<Cursor> { private ImageLoader imageLoader; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); ImageLoaderConfiguration ilConfig= new ImageLoaderConfiguration.Builder(this).build(); imageLoader=ImageLoader.getInstance(); imageLoader.init(ilConfig); getLoaderManager().initLoader(0, null, this); setLayoutManager(new LinearLayoutManager(this)); setAdapter(new VideoAdapter()); } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { return(new CursorLoader(this, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Video.Media.TITLE)); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor c) { ((VideoAdapter)getAdapter()).setVideos(c); } @Override public void onLoaderReset(Loader<Cursor> loader) { ((VideoAdapter)getAdapter()).setVideos(null); } class VideoAdapter extends RecyclerView.Adapter<RowController> { Cursor videos=null; @Override public RowController onCreateViewHolder(ViewGroup parent, int viewType) { return(new RowController(getLayoutInflater() .inflate(R.layout.row, parent, false), imageLoader)); } void setVideos(Cursor videos) { this.videos=videos; notifyDataSetChanged(); } @Override public void onBindViewHolder(RowController holder, int position) { videos.moveToPosition(position); holder.bindModel(videos); } @Override public int getItemCount() { if (videos==null) { return(0); } return(videos.getCount()); } } }
jorgereina1986/cw-omnibus
RecyclerView/VideoList/src/com/commonsware/android/recyclerview/videolist/MainActivity.java
Java
apache-2.0
3,052
/* * @test /nodynamiccopyright/ * @bug 8024207 * @summary javac crash in Flow$AssignAnalyzer.visitIdent * @compile/fail/ref=FlowCrashTest.out -XDrawDiagnostics FlowCrashTest.java */ import java.util.*; import java.util.stream.*; public class FlowCrashTest { static class ViewId { } public void crash() { Map<ViewId,String> viewToProfile = null; new TreeMap<>(viewToProfile.entrySet().stream() .collect(Collectors.toMap((vid, prn) -> prn, (vid, prn) -> Arrays.asList(vid), (a, b) -> { a.addAll(b); return a; }))); } }
rokn/Count_Words_2015
testing/openjdk2/langtools/test/tools/javac/T8024207/FlowCrashTest.java
Java
mit
674
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * 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.alibaba.rocketmq.common.protocol.body; import java.util.HashSet; import java.util.Set; import com.alibaba.rocketmq.remoting.protocol.RemotingSerializable; /** * @author shijia.wxr<[email protected]> * @since 2013-8-10 */ public class TopicList extends RemotingSerializable { private Set<String> topicList = new HashSet<String>(); private String brokerAddr; public Set<String> getTopicList() { return topicList; } public void setTopicList(Set<String> topicList) { this.topicList = topicList; } public String getBrokerAddr() { return brokerAddr; } public void setBrokerAddr(String brokerAddr) { this.brokerAddr = brokerAddr; } }
carlvine500/rocketmq
rocketmq-common/src/main/java/com/alibaba/rocketmq/common/protocol/body/TopicList.java
Java
apache-2.0
1,354
/* * Copyright 2000-2015 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. */ package com.intellij.codeInsight.template.postfix.settings; import com.intellij.codeInsight.intention.impl.config.BeforeAfterActionMetaData; import com.intellij.codeInsight.intention.impl.config.TextDescriptor; import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.lang.UrlClassLoader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; public final class PostfixTemplateMetaData extends BeforeAfterActionMetaData { public static final String KEY = "$key"; public static final PostfixTemplateMetaData EMPTY_METADATA = new PostfixTemplateMetaData(); private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.template.postfix.settings.PostfixTemplateMetaData"); private static final String DESCRIPTION_FOLDER = "postfixTemplates"; @NotNull static PostfixTemplateMetaData createMetaData(@Nullable PostfixTemplate template) { if (template == null) return EMPTY_METADATA; return new PostfixTemplateMetaData(template); } private URL urlDir = null; private PostfixTemplate myTemplate; public PostfixTemplateMetaData(PostfixTemplate template) { super(template.getClass().getClassLoader(), template.getClass().getSimpleName()); myTemplate = template; } PostfixTemplateMetaData() { super(EMPTY_DESCRIPTION, EMPTY_EXAMPLE, EMPTY_EXAMPLE); } @NotNull @Override public TextDescriptor[] getExampleUsagesBefore() { return decorateTextDescriptor(super.getExampleUsagesBefore()); } @NotNull private TextDescriptor[] decorateTextDescriptor(TextDescriptor[] before) { List<TextDescriptor> list = ContainerUtil.newArrayList(); for (final TextDescriptor descriptor : before) { list.add(new TextDescriptor() { @Override public String getText() throws IOException { return StringUtil.replace(descriptor.getText(), KEY, myTemplate.getKey()); } @Override public String getFileName() { return descriptor.getFileName(); } }); } return list.toArray(new TextDescriptor[list.size()]); } @NotNull @Override public TextDescriptor[] getExampleUsagesAfter() { return decorateTextDescriptor(super.getExampleUsagesAfter()); } @NotNull @Override protected URL getDirURL() { if (urlDir != null) { return urlDir; } final URL pageURL = myLoader.getResource(DESCRIPTION_FOLDER + "/" + myDescriptionDirectoryName + "/" + DESCRIPTION_FILE_NAME); if (LOG.isDebugEnabled()) { LOG.debug("Path:" + DESCRIPTION_FOLDER + "/" + myDescriptionDirectoryName); LOG.debug("URL:" + pageURL); } if (pageURL != null) { try { final String url = pageURL.toExternalForm(); urlDir = UrlClassLoader.internProtocol(new URL(url.substring(0, url.lastIndexOf('/')))); return urlDir; } catch (MalformedURLException e) { LOG.error(e); } } return null; } }
idea4bsd/idea4bsd
platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplateMetaData.java
Java
apache-2.0
3,854
/* * Copyright (c) 1997, 1998, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 com.sun.java.swing.plaf.motif; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.BasicArrowButton; import java.awt.*; import java.awt.event.*; /** * Motif scroll bar button. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is appropriate * for short term storage or RMI between applications running the same * version of Swing. A future release of Swing will provide support for * long term persistence. */ public class MotifScrollBarButton extends BasicArrowButton { private Color darkShadow = UIManager.getColor("controlShadow"); private Color lightShadow = UIManager.getColor("controlLtHighlight"); public MotifScrollBarButton(int direction) { super(direction); switch (direction) { case NORTH: case SOUTH: case EAST: case WEST: this.direction = direction; break; default: throw new IllegalArgumentException("invalid direction"); } setRequestFocusEnabled(false); setOpaque(true); setBackground(UIManager.getColor("ScrollBar.background")); setForeground(UIManager.getColor("ScrollBar.foreground")); } public Dimension getPreferredSize() { switch (direction) { case NORTH: case SOUTH: return new Dimension(11, 12); case EAST: case WEST: default: return new Dimension(12, 11); } } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } public boolean isFocusTraversable() { return false; } public void paint(Graphics g) { int w = getWidth(); int h = getHeight(); if (isOpaque()) { g.setColor(getBackground()); g.fillRect(0, 0, w, h); } boolean isPressed = getModel().isPressed(); Color lead = (isPressed) ? darkShadow : lightShadow; Color trail = (isPressed) ? lightShadow : darkShadow; Color fill = getBackground(); int cx = w / 2; int cy = h / 2; int s = Math.min(w, h); switch (direction) { case NORTH: g.setColor(lead); g.drawLine(cx, 0, cx, 0); for (int x = cx - 1, y = 1, dx = 1; y <= s - 2; y += 2) { g.setColor(lead); g.drawLine(x, y, x, y); if (y >= (s - 2)) { g.drawLine(x, y + 1, x, y + 1); } g.setColor(fill); g.drawLine(x + 1, y, x + dx, y); if (y < (s - 2)) { g.drawLine(x, y + 1, x + dx + 1, y + 1); } g.setColor(trail); g.drawLine(x + dx + 1, y, x + dx + 1, y); if (y >= (s - 2)) { g.drawLine(x + 1, y + 1, x + dx + 1, y + 1); } dx += 2; x -= 1; } break; case SOUTH: g.setColor(trail); g.drawLine(cx, s, cx, s); for (int x = cx - 1, y = s - 1, dx = 1; y >= 1; y -= 2) { g.setColor(lead); g.drawLine(x, y, x, y); if (y <= 2) { g.drawLine(x, y - 1, x + dx + 1, y - 1); } g.setColor(fill); g.drawLine(x + 1, y, x + dx, y); if (y > 2) { g.drawLine(x, y - 1, x + dx + 1, y - 1); } g.setColor(trail); g.drawLine(x + dx + 1, y, x + dx + 1, y); dx += 2; x -= 1; } break; case EAST: g.setColor(lead); g.drawLine(s, cy, s, cy); for (int y = cy - 1, x = s - 1, dy = 1; x >= 1; x -= 2) { g.setColor(lead); g.drawLine(x, y, x, y); if (x <= 2) { g.drawLine(x - 1, y, x - 1, y + dy + 1); } g.setColor(fill); g.drawLine(x, y + 1, x, y + dy); if (x > 2) { g.drawLine(x - 1, y, x - 1, y + dy + 1); } g.setColor(trail); g.drawLine(x, y + dy + 1, x, y + dy + 1); dy += 2; y -= 1; } break; case WEST: g.setColor(trail); g.drawLine(0, cy, 0, cy); for (int y = cy - 1, x = 1, dy = 1; x <= s - 2; x += 2) { g.setColor(lead); g.drawLine(x, y, x, y); if (x >= (s - 2)) { g.drawLine(x + 1, y, x + 1, y); } g.setColor(fill); g.drawLine(x, y + 1, x, y + dy); if (x < (s - 2)) { g.drawLine(x + 1, y, x + 1, y + dy + 1); } g.setColor(trail); g.drawLine(x, y + dy + 1, x, y + dy + 1); if (x >= (s - 2)) { g.drawLine(x + 1, y + 1, x + 1, y + dy + 1); } dy += 2; y -= 1; } break; } } }
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifScrollBarButton.java
Java
mit
6,694
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.platform.memory; import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.reallocateUnpooled; import static org.apache.ignite.internal.processors.platform.memory.PlatformMemoryUtils.releaseUnpooled; /** * Interop un-pooled memory chunk. */ public class PlatformUnpooledMemory extends PlatformAbstractMemory { /** * Constructor. * * @param memPtr Cross-platform memory pointer. */ public PlatformUnpooledMemory(long memPtr) { super(memPtr); } /** {@inheritDoc} */ @Override public void reallocate(int cap) { // Try doubling capacity to avoid excessive allocations. int doubledCap = PlatformMemoryUtils.capacity(memPtr) << 1; if (doubledCap > cap) cap = doubledCap; reallocateUnpooled(memPtr, cap); } /** {@inheritDoc} */ @Override public void close() { releaseUnpooled(memPtr); } }
agoncharuk/ignite
modules/platform/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformUnpooledMemory.java
Java
apache-2.0
1,786
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * 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. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2002-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4cheri.data; import org.dcm4che.data.Dataset; import org.dcm4che.data.DcmDecodeParam; import org.dcm4che.data.DcmElement; import org.dcm4che.data.DcmValueException; import org.dcm4che.data.FileFormat; import org.dcm4che.data.SpecificCharacterSet; import org.dcm4che.dict.Tags; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import javax.imageio.stream.ImageInputStream; /** Implementation of <code>Dataset</code> container objects. * * @author <a href="mailto:[email protected]">gunter zeilinger</a> * @author <a href="mailto:[email protected]">joseph foraci</a> * @since March 2002 * @version $Revision: 3994 $ $Date: 2006-05-18 06:10:23 +0800 (周四, 18 5月 2006) $ * @see "DICOM Part 5: Data Structures and Encoding, 7. The Data Set" */ final class DatasetImpl extends BaseDatasetImpl implements org.dcm4che.data.Dataset { private final Dataset parent; private SpecificCharacterSet charset = null; private String privateCreatorID = null; private long itemOffset = -1L; DatasetImpl() { this(null); } DatasetImpl(Dataset parent) { this.parent = parent; } public void setPrivateCreatorID(String privateCreatorID) { this.privateCreatorID = privateCreatorID; } public String getPrivateCreatorID() { return privateCreatorID != null ? privateCreatorID : parent != null ? parent.getPrivateCreatorID() : null; } public SpecificCharacterSet getSpecificCharacterSet() { return charset != null ? charset : parent != null ? parent.getSpecificCharacterSet() : null; } public final Dataset getParent() { return parent; } public final Dataset setItemOffset(long itemOffset) { this.itemOffset = itemOffset; return this; } public final long getItemOffset() { if (itemOffset != -1L || list.isEmpty()) return itemOffset; long elm1pos = ((DcmElement)list.get(0)).getStreamPosition(); return elm1pos == -1L ? -1L : elm1pos - 8L; } public DcmElement putSQ(int tag) { return put(new SQElement(tag, this)); } protected DcmElement put(DcmElement newElem) { if ((newElem.tag() >>> 16) < 4) { log.warn("Ignore illegal attribute " + newElem); return newElem; } if (newElem.tag() == Tags.SpecificCharacterSet) { try { this.charset = SpecificCharacterSet.valueOf(newElem.getStrings(null)); } catch (Exception ex) { log.warn("Failed to consider specified Charset!"); this.charset = null; } } return super.put(newElem); } public DcmElement remove(int tag) { if (tag == Tags.SpecificCharacterSet) charset = null; return super.remove(tag); } public void clear() { super.clear(); charset = null; totLen = 0; } public void readFile(InputStream in, FileFormat format, int stopTag) throws IOException, DcmValueException { DcmParserImpl parser = new DcmParserImpl(in); parser.setDcmHandler(getDcmHandler()); parser.parseDcmFile(format, stopTag); } public void readDataset(InputStream in, DcmDecodeParam param, int stopTag) throws IOException, DcmValueException { DcmParserImpl parser = new DcmParserImpl(in); parser.setDcmHandler(getDcmHandler()); parser.parseDataset(param, stopTag); } public void readFile(ImageInputStream in, FileFormat format, int stopTag) throws IOException, DcmValueException { DcmParserImpl parser = new DcmParserImpl(in); parser.setDcmHandler(getDcmHandler()); parser.parseDcmFile(format, stopTag); } public void readFile(File f, FileFormat format, int stopTag) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(f)); try { readFile(in, format, stopTag); } finally { try { in.close(); } catch (IOException ignore) {} } } }
medicayun/medicayundicom
dcm4che14/tags/DCM4CHE_2_14_22_TAGA/src/java/org/dcm4cheri/data/DatasetImpl.java
Java
apache-2.0
6,114
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.Not; /** * Interface for normal and cached NOT criteria. */ public interface IAbstractNotCriterium { }
guiquanz/binnavi
src/main/java/com/google/security/zynamics/binnavi/Gui/CriteriaDialog/Conditions/Not/IAbstractNotCriterium.java
Java
apache-2.0
760
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Views.Module.Component; import com.google.security.zynamics.zylib.disassembly.FunctionType; /** * Pair of function types and names that is used to sort function tables in a special way. */ public final class CFunctionNameTypePair { /** * Name of a function. */ private final String m_name; /** * Type of a function. */ private final FunctionType m_functionType; /** * Creates a new pair of function name and function type. * * @param name Name of a function. * @param functionType Type of a function. */ public CFunctionNameTypePair(final String name, final FunctionType functionType) { m_name = name; m_functionType = functionType; } /** * Returns the function type. * * @return The function type. */ public FunctionType getFunctionType() { return m_functionType; } /** * Returns the function name. * * @return The function name. */ public String getName() { return m_name; } @Override public String toString() { return m_name; } }
guiquanz/binnavi
src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Nodes/Views/Module/Component/CFunctionNameTypePair.java
Java
apache-2.0
1,705
/* * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4501660 * @summary change diagnostic of -help as 'print this help message and exit' * (actually, verify -help does not cause premature exit) */ import java.io.*; import java.util.zip.*; public class T4501660 { public static void main(String[] args) throws Exception { new T4501660().run(); } public void run() throws IOException { String testClasses = System.getProperty("test.classes", "."); String output = javap("-classpath", testClasses, "-help", "T4501660"); verify(output, "-public", "-protected", "-private", // check -help output is present "class T4501660" // check class output is present ); if (errors > 0) throw new Error(errors + " found."); } String javap(String... args) { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); //sun.tools.javap.Main.entry(args); int rc = com.sun.tools.javap.Main.run(args, out); if (rc != 0) throw new Error("javap failed. rc=" + rc); out.close(); System.out.println(sw); return sw.toString(); } void verify(String output, String... expects) { for (String expect: expects) { if (output.indexOf(expect)< 0) error(expect + " not found"); } } void error(String msg) { System.err.println(msg); errors++; } int errors; }
rokn/Count_Words_2015
testing/openjdk2/langtools/test/tools/javap/T4501660.java
Java
mit
2,579
/* * Copyright (c) 1996, 2002, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 java.awt.image; import java.awt.image.ImageConsumer; import java.awt.image.ColorModel; import java.util.Hashtable; import java.awt.Rectangle; /** * An ImageFilter class for scaling images using a simple area averaging * algorithm that produces smoother results than the nearest neighbor * algorithm. * <p>This class extends the basic ImageFilter Class to scale an existing * image and provide a source for a new image containing the resampled * image. The pixels in the source image are blended to produce pixels * for an image of the specified size. The blending process is analogous * to scaling up the source image to a multiple of the destination size * using pixel replication and then scaling it back down to the destination * size by simply averaging all the pixels in the supersized image that * fall within a given pixel of the destination image. If the data from * the source is not delivered in TopDownLeftRight order then the filter * will back off to a simple pixel replication behavior and utilize the * requestTopDownLeftRightResend() method to refilter the pixels in a * better way at the end. * <p>It is meant to be used in conjunction with a FilteredImageSource * object to produce scaled versions of existing images. Due to * implementation dependencies, there may be differences in pixel values * of an image filtered on different platforms. * * @see FilteredImageSource * @see ReplicateScaleFilter * @see ImageFilter * * @author Jim Graham */ public class AreaAveragingScaleFilter extends ReplicateScaleFilter { private static final ColorModel rgbmodel = ColorModel.getRGBdefault(); private static final int neededHints = (TOPDOWNLEFTRIGHT | COMPLETESCANLINES); private boolean passthrough; private float reds[], greens[], blues[], alphas[]; private int savedy; private int savedyrem; /** * Constructs an AreaAveragingScaleFilter that scales the pixels from * its source Image as specified by the width and height parameters. * @param width the target width to scale the image * @param height the target height to scale the image */ public AreaAveragingScaleFilter(int width, int height) { super(width, height); } /** * Detect if the data is being delivered with the necessary hints * to allow the averaging algorithm to do its work. * <p> * Note: This method is intended to be called by the * <code>ImageProducer</code> of the <code>Image</code> whose * pixels are being filtered. Developers using * this class to filter pixels from an image should avoid calling * this method directly since that operation could interfere * with the filtering operation. * @see ImageConsumer#setHints */ public void setHints(int hints) { passthrough = ((hints & neededHints) != neededHints); super.setHints(hints); } private void makeAccumBuffers() { reds = new float[destWidth]; greens = new float[destWidth]; blues = new float[destWidth]; alphas = new float[destWidth]; } private int[] calcRow() { float origmult = ((float) srcWidth) * srcHeight; if (outpixbuf == null || !(outpixbuf instanceof int[])) { outpixbuf = new int[destWidth]; } int[] outpix = (int[]) outpixbuf; for (int x = 0; x < destWidth; x++) { float mult = origmult; int a = Math.round(alphas[x] / mult); if (a <= 0) { a = 0; } else if (a >= 255) { a = 255; } else { // un-premultiply the components (by modifying mult here, we // are effectively doing the divide by mult and divide by // alpha in the same step) mult = alphas[x] / 255; } int r = Math.round(reds[x] / mult); int g = Math.round(greens[x] / mult); int b = Math.round(blues[x] / mult); if (r < 0) {r = 0;} else if (r > 255) {r = 255;} if (g < 0) {g = 0;} else if (g > 255) {g = 255;} if (b < 0) {b = 0;} else if (b > 255) {b = 255;} outpix[x] = (a << 24 | r << 16 | g << 8 | b); } return outpix; } private void accumPixels(int x, int y, int w, int h, ColorModel model, Object pixels, int off, int scansize) { if (reds == null) { makeAccumBuffers(); } int sy = y; int syrem = destHeight; int dy, dyrem; if (sy == 0) { dy = 0; dyrem = 0; } else { dy = savedy; dyrem = savedyrem; } while (sy < y + h) { int amty; if (dyrem == 0) { for (int i = 0; i < destWidth; i++) { alphas[i] = reds[i] = greens[i] = blues[i] = 0f; } dyrem = srcHeight; } if (syrem < dyrem) { amty = syrem; } else { amty = dyrem; } int sx = 0; int dx = 0; int sxrem = 0; int dxrem = srcWidth; float a = 0f, r = 0f, g = 0f, b = 0f; while (sx < w) { if (sxrem == 0) { sxrem = destWidth; int rgb; if (pixels instanceof byte[]) { rgb = ((byte[]) pixels)[off + sx] & 0xff; } else { rgb = ((int[]) pixels)[off + sx]; } // getRGB() always returns non-premultiplied components rgb = model.getRGB(rgb); a = rgb >>> 24; r = (rgb >> 16) & 0xff; g = (rgb >> 8) & 0xff; b = rgb & 0xff; // premultiply the components if necessary if (a != 255.0f) { float ascale = a / 255.0f; r *= ascale; g *= ascale; b *= ascale; } } int amtx; if (sxrem < dxrem) { amtx = sxrem; } else { amtx = dxrem; } float mult = ((float) amtx) * amty; alphas[dx] += mult * a; reds[dx] += mult * r; greens[dx] += mult * g; blues[dx] += mult * b; if ((sxrem -= amtx) == 0) { sx++; } if ((dxrem -= amtx) == 0) { dx++; dxrem = srcWidth; } } if ((dyrem -= amty) == 0) { int outpix[] = calcRow(); do { consumer.setPixels(0, dy, destWidth, 1, rgbmodel, outpix, 0, destWidth); dy++; } while ((syrem -= amty) >= amty && amty == srcHeight); } else { syrem -= amty; } if (syrem == 0) { syrem = destHeight; sy++; off += scansize; } } savedyrem = dyrem; savedy = dy; } /** * Combine the components for the delivered byte pixels into the * accumulation arrays and send on any averaged data for rows of * pixels that are complete. If the correct hints were not * specified in the setHints call then relay the work to our * superclass which is capable of scaling pixels regardless of * the delivery hints. * <p> * Note: This method is intended to be called by the * <code>ImageProducer</code> of the <code>Image</code> * whose pixels are being filtered. Developers using * this class to filter pixels from an image should avoid calling * this method directly since that operation could interfere * with the filtering operation. * @see ReplicateScaleFilter */ public void setPixels(int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize) { if (passthrough) { super.setPixels(x, y, w, h, model, pixels, off, scansize); } else { accumPixels(x, y, w, h, model, pixels, off, scansize); } } /** * Combine the components for the delivered int pixels into the * accumulation arrays and send on any averaged data for rows of * pixels that are complete. If the correct hints were not * specified in the setHints call then relay the work to our * superclass which is capable of scaling pixels regardless of * the delivery hints. * <p> * Note: This method is intended to be called by the * <code>ImageProducer</code> of the <code>Image</code> * whose pixels are being filtered. Developers using * this class to filter pixels from an image should avoid calling * this method directly since that operation could interfere * with the filtering operation. * @see ReplicateScaleFilter */ public void setPixels(int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize) { if (passthrough) { super.setPixels(x, y, w, h, model, pixels, off, scansize); } else { accumPixels(x, y, w, h, model, pixels, off, scansize); } } }
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/java/awt/image/AreaAveragingScaleFilter.java
Java
mit
11,006
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.service; public interface IReadCommand { public String getKeyspace(); public long getTimeout(); }
lynchlee/play-jmx
src/main/java/org/apache/cassandra/service/IReadCommand.java
Java
apache-2.0
942
/* * Copyright 2000-2012 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. */ package com.intellij.psi.codeStyle.arrangement; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.arrangement.std.ArrangementSettingsToken; import com.intellij.util.containers.ContainerUtilRt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; /** * Not thread-safe. * * @author Denis Zhdanov * @since 7/20/12 4:50 PM */ public class JavaElementArrangementEntry extends DefaultArrangementEntry implements TypeAwareArrangementEntry, NameAwareArrangementEntry,ModifierAwareArrangementEntry { @NotNull private final Set<ArrangementSettingsToken> myModifiers = ContainerUtilRt.newHashSet(); @NotNull private final Set<ArrangementSettingsToken> myTypes = ContainerUtilRt.newHashSet(); @NotNull private final ArrangementSettingsToken myType; @Nullable private final String myName; public JavaElementArrangementEntry(@Nullable ArrangementEntry parent, @NotNull TextRange range, @NotNull ArrangementSettingsToken type, @Nullable String name, boolean canBeMatched) { this(parent, range.getStartOffset(), range.getEndOffset(), type, name, canBeMatched); } public JavaElementArrangementEntry(@Nullable ArrangementEntry parent, int startOffset, int endOffset, @NotNull ArrangementSettingsToken type, @Nullable String name, boolean canBeArranged) { super(parent, startOffset, endOffset, canBeArranged); myType = type; myTypes.add(type); myName = name; } @NotNull @Override public Set<ArrangementSettingsToken> getModifiers() { return myModifiers; } public void addModifier(@NotNull ArrangementSettingsToken modifier) { myModifiers.add(modifier); } @Nullable @Override public String getName() { return myName; } @NotNull @Override public Set<ArrangementSettingsToken> getTypes() { return myTypes; } @NotNull public ArrangementSettingsToken getType() { return myType; } @Override public String toString() { return String.format( "[%d; %d): %s %s %s", getStartOffset(), getEndOffset(), StringUtil.join(myModifiers, " ").toLowerCase(), myTypes.iterator().next().toString().toLowerCase(), myName == null ? "<no name>" : myName ); } }
idea4bsd/idea4bsd
java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaElementArrangementEntry.java
Java
apache-2.0
3,254
/* * Copyright 2000-2011 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. */ package com.intellij.lang.ant.config.impl.artifacts; import com.intellij.compiler.ant.*; import com.intellij.compiler.ant.taskdefs.Property; import com.intellij.lang.ant.config.impl.BuildFileProperty; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactPropertiesProvider; import com.intellij.packaging.elements.ArtifactAntGenerationContext; import com.intellij.util.ArrayUtil; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.ant.model.impl.artifacts.JpsAntArtifactExtensionImpl; /** * @author nik */ public class AntArtifactBuildExtension extends ChunkBuildExtension { @Override public void generateTasksForArtifact(Artifact artifact, boolean preprocessing, ArtifactAntGenerationContext context, CompositeGenerator generator) { final ArtifactPropertiesProvider provider; if (preprocessing) { provider = AntArtifactPreProcessingPropertiesProvider.getInstance(); } else { provider = AntArtifactPostprocessingPropertiesProvider.getInstance(); } final AntArtifactProperties properties = (AntArtifactProperties)artifact.getProperties(provider); if (properties != null && properties.isEnabled()) { final String path = VfsUtil.urlToPath(properties.getFileUrl()); String fileName = PathUtil.getFileName(path); String dirPath = PathUtil.getParentPath(path); final String relativePath = GenerationUtils.toRelativePath(dirPath, BuildProperties.getProjectBaseDir(context.getProject()), BuildProperties.getProjectBaseDirProperty(), context.getGenerationOptions()); final Tag ant = new Tag("ant", Pair.create("antfile", fileName), Pair.create("target", properties.getTargetName()), Pair.create("dir", relativePath)); final String outputPath = BuildProperties.propertyRef(context.getArtifactOutputProperty(artifact)); ant.add(new Property(JpsAntArtifactExtensionImpl.ARTIFACT_OUTPUT_PATH_PROPERTY, outputPath)); for (BuildFileProperty property : properties.getUserProperties()) { ant.add(new Property(property.getPropertyName(), property.getPropertyValue())); } generator.add(ant); } } @NotNull @Override public String[] getTargets(ModuleChunk chunk) { return ArrayUtil.EMPTY_STRING_ARRAY; } @Override public void process(Project project, ModuleChunk chunk, GenerationOptions genOptions, CompositeGenerator generator) { } }
asedunov/intellij-community
plugins/ant/src/com/intellij/lang/ant/config/impl/artifacts/AntArtifactBuildExtension.java
Java
apache-2.0
3,319
class Test { { Object o = null; Comparable<String> c = <error descr="Variable 'o' is already defined in the scope">o</error> -> 42; } }
hurricup/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/AlreadyUsedParamName.java
Java
apache-2.0
147
package com.badlogic.gdx.graphics.g3d.particles.renderers; import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels; import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels.ColorInitializer; import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels.Rotation2dInitializer; import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels.ScaleInitializer; import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels.TextureRegionInitializer; import com.badlogic.gdx.graphics.g3d.particles.ParticleControllerComponent; import com.badlogic.gdx.graphics.g3d.particles.batches.BillboardParticleBatch; import com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch; import com.badlogic.gdx.graphics.g3d.particles.batches.PointSpriteParticleBatch; /** A {@link ParticleControllerRenderer} which will render particles as point sprites to a {@link PointSpriteParticleBatch} . * @author Inferno */ public class PointSpriteRenderer extends ParticleControllerRenderer<PointSpriteControllerRenderData, PointSpriteParticleBatch> { public PointSpriteRenderer(){ super(new PointSpriteControllerRenderData()); } public PointSpriteRenderer(PointSpriteParticleBatch batch){ this(); setBatch(batch); } @Override public void allocateChannels () { renderData.positionChannel = controller.particles.addChannel(ParticleChannels.Position); renderData.regionChannel = controller.particles.addChannel(ParticleChannels.TextureRegion, TextureRegionInitializer.get()); renderData.colorChannel = controller.particles.addChannel(ParticleChannels.Color, ColorInitializer.get()); renderData.scaleChannel = controller.particles.addChannel(ParticleChannels.Scale, ScaleInitializer.get()); renderData.rotationChannel = controller.particles.addChannel(ParticleChannels.Rotation2D, Rotation2dInitializer.get()); } @Override public boolean isCompatible (ParticleBatch<?> batch) { return batch instanceof PointSpriteParticleBatch; } @Override public ParticleControllerComponent copy () { return new PointSpriteRenderer(batch); } }
GreenLightning/libgdx
gdx/src/com/badlogic/gdx/graphics/g3d/particles/renderers/PointSpriteRenderer.java
Java
apache-2.0
2,065
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.tools.findbugs.plugin; /** * This class has synchronized(this) statement and is used to test * SynchronizedThisDetector. */ class SimpleSynchronizedThis { private int mCounter = 0; void synchronizedThis() { synchronized (this) { mCounter++; } } }
XiaosongWei/chromium-crosswalk
tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedThis.java
Java
bsd-3-clause
479
/* * Copyright (c) 2000, 2002, 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 sun.jvm.hotspot; import sun.jvm.hotspot.debugger.*; import sun.jvm.hotspot.types.*; import sun.jvm.hotspot.types.basic.*; /** This class implements the compiler-specific access to the vtbl for a given C++ type. As it happens, on Win32 (at least for Visual C++ 6.0) the name mangling for vtbls is very straightforward. We only need to ensure that these symbols are exported from the HotSpot DLL, which is done with a .DEF file. This class is named "Win32VtblAccess" because it is not necessarily HotSpot-specific. */ public class Win32VtblAccess extends BasicVtblAccess { public Win32VtblAccess(SymbolLookup symbolLookup, String[] dllNames) { super(symbolLookup, dllNames); } protected String vtblSymbolForType(Type type) { return "??_7" + type.getName() + "@@6B@"; } }
rokn/Count_Words_2015
testing/openjdk2/hotspot/agent/src/share/classes/sun/jvm/hotspot/Win32VtblAccess.java
Java
mit
1,903
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.spring.issues.packagescan; import org.apache.camel.builder.RouteBuilder; /** * */ public class MyCoolRoute extends RouteBuilder { @Override public void configure() throws Exception { from("direct:cool").routeId("cool").to("mock:cool"); } }
CandleCandle/camel
components/camel-spring/src/test/java/org/apache/camel/spring/issues/packagescan/MyCoolRoute.java
Java
apache-2.0
1,098
package hudson.util; import hudson.model.AdministrativeMonitor; import hudson.Extension; /** * A convenient {@link AdministrativeMonitor} implementations that show an error message * and optional stack trace. This is useful for notifying a non-fatal error to the administrator. * * <p> * These errors are registered when instances are created. No need to use {@link Extension}. * * @author Kohsuke Kawaguchi */ public class AdministrativeError extends AdministrativeMonitor { public final String message; public final String title; public final Throwable details; /** * @param id * Unique ID that distinguishes this error from other errors. * Must remain the same across Hudson executions. Use a caller class name, or something like that. * @param title * A title of the problem. This is used as the HTML title * of the details page. Should be just one sentence, like "ZFS migration error." * @param message * A short description of the problem. This is used in the "/manage" page, and can include HTML, but it should be still short. * @param details * An exception indicating the problem. The administrator can see this once they click "more details". */ public AdministrativeError(String id, String title, String message, Throwable details) { super(id); this.message = message; this.title = title; this.details = details; all().add(this); } public boolean isActivated() { return true; } }
sincere520/testGitRepo
hudson-core/src/main/java/hudson/util/AdministrativeError.java
Java
mit
1,569
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.views.image; import com.facebook.drawee.drawable.ScalingUtils; import org.junit.Rule; import org.junit.runner.RunWith; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) public class ImageResizeModeTest { @Rule public PowerMockRule rule = new PowerMockRule(); @Test public void testImageResizeMode() { assertThat(ImageResizeMode.toScaleType(null)) .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); assertThat(ImageResizeMode.toScaleType("contain")) .isEqualTo(ScalingUtils.ScaleType.FIT_CENTER); assertThat(ImageResizeMode.toScaleType("cover")) .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); assertThat(ImageResizeMode.toScaleType("stretch")) .isEqualTo(ScalingUtils.ScaleType.FIT_XY); assertThat(ImageResizeMode.toScaleType("center")) .isEqualTo(ScalingUtils.ScaleType.CENTER_INSIDE); // No resizeMode set assertThat(ImageResizeMode.defaultValue()) .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); } }
prayuditb/tryout-01
websocket/client/Client/node_modules/react-native/ReactAndroid/src/test/java/com/facebook/react/views/image/ImageResizeModeTest.java
Java
mit
1,688
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.file; import android.util.SparseArray; import org.apache.cordova.CallbackContext; /** * Holds pending runtime permission requests */ class PendingRequests { private int currentReqId = 0; private SparseArray<Request> requests = new SparseArray<Request>(); /** * Creates a request and adds it to the array of pending requests. Each created request gets a * unique result code for use with requestPermission() * @param rawArgs The raw arguments passed to the plugin * @param action The action this request corresponds to (get file, etc.) * @param callbackContext The CallbackContext for this plugin call * @return The request code that can be used to retrieve the Request object */ public synchronized int createRequest(String rawArgs, int action, CallbackContext callbackContext) { Request req = new Request(rawArgs, action, callbackContext); requests.put(req.requestCode, req); return req.requestCode; } /** * Gets the request corresponding to this request code and removes it from the pending requests * @param requestCode The request code for the desired request * @return The request corresponding to the given request code or null if such a * request is not found */ public synchronized Request getAndRemove(int requestCode) { Request result = requests.get(requestCode); requests.remove(requestCode); return result; } /** * Holds the options and CallbackContext for a call made to the plugin. */ public class Request { // Unique int used to identify this request in any Android permission callback private int requestCode; // Action to be performed after permission request result private int action; // Raw arguments passed to plugin private String rawArgs; // The callback context for this plugin request private CallbackContext callbackContext; private Request(String rawArgs, int action, CallbackContext callbackContext) { this.rawArgs = rawArgs; this.action = action; this.callbackContext = callbackContext; this.requestCode = currentReqId ++; } public int getAction() { return this.action; } public String getRawArgs() { return rawArgs; } public CallbackContext getCallbackContext() { return callbackContext; } } }
circular-code/ImageStream
www/plugins/cordova-plugin-file/src/android/PendingRequests.java
Java
mit
3,477
/* * 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.cluster.routing.allocation.decider; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; /** * An allocation decider that prevents multiple instances of the same shard to * be allocated on the same <tt>node</tt>. * * The {@value #SAME_HOST_SETTING} setting allows to perform a check to prevent * allocation of multiple instances of the same shard on a single <tt>host</tt>, * based on host name and host address. Defaults to `false`, meaning that no * check is performed by default. * * <p> * Note: this setting only applies if multiple nodes are started on the same * <tt>host</tt>. Allocations of multiple copies of the same shard on the same * <tt>node</tt> are not allowed independently of this setting. * </p> */ public class SameShardAllocationDecider extends AllocationDecider { public static final String NAME = "same_shard"; public static final String SAME_HOST_SETTING = "cluster.routing.allocation.same_shard.host"; private final boolean sameHost; @Inject public SameShardAllocationDecider(Settings settings) { super(settings); this.sameHost = settings.getAsBoolean(SAME_HOST_SETTING, false); } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { Iterable<ShardRouting> assignedShards = allocation.routingNodes().assignedShards(shardRouting); for (ShardRouting assignedShard : assignedShards) { if (node.nodeId().equals(assignedShard.currentNodeId())) { return allocation.decision(Decision.NO, NAME, "shard cannot be allocated on same node [%s] it already exists on", node.nodeId()); } } if (sameHost) { if (node.node() != null) { for (RoutingNode checkNode : allocation.routingNodes()) { if (checkNode.node() == null) { continue; } // check if its on the same host as the one we want to allocate to boolean checkNodeOnSameHost = false; if (Strings.hasLength(checkNode.node().getHostAddress()) && Strings.hasLength(node.node().getHostAddress())) { if (checkNode.node().getHostAddress().equals(node.node().getHostAddress())) { checkNodeOnSameHost = true; } } else if (Strings.hasLength(checkNode.node().getHostName()) && Strings.hasLength(node.node().getHostName())) { if (checkNode.node().getHostName().equals(node.node().getHostName())) { checkNodeOnSameHost = true; } } if (checkNodeOnSameHost) { for (ShardRouting assignedShard : assignedShards) { if (checkNode.nodeId().equals(assignedShard.currentNodeId())) { return allocation.decision(Decision.NO, NAME, "shard cannot be allocated on same host [%s] it already exists on", node.nodeId()); } } } } } } return allocation.decision(Decision.YES, NAME, "shard is not allocated to same node or host"); } }
wayeast/elasticsearch
core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/SameShardAllocationDecider.java
Java
apache-2.0
4,462
package org.apollo.net.release.r317; import org.apollo.game.event.impl.FirstItemActionEvent; import org.apollo.game.event.impl.ThirdPlayerActionEvent; import org.apollo.net.codec.game.DataOrder; import org.apollo.net.codec.game.DataType; import org.apollo.net.codec.game.GamePacket; import org.apollo.net.codec.game.GamePacketReader; import org.apollo.net.release.EventDecoder; /** * An {@link EventDecoder} for the {@link FirstItemActionEvent}. * @author Graham */ public final class ThirdPlayerActionDecoder extends EventDecoder<ThirdPlayerActionEvent> { @Override public ThirdPlayerActionEvent decode(GamePacket packet) { GamePacketReader reader = new GamePacketReader(packet); int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); return new ThirdPlayerActionEvent(id); } }
AWildridge/ProtoScape
src/org/apollo/net/release/r317/ThirdPlayerActionDecoder.java
Java
isc
823
/* * Copyright (c) 2011, Simon Kölsch * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package org.oark.psycoffee.parser; import java.util.regex.Pattern; import org.oark.psycoffee.core.Context; import org.oark.psycoffee.core.Packet; import org.oark.psycoffee.core.VarCollection; import org.oark.psycoffee.core.constants.Operators; public abstract class Parser { public void parse(String raw) { parse(raw, null); } //TODO write junit tests protected int getStringByBytes(int bytes, StringBuffer target, String raw[], int idx) { int bytesToRead = bytes; String[] lines = raw.clone(); //quickhack lines[idx] = lines[idx].split("\t")[1]; int lineIdx; for(lineIdx = idx; bytesToRead > 0; lineIdx++) { String line = lines[lineIdx]; if (line.getBytes().length < bytesToRead) { target.append(line+"\n"); bytesToRead -= line.getBytes().length+1; } else if (line.getBytes().length == bytesToRead) { target.append(line); bytesToRead -= line.getBytes().length; } else { byte[] tmp; tmp = line.getBytes(); byte[] part = new byte[bytesToRead]; for(int i=0;i<bytesToRead;i++) { part[i] = tmp[i]; } target.append(new String(part)); bytesToRead = 0; } } return lineIdx; } //TODO write junit tests protected int parseVar(String var, VarCollection vars, String raw[], int idx) { String first = ""; if(!"".equals(var)) { first = var.substring(0,1); } if (isOperator(first)) { int size = 0; String lineParts[] = var.split("\t"); String operator = lineParts[0].substring(0,1) ; String name = lineParts[0].substring(1); String nameParts[] = name.split("\\s"); if(nameParts.length == 2) { if (nameParts[1].matches("[0-9]*")) { size = new Integer(nameParts[1]); } else { //TODO PANIC MODE! SOMETHING BAD HAPPENED!!! BROKEN VAR!!! \o/ } name = nameParts[0]; } StringBuffer value = new StringBuffer(); if(nameParts.length == 2 && size > 0) { idx = getStringByBytes(size, value, raw, idx); } else { if(lineParts.length == 2) { value.append(lineParts[1]); } } vars.addVar(name,value.toString(),operator); } return idx; } //TODO write junit tests protected int parseVars(String raw[], VarCollection vars, int idx) { int i; for (i = idx; i < raw.length; i++) { String line = raw[i]; if ("".equals(line) || line.matches("[0-9]*")) { break; } else if (isMethod(line)) { break; } else if ("|".equals(line)) { break; } i = parseVar(line, vars,raw,i); } return i; } public void parse(String raw, Context context) { //TODO cleanup this mess! :-) String[] lines = raw.split("\n"); boolean gotMethod = false; Packet packet = new Packet(); packet.setPayload(""); packet.setMethod(""); VarCollection vars = packet.getRoutingVars(); StringBuffer payload = new StringBuffer(); long bytesToRead = 0; int entityStart = 0; for (int lineIdx = 0; lineIdx < lines.length; lineIdx++) { if (gotMethod == false) { lineIdx = parseVars(lines,vars,lineIdx); } String line = lines[lineIdx]; if(("".equals(line) || line.matches("[0-9]+")) && gotMethod == false) { if (gotMethod == false && line.matches("[0-9]+")) { packet.setEntityLength(new Long(line)); bytesToRead = packet.getEntityLength(); entityStart = lineIdx+1; } vars = packet.getEntityVars(); } else if (isMethod(line) && gotMethod == false) { packet.setMethod(line); gotMethod = true; if(entityStart != 0) { //calc length to read for(int i = entityStart; i <= lineIdx; i++) { bytesToRead -= lines[i].getBytes().length + 1; } } } else if (gotMethod == true) { if(entityStart == 0) { if ("|".equals(line)) { //finish packet and do callbacks packet.setPayload(payload.toString()); dispatch(packet, context); //reset gotMethod = false; packet = new Packet(); vars = packet.getRoutingVars(); payload = new StringBuffer(); } else { payload.append(line+"\n"); } } else if (bytesToRead > 0) { bytesToRead -= line.getBytes().length + 1; if (bytesToRead == 0) { payload.append(line); } else { payload.append(line+"\n"); } } else if (bytesToRead <= 0) { //TODO cleanup copy and paste section //finish packet and do callbacks packet.setPayload(payload.toString()); dispatch(packet, context); //reset gotMethod = false; packet = new Packet(); vars = packet.getRoutingVars(); payload = new StringBuffer(); } } else { if("|".equals(line)) { dispatch(packet, context); } } } } abstract protected void dispatch(Packet packet, Context context); protected static boolean isMethod(String method) { //TODO should be a little more efficient ;-) Pattern p = Pattern.compile("[a-zA-Z_]+"); return p.matcher(method).matches(); } protected static boolean isOperator(String operator) { //TODO should be a little more efficient ;-) for(int i=0; i < Operators.ALL_OPERATORS.length; i++) { if(Operators.ALL_OPERATORS[i].equals(operator)) { return true; } } return false; } }
echox/psyCoffee
src/org/oark/psycoffee/parser/Parser.java
Java
isc
6,105
package de.soulworks.dam.webservice.dao; import de.soulworks.dam.domain.Customer; import org.joda.time.Instant; import org.joda.time.ReadableInstant; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Christian Schmitz <[email protected] */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring/ektorp-config.xml") public class CustomerDaoTest { @Autowired @Qualifier("customerDao") CustomerDao customerDao; @Test public void testGetCustomer() { ReadableInstant now = new Instant(); String uid = "testCreateCustomer." + now.getMillis(); // Compose a customer Customer customer = Customer.create() .setUid(uid) .setName("Soulworks GmbH"); // Create the customer at the datastore customerDao.createCustomer(customer); // Get the same customer from the datastore Customer c = customerDao.getCustomer(uid); Assert.assertNotNull(c); } public void testGetCustomers() { } @Test public void testCreateCustomer() { ReadableInstant now = new Instant(); String uid = "testCreateCustomer." + now.getMillis(); // Compose a customer Customer customer = Customer.create() .setUid(uid) .setName("Company GmbH"); // Create the customer at the datastore customerDao.createCustomer(customer); // Check if we got an id and revision after creation Assert.assertNotNull(customer.getId()); Assert.assertNotNull(customer.getRevision()); // Get the same customer from the datastore Customer c = customerDao.getCustomer(uid); // Check wether we got a customer or not Assert.assertNotNull(c); // Compare the objects Assert.assertEquals(customer.getUid(), c.getUid()); Assert.assertEquals(customer.getName(), c.getName()); Assert.assertTrue(customer.equals(c)); } @Test public void testUpdateCustomer() { ReadableInstant now = new Instant(); String uid = "testUpdateCustomer." + now.getMillis(); // Compose a customer Customer customer = Customer.create() .setUid(uid) .setName("Company GmbH"); // Create the customer at the datastore customerDao.createCustomer(customer); // Get the same customer from the datastore customer.setName("Jockel GmbH"); customerDao.updateCustomer(customer); // Get the same customer from the datastore Customer c = customerDao.getCustomer(uid); Assert.assertEquals("Jockel GmbH", c.getName()); } public void testDeleteCustomer() { } }
butfriendly/friendly-dam
src/test/java/de/soulworks/dam/webservice/dao/CustomerDaoTest.java
Java
isc
2,848
package org.apollo; import org.apollo.fs.FileSystem; import org.apollo.game.model.World; import org.apollo.game.msg.MessageTranslator; import org.apollo.game.sync.ClientSynchronizer; import org.apollo.io.player.PlayerSerializerWorker; import org.apollo.service.Service; /** * Represents the context of this {@link Server}. * * @author Ryley Kimmel <[email protected]> */ public final class ServerContext { /** * The {@link Server} this {@link ServerContext} represents. */ private final Server server; /** * Constructs a new {@link ServerContext} with the specified {@link Server}. * * @param server The server this context represents. */ public ServerContext(Server server) { this.server = server; } /** * Checks if the specified service class exists. * * @param clazz The services class. * @return {@code true} if and only if the service exists otherwise * {@code false}. */ public <T extends Service> boolean serviceExists(Class<T> clazz) { return server.serviceExists(clazz); } /** * Returns the {@link Service} for the specified service class. * * @param clazz The services class. * @return The {@link Service} object for the specified service class. */ public <T extends Service> T getService(Class<T> clazz) { return server.getService(clazz); } /** * Returns this servers file system. */ public FileSystem getFileSystem() { return server.getFileSystem(); } /** * Returns this servers world. */ public World getWorld() { return server.getWorld(); } /** * Returns this servers message translator. */ public MessageTranslator getMessageTranslator() { return server.getMessageTranslator(); } /** * Returns this servers player serializer worker. */ public PlayerSerializerWorker getSerializerWorker() { return server.getSerializerWorker(); } /** * Returns this servers client synchronizer. */ public ClientSynchronizer getClientSynchronizer() { return server.getClientSynchronizer(); } }
atomicint/aj8
server/src/main/java/org/apollo/ServerContext.java
Java
isc
2,013
package org.ripple.bouncycastle.openpgp.examples; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.SignatureException; import java.util.Date; import org.ripple.bouncycastle.bcpg.ArmoredOutputStream; import org.ripple.bouncycastle.bcpg.HashAlgorithmTags; import org.ripple.bouncycastle.jce.provider.BouncyCastleProvider; import org.ripple.bouncycastle.openpgp.PGPEncryptedData; import org.ripple.bouncycastle.openpgp.PGPException; import org.ripple.bouncycastle.openpgp.PGPKeyPair; import org.ripple.bouncycastle.openpgp.PGPPublicKey; import org.ripple.bouncycastle.openpgp.PGPSecretKey; import org.ripple.bouncycastle.openpgp.PGPSignature; import org.ripple.bouncycastle.openpgp.operator.PGPDigestCalculator; import org.ripple.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; import org.ripple.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; import org.ripple.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder; /** * A simple utility class that generates a RSA PGPPublicKey/PGPSecretKey pair. * <p> * usage: RSAKeyPairGenerator [-a] identity passPhrase * <p> * Where identity is the name to be associated with the public key. The keys are placed * in the files pub.[asc|bpg] and secret.[asc|bpg]. */ public class RSAKeyPairGenerator { private static void exportKeyPair( OutputStream secretOut, OutputStream publicOut, PublicKey publicKey, PrivateKey privateKey, String identity, char[] passPhrase, boolean armor) throws IOException, InvalidKeyException, NoSuchProviderException, SignatureException, PGPException { if (armor) { secretOut = new ArmoredOutputStream(secretOut); } PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1); PGPKeyPair keyPair = new PGPKeyPair(PGPPublicKey.RSA_GENERAL, publicKey, privateKey, new Date()); PGPSecretKey secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, keyPair, identity, sha1Calc, null, null, new JcaPGPContentSignerBuilder(keyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.CAST5, sha1Calc).setProvider("BC").build(passPhrase)); secretKey.encode(secretOut); secretOut.close(); if (armor) { publicOut = new ArmoredOutputStream(publicOut); } PGPPublicKey key = secretKey.getPublicKey(); key.encode(publicOut); publicOut.close(); } public static void main( String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024); KeyPair kp = kpg.generateKeyPair(); if (args.length < 2) { System.out.println("RSAKeyPairGenerator [-a] identity passPhrase"); System.exit(0); } if (args[0].equals("-a")) { if (args.length < 3) { System.out.println("RSAKeyPairGenerator [-a] identity passPhrase"); System.exit(0); } FileOutputStream out1 = new FileOutputStream("secret.asc"); FileOutputStream out2 = new FileOutputStream("pub.asc"); exportKeyPair(out1, out2, kp.getPublic(), kp.getPrivate(), args[1], args[2].toCharArray(), true); } else { FileOutputStream out1 = new FileOutputStream("secret.bpg"); FileOutputStream out2 = new FileOutputStream("pub.bpg"); exportKeyPair(out1, out2, kp.getPublic(), kp.getPrivate(), args[0], args[1].toCharArray(), false); } } }
xdv/ripple-lib-java
ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/openpgp/examples/RSAKeyPairGenerator.java
Java
isc
4,359
package jp.ac.hiroshima_u.fu_midori.SSH2017.DroneSimulator.plugins.tactics.util.calling; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.*; /** * FilterManagementのテスト * * @author 遠藤拓斗 on 2017/06/10. */ public class FiltersManagementTest { private FiltersManagement sut; private List<CallingFilter> filters = new ArrayList<>(); @Before public void setUp() throws Exception { CallingFilter filterA = mock(CallingFilter.class); CallingFilter filterB = mock(CallingFilter.class); sut = new FiltersManagement(filterA, filterB); filters.add(filterA); filters.add(filterB); CallingFilter filterC = mock(CallingFilter.class); sut.addFilter(filterC); filters.add(filterC); } @Test public void before() throws Exception { sut.before(); for (CallingFilter filter : filters) { verify(filter).before(); } } @Test public void after() throws Exception { sut.after(); for (CallingFilter filter : filters) { verify(filter).after(); } } @Test public void informFinding() throws Exception { sut.informFinding(0, 1); for (CallingFilter filter : filters) { verify(filter).informFinding(0, 1); } } @Test public void informCalling() throws Exception { sut.informCalling(3); for (CallingFilter filter : filters) { verify(filter).informCalling(3); } } @Test public void informBeingCalled() throws Exception { sut.informBeingCalled(2); for (CallingFilter filter : filters) { verify(filter).informBeingCalled(2); } } @Test public void filter() throws Exception { IntStream stream = IntStream.range(0, 10); when(filters.get(0).filter(anyInt(), anyObject())).thenReturn(IntStream.range(0, 5)); when(filters.get(1).filter(anyInt(), anyObject())).thenReturn(IntStream.range(0, 6)); when(filters.get(2).filter(anyInt(), anyObject())).thenReturn(IntStream.range(0, 4)); int[] actual = sut.filter(0, stream).toArray(); for (CallingFilter filter : filters) { verify(filter).filter(anyInt(), anyObject()); } int[] expected = {0, 1, 2, 3}; assertThat(actual.length, is(expected.length)); for (int i = 0; i < expected.length; i++) { assertThat(actual[i], is(expected[i])); } } }
dsajgiouawj/DroneSimulator
src/test/java/jp/ac/hiroshima_u/fu_midori/SSH2017/DroneSimulator/plugins/tactics/util/calling/FiltersManagementTest.java
Java
mit
2,773
package gotoh; public class LocalGotoh extends Gotoh { public LocalGotoh(Sequence seq1, Sequence seq2, Substitutionmatrix subMatrix, double gapOpen, double gapExtend, int multiplicationFactor){ super(seq1, seq2, subMatrix, gapOpen, gapExtend, multiplicationFactor); initA(); } public void initA() { for (int i = 0; i < matrixA.length; i++) { matrixA[i][0] = 0; } for (int j = 0; j < matrixA[0].length; j++) { matrixA[0][j] = 0; } } public int getMaxValue(int x, int y) { int max = Math.max(matrixA[x-1][y-1] + submatrix.matrix[intSeq1[x-1]][intSeq2[y-1]], Math.max(matrixD[x][y], matrixI[x][y])); return (max < 0) ? 0 : max; } public Alignment getAlignmentScore() { int maxScore = Integer.MIN_VALUE; int xMax = 0; int yMax = 0; for (int i = 0; i < matrixA.length; i++) { for (int j = 0; j < matrixA[0].length; j++) { if (matrixA[i][j] > maxScore) { maxScore = matrixA[i][j]; xMax = i; yMax = j; } } } return new Alignment (maxScore / (double) submatrix.multiplicationFactor, xMax, yMax); } public void backtrack(Alignment ali) { StringBuilder alignedSeq1 = new StringBuilder(); StringBuilder alignedSeq2 = new StringBuilder(); int x = ali.xMax; int y = ali.yMax; while(x > 0 && y > 0 && matrixA[x][y] > 0){ if(matrixA[x][y] == matrixA[x-1][y-1] + submatrix.matrix[intSeq1[x-1]][intSeq2[y-1]] ){ alignedSeq1.append(seq1.getAsChar(x-1)); alignedSeq2.append(seq2.getAsChar(y-1)); x--; y--; } else if(matrixA[x][y] == matrixD[x][y]){ int gapLength = 1; alignedSeq1.append('-'); alignedSeq2.append(seq2.getAsChar(y-1)); while(matrixA[x][y - gapLength] + gapOpen + gapLength * gapExtend != matrixA[x][y]) { if(y > gapLength){ alignedSeq1.append('-'); alignedSeq2.append(seq2.getAsChar(y - gapLength - 1)); gapLength++; } else break; } y -= gapLength; } else if(matrixA[x][y] == matrixI[x][y]){ int gapLength = 1; alignedSeq1.append(seq1.getAsChar(x-1)); alignedSeq2.append('-'); while(matrixA[x - gapLength][y] + gapOpen + gapLength * gapExtend != matrixA[x][y]){ if(x > gapLength){ alignedSeq1.append(seq1.getAsChar(x - gapLength -1)); alignedSeq2.append('-'); gapLength++; } else break; } x -= gapLength; } } int firstPos = Math.max(x, y); for (int i = 1; i <= firstPos; i++) { if (x > i) { alignedSeq1.append(seq1.getAsChar(x - i)); alignedSeq2.append('-'); } else break; } for (int i = 1; i <= firstPos; i++) { if (y > i) { alignedSeq1.append('-'); alignedSeq2.append(seq2.getAsChar(y - i)); } else break; } int startAlignment = x + y; alignedSeq1 = alignedSeq1.reverse(); alignedSeq2 = alignedSeq2.reverse(); int endAlignment = alignedSeq1.length(); x = ali.xMax + 1; y = ali.yMax + 1; while (x <= seq1.length()) { alignedSeq1.append(seq1.getAsChar(x-1)); alignedSeq2.append('-'); x++; } while (y <= seq2.length()) { alignedSeq1.append('-'); alignedSeq2.append(seq2.getAsChar(y-1)); y++; } ali.addAlignment(alignedSeq1.toString(), alignedSeq2.toString(), startAlignment, endAlignment); } }
Jonas-R/gotoh
src/gotoh/LocalGotoh.java
Java
mit
3,217
package ru.russianbravedev.dotamania; import java.sql.SQLException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import ru.russianbravedev.dotamania.R; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import com.danildr.androidcomponents.LoadingJSONfromURL; public class ShowMatchInfo extends FullScreenActivity { private Database database; private FixedGridView gridMatchPlayers; private JSONObject apiHeroes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_match_info); String urlheroes = "https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=" + getString(R.string.steamkey) + "&language=" + lang; try { apiHeroes = new LoadingJSONfromURL().execute(urlheroes).get(20, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } String matchid = getIntent().getStringExtra("matchid"); gridMatchPlayers = (FixedGridView) findViewById(R.id.gridMatchPlayers); RomulTextView matchWinner = (RomulTextView) findViewById(R.id.matchWinner); final RomulTextView showRadianPlayers = (RomulTextView) findViewById(R.id.showRadianPlayers); final RomulTextView showDirePlayers = (RomulTextView) findViewById(R.id.showDirePlayers); TextView matchDurationTv = (TextView) findViewById(R.id.matchDuration); database = new Database(this); try { database.openDataBase(); } catch (SQLException e2) { e2.printStackTrace(); } JSONObject matchInfoJSON = null; try { matchInfoJSON = new GetMatchInfo().execute(matchid, getString(R.string.steamkey)).get(); } catch (InterruptedException e1) { e1.printStackTrace(); } catch (ExecutionException e1) { e1.printStackTrace(); } if (matchInfoJSON != null) { try { Boolean matchWinnerSide = matchInfoJSON.getBoolean("radiant_win"); if (matchWinnerSide == true) { matchWinner.setText(getString(R.string.radianwin)); } else { matchWinner.setText(getString(R.string.direwin)); } } catch (JSONException e) { e.printStackTrace(); } try { Integer matchDuration = new Integer(matchInfoJSON.getInt("duration")); matchDurationTv.setText((matchDuration / 60) + ":" + (matchDuration % 60)); } catch (JSONException e) { e.printStackTrace(); } }; JSONArray matchJSONPlayers = null; try { matchJSONPlayers = matchInfoJSON.getJSONArray("players"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (matchJSONPlayers != null ) { final JSONArray matchJSONPlayersClc = matchJSONPlayers; showRadianPlayers.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showRadianPlayers.setBackgroundColor(colors[1]); showDirePlayers.setBackgroundColor(colors[0]); gridMatchPlayers.setAdapter(new GridAdapterMatchPlayer(ShowMatchInfo.this, matchJSONPlayersClc, true, apiHeroes, getString(R.string.steamkey))); } }); showDirePlayers.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showRadianPlayers.setBackgroundColor(colors[0]); showDirePlayers.setBackgroundColor(colors[1]); gridMatchPlayers.setAdapter(new GridAdapterMatchPlayer(ShowMatchInfo.this, matchJSONPlayersClc, false, apiHeroes, getString(R.string.steamkey))); } }); showRadianPlayers.performClick(); } } }
DanilDr/Dota2Guide
Dota2Guide/src/ru/russianbravedev/dotamania/ShowMatchInfo.java
Java
mit
3,831
package org.innovateuk.ifs.competition.repository; import org.innovateuk.ifs.BaseRepositoryIntegrationTest; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.assessment.domain.AssessmentParticipant; import org.innovateuk.ifs.assessment.repository.AssessmentParticipantRepository; import org.innovateuk.ifs.competition.domain.*; import org.innovateuk.ifs.competition.resource.CompetitionCompletionStage; import org.innovateuk.ifs.competition.resource.CompetitionOpenQueryResource; import org.innovateuk.ifs.competition.resource.MilestoneType; import org.innovateuk.ifs.finance.domain.ProjectFinance; import org.innovateuk.ifs.finance.repository.ProjectFinanceRepository; import org.innovateuk.ifs.fundingdecision.domain.FundingDecisionStatus; import org.innovateuk.ifs.invite.domain.ParticipantStatus; import org.innovateuk.ifs.organisation.domain.Organisation; import org.innovateuk.ifs.organisation.repository.OrganisationRepository; import org.innovateuk.ifs.project.core.domain.PartnerOrganisation; import org.innovateuk.ifs.project.core.domain.Project; import org.innovateuk.ifs.project.core.domain.ProjectProcess; import org.innovateuk.ifs.project.core.repository.ProjectRepository; import org.innovateuk.ifs.project.resource.ProjectState; import org.innovateuk.ifs.threads.domain.Query; import org.innovateuk.ifs.threads.repository.QueryRepository; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.repository.UserRepository; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.annotation.Rollback; import org.springframework.test.util.ReflectionTestUtils; import java.time.ZonedDateTime; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static java.time.ZonedDateTime.now; import static java.util.Collections.singleton; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.id; import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition; import static org.innovateuk.ifs.competition.builder.CompetitionTypeBuilder.newCompetitionType; import static org.innovateuk.ifs.competition.builder.InnovationLeadBuilder.newInnovationLead; import static org.innovateuk.ifs.competition.builder.MilestoneBuilder.newMilestone; import static org.innovateuk.ifs.competition.resource.MilestoneType.FEEDBACK_RELEASED; import static org.innovateuk.ifs.competition.resource.MilestoneType.OPEN_DATE; import static org.innovateuk.ifs.fundingdecision.domain.FundingDecisionStatus.FUNDED; import static org.innovateuk.ifs.fundingdecision.domain.FundingDecisionStatus.UNFUNDED; import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject; import static org.innovateuk.ifs.project.core.builder.ProjectProcessBuilder.newProjectProcess; import static org.innovateuk.ifs.project.resource.ProjectState.*; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst; import static org.junit.Assert.*; public class CompetitionRepositoryIntegrationTest extends BaseRepositoryIntegrationTest<CompetitionRepository> { @Autowired private ApplicationRepository applicationRepository; @Autowired private MilestoneRepository milestoneRepository; @Autowired private ProjectRepository projectRepository; @Autowired private OrganisationRepository organisationRepository; @Autowired private AssessmentParticipantRepository assessmentParticipantRepository; @Autowired private QueryRepository queryRepository; @Autowired private ProjectFinanceRepository projectFinanceRepository; @Autowired private UserRepository userRepository; @Autowired @Override protected void setRepository(CompetitionRepository repository) { this.repository = repository; } private Long org1Id; private Long org2Id; private List<Competition> existingSearchResults; @Before public void setup() { Organisation org = organisationRepository.findOneByName("Org1"); assertNotNull(org); org1Id = org.getId(); org = organisationRepository.findOneByName("Org2"); assertNotNull(org); org2Id = org.getId(); existingSearchResults = repository.findAll(); loginCompAdmin(); } @Test @Rollback public void projectSetup() { Competition compInProjectSetup = newCompetition() .withId() .withNonIfs(false) .withSetupComplete(true) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .build(); compInProjectSetup = repository.save(compInProjectSetup); Milestone feedbackReleasedMilestone = new Milestone(MilestoneType.FEEDBACK_RELEASED, ZonedDateTime.now().minusDays(1), compInProjectSetup); milestoneRepository.save(feedbackReleasedMilestone); Application applicationFundedAndInformed = newApplication().withCompetition(compInProjectSetup) .withFundingDecision(FundingDecisionStatus.FUNDED).withManageFundingEmailDate(now()).build(); applicationRepository.save(applicationFundedAndInformed); ProjectProcess activeProcess = newProjectProcess().withActivityState(ProjectState.SETUP).build(); Project activeProject = newProject() .withName("project name") .withApplication(applicationFundedAndInformed) .withProjectProcess(activeProcess) .build(); projectRepository.save(activeProject); // any competitions with projects still active will show in this list assertEquals(5L, repository.countProjectSetup().longValue()); assertEquals(5, repository.findProjectSetup(PageRequest.of(0, 10)).getTotalElements()); // our new competition should be included assertTrue(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(compInProjectSetup)); // and will also appear in the Previous competitions list assertEquals(1L, repository.countPrevious().longValue()); assertEquals(1, repository.findPrevious(PageRequest.of(0, 10)).getTotalElements()); } @Test @Rollback public void competitionWithInactiveProject() { Competition compWithInactiveProject = newCompetition() .withId() .withNonIfs(false) .withSetupComplete(true) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .build(); compWithInactiveProject = repository.save(compWithInactiveProject); Milestone feedbackReleasedMilestone = new Milestone(MilestoneType.FEEDBACK_RELEASED, ZonedDateTime.now().minusDays(1), compWithInactiveProject); milestoneRepository.save(feedbackReleasedMilestone); Application applicationFundedAndInformed = newApplication().withCompetition(compWithInactiveProject) .withFundingDecision(FundingDecisionStatus.FUNDED).withManageFundingEmailDate(now()).build(); applicationRepository.save(applicationFundedAndInformed); ProjectProcess inactiveProcess = newProjectProcess().withActivityState(ProjectState.COMPLETED_OFFLINE).build(); Project activeProject = newProject() .withName("project name") .withApplication(applicationFundedAndInformed) .withProjectProcess(inactiveProcess) .build(); projectRepository.save(activeProject); assertFalse(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(compWithInactiveProject)); } @Test @Rollback public void competitionWithNoProjects() { Competition competitionWithNoProjects = newCompetition() .withId() .withNonIfs(false) .withSetupComplete(true) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .build(); competitionWithNoProjects = repository.save(competitionWithNoProjects); Milestone feedbackReleasedMilestone = new Milestone(FEEDBACK_RELEASED, ZonedDateTime.now().minusDays(1), competitionWithNoProjects); milestoneRepository.save(feedbackReleasedMilestone); Application applicationFundedAndInformed = newApplication() .withCompetition(competitionWithNoProjects) .withFundingDecision(FUNDED) .withManageFundingEmailDate(now()) .build(); applicationRepository.save(applicationFundedAndInformed); assertFalse(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(competitionWithNoProjects)); } @Test @Rollback public void multipleCompetitionsInProjectSetup() { CompetitionType competitionType = newCompetitionType() .withId(1L) .withName("Programme") .build(); Competition competitionOne = newCompetition() .withId() .withName("Comp1") .withNonIfs(false) .withSetupComplete(true) .withCompetitionType(competitionType) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .withCreatedBy(newUser().build()) .withCreatedOn(now()) .build(); competitionOne = repository.save(competitionOne); Application applicationOne = newApplication() .withId().withCompetition(competitionOne) .withFundingDecision(FUNDED) .withManageFundingEmailDate(now()) .build(); applicationOne = applicationRepository.save(applicationOne); ProjectProcess activeProcessOne = newProjectProcess().withActivityState(ON_HOLD).build(); Project projectOne = newProject() .withName("Project One") .withApplication(applicationOne) .withProjectProcess(activeProcessOne) .build(); projectRepository.save(projectOne); Competition competitionTwo = newCompetition() .withId() .withName("Comp2") .withNonIfs(false) .withSetupComplete(true) .withCompetitionType(competitionType) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .withCreatedBy(newUser().build()) .withCreatedOn(now()) .build(); competitionTwo = repository.save(competitionTwo); Application applicationTwo = newApplication().withId().withCompetition(competitionTwo) .withFundingDecision(FUNDED).withManageFundingEmailDate(now()).build(); applicationTwo = applicationRepository.save(applicationTwo); ProjectProcess activeProcessTwo = newProjectProcess().withActivityState(HANDLED_OFFLINE).build(); Project projectTwo = newProject() .withName("Project Two") .withApplication(applicationTwo) .withProjectProcess(activeProcessTwo) .build(); projectRepository.save(projectTwo); Competition competitionNonIfs = newCompetition() .withId() .withName("Comp3") .withNonIfs(true) .withSetupComplete(true) .withCreatedBy(newUser().build()) .withCreatedOn(now()) .build(); competitionNonIfs = repository.save(competitionNonIfs); assertTrue(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(competitionOne)); assertTrue(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(competitionTwo)); assertFalse(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(competitionNonIfs)); } @Test @Rollback public void fundedAndInformedWithReleaseFeedbackCompletionStage() { loginCompAdmin(); Competition compFundedAndInformed = newCompetition() .withId() .withNonIfs(false) .withSetupComplete(true) .withCompletionStage(CompetitionCompletionStage.RELEASE_FEEDBACK) .build(); compFundedAndInformed = repository.save(compFundedAndInformed); Milestone feedbackReleasedMilestone = new Milestone(MilestoneType.FEEDBACK_RELEASED, ZonedDateTime.now().minusDays(1), compFundedAndInformed); milestoneRepository.save(feedbackReleasedMilestone); Application applicationFundedAndInformed = newApplication().withCompetition(compFundedAndInformed) .withFundingDecision(FundingDecisionStatus.FUNDED).withManageFundingEmailDate(now()).build(); applicationRepository.save(applicationFundedAndInformed); assertEquals(1L, repository.countPrevious().longValue()); assertEquals(1, repository.findPrevious(PageRequest.of(0, 10)).getTotalElements()); assertEquals(compFundedAndInformed.getId().longValue(), repository.findPrevious(PageRequest.of(0, 10)).getContent().get(0).getId() .longValue()); } @Test @Rollback public void fundedAndNotInformed() { Competition fundedNotInformed = newCompetition() .withId() .withNonIfs(false) .withSetupComplete(true) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .build(); fundedNotInformed = repository.save(fundedNotInformed); Application applicationFundedAndInformed = newApplication().withCompetition(fundedNotInformed) .withFundingDecision(FUNDED).build(); applicationRepository.save(applicationFundedAndInformed); assertFalse(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(fundedNotInformed)); } @Test @Rollback public void notFundedAndInformed() { loginCompAdmin(); Competition notFundedAndInformed = newCompetition() .withId() .withNonIfs(false) .withSetupComplete(true) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .build(); notFundedAndInformed = repository.save(notFundedAndInformed); Application applicationFundedAndInformed = newApplication() .withCompetition(notFundedAndInformed) .withFundingDecision(UNFUNDED) .withManageFundingEmailDate(now()) .build(); applicationRepository.save(applicationFundedAndInformed); assertFalse(repository.findProjectSetup(PageRequest.of(0, 10)).getContent().contains(notFundedAndInformed)); } private List<Milestone> replaceOpenDateMilestoneDate(List<Milestone> milestones, ZonedDateTime time) { Optional<Milestone> openDate = milestones.stream().filter(m -> m.getType().equals(OPEN_DATE)) .findFirst(); List<Milestone> nonOpenDateMilestones = milestones.stream().filter(m -> !m.getType().equals(OPEN_DATE)).collect(Collectors.toList()); if (openDate.isPresent()) { openDate.get().setDate(time); nonOpenDateMilestones.add(openDate.get()); } return nonOpenDateMilestones; } @Test @Rollback public void search() { User leadTechnologist = getUserByEmail("[email protected]"); User notLeadTechnologist = getUserByEmail("[email protected]"); GrantTermsAndConditions termsAndConditions = new GrantTermsAndConditions(); termsAndConditions.setId(1L); Competition openComp = new Competition(null, null, "openComp", null, null, null, termsAndConditions); openComp.setTermsAndConditions(termsAndConditions); openComp.setLeadTechnologist(leadTechnologist); openComp.setSetupComplete(true); openComp = repository.save(openComp); openComp.setMilestones(replaceOpenDateMilestoneDate(openComp.getMilestones(), now().minusHours(5L))); openComp = repository.save(openComp); AssessmentParticipant competitionParticipant = buildCompetitionParticipant(openComp, leadTechnologist); assessmentParticipantRepository.save(competitionParticipant); Competition earliestOpenComp = new Competition(null, null, "earliestOpenComp", null, null, null, termsAndConditions); earliestOpenComp.setLeadTechnologist(leadTechnologist); earliestOpenComp.setSetupComplete(true); earliestOpenComp = repository.save(earliestOpenComp); earliestOpenComp.setMilestones(replaceOpenDateMilestoneDate(earliestOpenComp.getMilestones(), now().minusDays (3L))); earliestOpenComp = repository.save(earliestOpenComp); competitionParticipant = buildCompetitionParticipant(earliestOpenComp, leadTechnologist); assessmentParticipantRepository.save(competitionParticipant); Competition compWithNoInnovationLead = new Competition(null, null, "compWithNoInnovationLead", null, null, null, termsAndConditions); compWithNoInnovationLead.setLeadTechnologist(notLeadTechnologist); compWithNoInnovationLead.setSetupComplete(true); compWithNoInnovationLead = repository.save(compWithNoInnovationLead); compWithNoInnovationLead.setMilestones(replaceOpenDateMilestoneDate(compWithNoInnovationLead.getMilestones(), now().minusHours(10L))); compWithNoInnovationLead = repository.save(compWithNoInnovationLead); competitionParticipant = buildCompetitionParticipant(compWithNoInnovationLead, notLeadTechnologist); assessmentParticipantRepository.save(competitionParticipant); Competition compInPreparation = new Competition(null, null, "compInPreparation", null, null, null, termsAndConditions); compInPreparation.setLeadTechnologist(leadTechnologist); compInPreparation.setSetupComplete(false); compInPreparation = repository.save(compInPreparation); compInPreparation.setMilestones(replaceOpenDateMilestoneDate(compInPreparation.getMilestones(), now() .minusHours(20L))); compInPreparation = repository.save(compInPreparation); competitionParticipant = buildCompetitionParticipant(compInPreparation, leadTechnologist); assessmentParticipantRepository.save(competitionParticipant); Competition compReadyToOpen = new Competition(null, null, "compReadyToOpen", null, null, null, termsAndConditions); compReadyToOpen.setLeadTechnologist(leadTechnologist); compReadyToOpen.setSetupComplete(true); compReadyToOpen = repository.save(compReadyToOpen); compReadyToOpen.setMilestones(replaceOpenDateMilestoneDate(compReadyToOpen.getMilestones(), now().plusHours (12L))); compReadyToOpen = repository.save(compReadyToOpen); competitionParticipant = buildCompetitionParticipant(compReadyToOpen, leadTechnologist); assessmentParticipantRepository.save(competitionParticipant); Competition compInInform = new Competition(null, null, "compInInform", null, null, null, termsAndConditions); compInInform.setLeadTechnologist(leadTechnologist); compInInform.setSetupComplete(true); compInInform = repository.save(compInInform); compInInform.setMilestones(replaceOpenDateMilestoneDate(compInInform.getMilestones(), now().minusDays(1L) .minusHours(12L))); compInInform = repository.save(compInInform); competitionParticipant = buildCompetitionParticipant(compInInform, leadTechnologist); assessmentParticipantRepository.save(competitionParticipant); Competition compInProjectSetup = new Competition(null, null, "compInProjectSetup", null, null, null, termsAndConditions); compInProjectSetup.setLeadTechnologist(leadTechnologist); compInProjectSetup.setSetupComplete(true); compInProjectSetup = repository.save(compInProjectSetup); compInProjectSetup.setMilestones(replaceOpenDateMilestoneDate(compInProjectSetup.getMilestones(), now() .minusDays(2L))); compInProjectSetup = repository.save(compInProjectSetup); competitionParticipant = buildCompetitionParticipant(compInProjectSetup, leadTechnologist); assessmentParticipantRepository.save(competitionParticipant); Milestone feedbackReleasedMilestoneInProjectSetup = newMilestone().withCompetition(compInProjectSetup) .withType(FEEDBACK_RELEASED).withDate(now().minusDays(1L)).build(); milestoneRepository.save(feedbackReleasedMilestoneInProjectSetup); Pageable pageable = PageRequest.of(0, 40); Page<Competition> searchResults = repository.search("%o%", pageable); List<Competition> filteredSearchResults = searchResults.getContent().stream().filter(r -> existingSearchResults.stream().noneMatch(er -> er.getId().equals(r.getId()))).collect (Collectors.toList()); assertEquals(7, filteredSearchResults.size()); assertEquals("earliestOpenComp", filteredSearchResults.get(0).getName()); assertEquals("compInProjectSetup", filteredSearchResults.get(1).getName()); assertEquals("compInInform", filteredSearchResults.get(2).getName()); assertEquals("compInPreparation", filteredSearchResults.get(3).getName()); assertEquals("compWithNoInnovationLead", filteredSearchResults.get(4).getName()); assertEquals("openComp", filteredSearchResults.get(5).getName()); assertEquals("compReadyToOpen", filteredSearchResults.get(6).getName()); Page<Competition> leadTechnologistSearchResults = repository.searchForInnovationLeadOrStakeholder("%o%", leadTechnologist.getId(), pageable); List<Competition> filteredLeadTechnologistSearchResults = leadTechnologistSearchResults.getContent().stream() .filter(r -> existingSearchResults.stream().filter(er -> er.getId().equals(r.getId())).count() == 0L) .collect(Collectors.toList()); assertEquals(4, filteredLeadTechnologistSearchResults.size()); assertEquals("earliestOpenComp", filteredLeadTechnologistSearchResults.get(0).getName()); assertEquals("compInProjectSetup", filteredLeadTechnologistSearchResults.get(1).getName()); assertEquals("compInInform", filteredLeadTechnologistSearchResults.get(2).getName()); assertEquals("openComp", filteredLeadTechnologistSearchResults.get(3).getName()); Page<Competition> supportUserSearchResults = repository.searchForSupportUser("%o%", pageable); List<Competition> filteredSupportUserSearchResults = supportUserSearchResults.getContent().stream().filter(r -> existingSearchResults.stream().filter(er -> er.getId().equals(r.getId())).count() == 0L).collect (Collectors.toList()); assertEquals(6, filteredSupportUserSearchResults.size()); assertEquals("earliestOpenComp", filteredSupportUserSearchResults.get(0).getName()); assertEquals("compInProjectSetup", filteredSupportUserSearchResults.get(1).getName()); assertEquals("compInInform", filteredSupportUserSearchResults.get(2).getName()); assertEquals("compWithNoInnovationLead", filteredSupportUserSearchResults.get(3).getName()); assertEquals("openComp", filteredSupportUserSearchResults.get(4).getName()); assertEquals("compReadyToOpen", filteredSupportUserSearchResults.get(5).getName()); } private AssessmentParticipant buildCompetitionParticipant(Competition competition, User user) { AssessmentParticipant competitionParticipant = new AssessmentParticipant(); competitionParticipant.setUser(user); competitionParticipant.setRole(CompetitionParticipantRole.INNOVATION_LEAD); competitionParticipant.setStatus(ParticipantStatus.ACCEPTED); competitionParticipant.setProcess(competition); return competitionParticipant; } @Test public void oneQueryCreatedByProjectFinance() { List<Competition> comps = repository.findByName("Comp21001"); assertTrue(comps.size() > 0); assertEquals(0L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(0L, results.size()); } @Test public void oneQueryCreatedByProjectManager() { List<Competition> comps = repository.findByName("Comp21002"); assertTrue(comps.size() > 0); assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, results.size()); List<Application> apps = applicationRepository.findByName("App21002"); assertEquals(1L, apps.size()); Long appId = apps.get(0).getId(); List<Project> projects = projectRepository.findByApplicationCompetitionId(comps.get(0).getId()); Project project = projects.stream().filter(p -> p.getName().equals("project 2")).findFirst().get(); assertNotNull(project); Long projectId = project.getId(); assertEquals(new CompetitionOpenQueryResource(appId, org2Id, "Org2", projectId, "project 2"), results.get(0)); } @Test public void oneQueryCreatedByProjectManagerAndResolved() { List<Competition> comps = repository.findByName("Comp21002"); assertTrue(comps.size() > 0); assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, results.size()); List<Application> apps = applicationRepository.findByName("App21002"); assertEquals(1L, apps.size()); Long projectId = results.get(0).getProjectId(); Long organisationId = results.get(0).getOrganisationId(); ProjectFinance projectFinanceRow = projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisationId).get(); // get all of the open queries and close them List<Query> openQueries = queryRepository.findAllByClassPkAndClassName(projectFinanceRow.getId(), ProjectFinance.class.getName()); openQueries.forEach(query -> { query.closeThread(userRepository.findByEmail("[email protected]").get()); queryRepository.save(query); }); // clean the cache and get some fresh results flushAndClearSession(); assertEquals(0L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> newResults = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(0L, newResults.size()); } @Test public void oneQueryCreatedByProjectFinanceWithResponseFromProjectManager() { List<Competition> comps = repository.findByName("Comp21003"); assertTrue(comps.size() > 0); assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, results.size()); List<Application> apps = applicationRepository.findByName("App21003"); assertEquals(1L, apps.size()); Long appId = apps.get(0).getId(); List<Project> projects = projectRepository.findByApplicationCompetitionId(comps.get(0).getId()); Project project = projects.stream().filter(p -> p.getName().equals("project 3")).findFirst().get(); assertNotNull(project); Long projectId = project.getId(); assertEquals(new CompetitionOpenQueryResource(appId, org1Id, "Org1", projectId, "project 3"), results.get(0)); } @Test @Rollback public void twoQueriesCreatedBySamePartnerSameProject() { List<Competition> comps = createTwoQueriesFromSamePartnerSameProject(); // and see that we now have a single query count because the 2 queries are from the same partner assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> newResults = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, newResults.size()); } @Test @Rollback public void twoQueriesCreatedBySamePartnerSameProjectAndOneIsResolved() { List<Competition> comps = createTwoQueriesFromSamePartnerSameProject(); // and see that we now have a single query count because the 2 queries are from the same partner assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, results.size()); Long projectId = results.get(0).getProjectId(); Long organisationId = results.get(0).getOrganisationId(); ProjectFinance projectFinanceRow = projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisationId).get(); // get all of the open queries and close them List<Query> openQueries = queryRepository.findAllByClassPkAndClassName(projectFinanceRow.getId(), ProjectFinance.class.getName()); Query query = openQueries.get(0); query.closeThread(userRepository.findByEmail("[email protected]").get()); queryRepository.save(query); // clean the cache and get some fresh results flushAndClearSession(); // assert that we still see a count of one because not all of these partner org's queries are yet resolved assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> newResults = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, newResults.size()); } @Test @Rollback public void twoQueriesCreatedBySamePartnerSameProjectAndBothAreResolved() { List<Competition> comps = createTwoQueriesFromSamePartnerSameProject(); // and see that we now have a single query count because the 2 queries are from the same partner assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, results.size()); Long projectId = results.get(0).getProjectId(); Long organisationId = results.get(0).getOrganisationId(); ProjectFinance projectFinanceRow = projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisationId).get(); // get all of the open queries and close them List<Query> openQueries = queryRepository.findAllByClassPkAndClassName(projectFinanceRow.getId(), ProjectFinance.class.getName()); openQueries.forEach(query -> { query.closeThread(userRepository.findByEmail("[email protected]").get()); queryRepository.save(query); }); // clean the cache and get some fresh results flushAndClearSession(); // and see that we now see all resolved assertEquals(0L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> newResults = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(0L, newResults.size()); } @Test public void twoOpenQueryResponsesFromDifferentPartners() { List<Competition> comps = repository.findByName("Comp21005"); assertTrue(comps.size() > 0); assertEquals(2L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(2L, results.size()); List<Application> apps = applicationRepository.findByName("App21005"); assertEquals(1L, apps.size()); Long appId = apps.get(0).getId(); List<Project> projects = projectRepository.findByApplicationCompetitionId(comps.get(0).getId()); Project project = projects.stream().filter(p -> p.getName().equals("project 5")).findFirst().get(); assertNotNull(project); Long projectId = project.getId(); assertEquals(new CompetitionOpenQueryResource(appId, org1Id, "Org1", projectId, "project 5"), results.get(0)); assertEquals(new CompetitionOpenQueryResource(appId, org2Id, "Org2", projectId, "project 5"), results.get(1)); } @Test public void twoOpenQueryResponsesFromDifferentPartnersAndOneIsResolved() { List<Competition> comps = repository.findByName("Comp21005"); assertTrue(comps.size() > 0); assertEquals(2L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(2L, results.size()); Long projectId = results.get(0).getProjectId(); Long organisationId = results.get(0).getOrganisationId(); ProjectFinance projectFinanceRow = projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisationId).get(); // get all of the open queries and close them List<Query> openQueries = queryRepository.findAllByClassPkAndClassName(projectFinanceRow.getId(), ProjectFinance.class.getName()); openQueries.forEach(query -> { query.closeThread(userRepository.findByEmail("[email protected]").get()); queryRepository.save(query); }); // clean the cache and get some fresh results flushAndClearSession(); // and see that we now see one resolved assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> newResults = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, newResults.size()); } @Test public void twoProjectsHaveOpenQueries() { List<Competition> comps = repository.findByName("Comp21006"); assertTrue(comps.size() > 0); assertEquals(2L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(2L, results.size()); List<Application> apps = applicationRepository.findByName("App21006a"); assertEquals(1L, apps.size()); Long appId = apps.get(0).getId(); List<Project> projects = projectRepository.findByApplicationCompetitionId(comps.get(0).getId()); Project project = projects.stream().filter(p -> p.getName().equals("project 6")).findFirst().get(); assertNotNull(project); Long projectId = project.getId(); assertEquals(new CompetitionOpenQueryResource(appId, org1Id, "Org1", projectId, "project 6"), results.get(0)); apps = applicationRepository.findByName("App21006b"); assertEquals(1L, apps.size()); appId = apps.get(0).getId(); project = projects.stream().filter(p -> p.getName().equals("project 7")).findFirst().get(); assertNotNull(project); projectId = project.getId(); assertEquals(new CompetitionOpenQueryResource(appId, org1Id, "Org1", projectId, "project 7"), results.get(1)); } @Test public void twoProjectsHaveOpenQueriesAndOneIsResolved() { List<Competition> comps = repository.findByName("Comp21006"); assertTrue(comps.size() > 0); assertEquals(2L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(2L, results.size()); Long projectId = results.get(0).getProjectId(); Long organisationId = results.get(0).getOrganisationId(); ProjectFinance projectFinanceRow = projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisationId).get(); // get all of the open queries and close them List<Query> openQueries = queryRepository.findAllByClassPkAndClassName(projectFinanceRow.getId(), ProjectFinance.class.getName()); openQueries.forEach(query -> { query.closeThread(userRepository.findByEmail("[email protected]").get()); queryRepository.save(query); }); // clean the cache and get some fresh results flushAndClearSession(); // and see that we now see one resolved assertEquals(1L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> newResults = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(1L, newResults.size()); } @Test public void oneQueryCreatedByProjectFinanceWithResponseFromProjectManagerButWithSpendProfileGenerated() { List<Competition> comps = repository.findByName("Comp21007"); assertTrue(comps.size() > 0); assertEquals(0L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(0L, results.size()); } @Test public void countLiveForInnovationLead() { // TODO: Improve once IFS-2222 is done. InnovationLead innovationLeadOne = newInnovationLead() .withId(51L) .build(); InnovationLead innovationLeadTwo = newInnovationLead() .withId(52L) .build(); Long count = repository.countLiveForInnovationLeadOrStakeholder(innovationLeadTwo.getId()); assertEquals(new Long(1L), count); count = repository.countLiveForInnovationLeadOrStakeholder(innovationLeadOne.getId()); assertEquals(new Long(0L), count); } @Test public void findByApplicationsId() { loginCompAdmin(); Competition competition = repository.save(newCompetition() .with(id(null)) .build()); Application application = applicationRepository.save(newApplication().withId(11L).withCompetition (competition).build()); Competition retrieved = repository.findById(application.getCompetition().getId()).get(); assertEquals(competition, retrieved); } // IFS-2263 -- ensure milestone dates aren't rounded up @Test @Rollback public void milestoneDatesTruncated() { final ZonedDateTime dateTime = ZonedDateTime.parse("2017-12-03T10:18:30.500Z"); final ZonedDateTime expectedDateTime = ZonedDateTime.parse("2017-12-03T10:18:30.000Z"); GrantTermsAndConditions termsAndConditions = new GrantTermsAndConditions(); termsAndConditions.setId(1L); Competition competition = new Competition(null, null, "comp", dateTime, null, null, termsAndConditions); Competition savedCompetition = repository.save(competition); flushAndClearSession(); Competition retrievedCompetition = repository.findById(savedCompetition.getId()).get(); assertTrue(expectedDateTime.isEqual(retrievedCompetition.getStartDate())); } private List<Competition> createTwoQueriesFromSamePartnerSameProject() { // firstly assert that we have 2 unique queries for this competition as 2 partners have open queries currently List<Competition> comps = repository.findByName("Comp21005"); assertTrue(comps.size() > 0); assertEquals(2L, repository.countOpenQueriesByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)).longValue()); List<CompetitionOpenQueryResource> results = repository.getOpenQueryByCompetitionAndProjectStateNotIn(comps.get(0).getId(), singleton(WITHDRAWN)); assertEquals(2L, results.size()); Long projectId = results.get(0).getProjectId(); Long organisationId = results.get(0).getOrganisationId(); Project project = projectRepository.findById(projectId).get(); PartnerOrganisation otherPartnerOrganisation = simpleFindFirst(project.getPartnerOrganisations(), org -> !org .getOrganisation().getId().equals(organisationId)).get(); ProjectFinance projectFinanceRow = projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisationId).get(); ProjectFinance otherPartnerFinanceRow = projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, otherPartnerOrganisation.getOrganisation().getId()).get(); // now assign one of the queries to the other partner so that they are both coming from the same partner List<Query> openQueries = queryRepository.findAllByClassPkAndClassName(projectFinanceRow.getId(), ProjectFinance.class.getName()); Query queryToAssignToOtherPartner = openQueries.get(0); ReflectionTestUtils.setField(queryToAssignToOtherPartner, "classPk", otherPartnerFinanceRow.getId()); queryRepository.save(queryToAssignToOtherPartner); // clean the cache and get some fresh results flushAndClearSession(); return comps; } }
InnovateUKGitHub/innovation-funding-service
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/competition/repository/CompetitionRepositoryIntegrationTest.java
Java
mit
44,170
package de.sepe.tennis.local; import java.awt.*; import java.awt.geom.*; /** * The ball to play. * * @author Sebastian Peters */ public class Ball { /** ball painting */ private Ellipse2D.Double delegate; /** color */ private Color color; /** action diameter */ private Rectangle2D diameter; /** x movement factor */ private double dx; /** y movement factor */ private double dy; /** random nr generator */ private java.util.Random rand = new java.util.Random(); /** * Constructor. */ public Ball() { this(17.5, 17.5, 12, 12); } /** * Constructor. */ public Ball(double x, double y, double width, double height) { this.delegate = new Ellipse2D.Double(x, y, width, height); this.color = Color.yellow; this.dx = 4; this.dy = 0; } /** * Draws the ball. * * @param g gc */ public void draw(Graphics2D g) { Color oldColor = g.getColor(); g.setColor(color); g.fill(delegate); g.setColor(oldColor); } /** * Hit by player. * * @param player * @return player hit the ball */ public boolean hit(Player player) { final Point2D p = player.getPosition(); final double s = player.getSize(); if (delegate.intersects(p.getX(), p.getY(), 0.001, s)) { dx = -dx; // change direction if (delegate.getCenterY() < p.getY() + s / 2) { dy = -rand.nextDouble() * Math.abs(dx); // dy = // -Math.abs(dx) // * ((s / 2 + p.getY() - delegate.getCenterY()) // / (s / 2 + p.getY())); } else if (delegate.getCenterY() > p.getY() + s / 2) { dy = rand.nextDouble() * Math.abs(dx); // dy = // +Math.abs(dx) // * ((s / 2 + delegate.getCenterY() - p.getY()) // / (s / 2 + p.getY())); } else { // hit the middle dy = 0; } return true; } return false; } /** * Move the ball. * * @return status 0...in field 1...left out of bounds 2...right out of bounds */ public int move() { double newX = delegate.getX() + dx; double newY = delegate.getY() + dy; if (newX <= diameter.getX()) { dx = -dx; return 1; } else if (newX + delegate.getWidth() >= diameter.getWidth()) { dx = -dx; return 2; } if (newY <= diameter.getY()) { dy = -dy; newY = 0; } else if (newY + delegate.getHeight() >= diameter.getHeight()) { dy = -dy; newY = diameter.getHeight() - delegate.getHeight(); } delegate.setFrame(newX, newY, delegate.getWidth(), delegate.getHeight()); return 0; } /** * Sets the diameter. * * @param diameter The diameter to set */ public void setDiameter(Rectangle2D diameter) { this.diameter = diameter; } @Override public String toString() { return "ball at (" + delegate.getCenterX() + ", " + delegate.getCenterY() + ")"; } }
sepe81/tennis
src/main/java/de/sepe/tennis/local/Ball.java
Java
mit
3,314
/* * Written by Mike Wallace (mfwallace at gmail.com). Available * on the web site http://mfwallace.googlepages.com/. * * Copyright (c) 2006 Mike Wallace. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package io.miti.jawbone; /** * This class represents a word in the WordNet data files. * * @author mwallace */ public final class WordData { /** * The word. */ private String word = null; /** * A number that, when appended onto lemma, uniquely identifies * a sense within a lexicographer file. */ private int lexID = 0; /** * For adjectives, a word is followed by a syntactic marker if * one was specified in the lexicographer file. A syntactic marker * is appended, in parentheses, onto word without any intervening * spaces. */ private String syntacticMarker = null; /** * The offset into the data file for the line with this word. */ private long dataFileOffset = 0; /** * The sense number for this word. * * If this number is positive, it's the sense number (1-based). * If it's -1, it has not been loaded yet; if 0, it was not found * in the index file (this should never happen). */ private int senseNum = -1; /** * The part of speech for this word. */ private PartOfSpeech pos; /** * Default constructor. */ public WordData() { super(); } /** * Constructor that takes the 3 fields of interest. * * @param sWord the word * @param nLexID the lexicon ID * @param sSyntacticMarker a syntactic marker * @param pPos the part of speech * @param lOffset the offset into the data file */ public WordData(final String sWord, final int nLexID, final String sSyntacticMarker, final PartOfSpeech pPos, final long lOffset) { word = sWord; lexID = nLexID; syntacticMarker = sSyntacticMarker; pos = pPos; dataFileOffset = lOffset; } /** * @return Returns the lexicon ID. */ public int getLexID() { return lexID; } /** * @param nLexID The lexicon ID to set. */ public void setLexID(final int nLexID) { lexID = nLexID; } /** * @return Returns the word. */ public String getWord() { return word; } /** * @param sWord The word to set. */ public void setWord(final String sWord) { word = sWord; } /** * @return Returns the syntactic marker. */ public String getSyntacticMarker() { return syntacticMarker; } /** * @param sSyntacticMarker The syntactic marker to set. */ public void setSyntacticMarker(final String sSyntacticMarker) { syntacticMarker = sSyntacticMarker; } /** * Return the part of speech. * * @return the part of speech */ public PartOfSpeech getPos() { return pos; } /** * Return the sense number. This is 1-based. * If zero, it was not found (should never happen). * * @return the sense number */ public int getSenseNumber() { // Check if it's been loaded if (senseNum < 0) { // It has not, so load it now senseNum = ParseIndexFile.getSenseNumber(word, pos, dataFileOffset); } return senseNum; } /** * Set the sense number. * * @param lSenseNumber the sense number for this word */ public void setSenseNumber(final int lSenseNumber) { senseNum = lSenseNumber; } /** * @see java.lang.Object#toString() * @return A string representation of this object */ @Override public String toString() { // Declare our string buffer StringBuffer buf = new StringBuffer(100); // Build the string buf.append("Word: ").append(word).append(" Lexicon-ID: ") .append(lexID).append(" Syntactic-Marker: ").append(syntacticMarker) .append("\nPOS: ").append(pos.toString()).append(" Offset: ") .append(Long.toString(dataFileOffset)).append(" Sense"); if (senseNum < 0) { buf.append(": <Not loaded>"); } else if (senseNum == 0) { buf.append(": <Not found>"); } else { buf.append(" #").append(Integer.toString(senseNum)); } // Return the string return buf.toString(); } }
argonium/jawbone
src/io/miti/jawbone/WordData.java
Java
mit
5,609
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejb; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; /** * * @author jon */ @Entity(name="Tutor") public class TutorEntity implements Serializable { private static final long serialVersionUID = 1L; @Id private Long id; private String staffNumber; private String name; private String email; public TutorEntity() { setId(System.nanoTime()); } public void create(String staffNumber, String name, String email) { this.staffNumber = staffNumber; this.name = name; this.email = email; } public String getStaffNumber() { return staffNumber; } public void setStaffNumber(String staffNumber) { this.staffNumber = staffNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TutorEntity)) { return false; } TutorEntity other = (TutorEntity) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "ejb.TutorEntity[ id=" + id + " ]"; } }
jhowtan/is2103
Part 2/MRS-ejb/src/java/ejb/TutorEntity.java
Java
mit
2,050
/** * Class graph. */ class Graph { private final int MAX_VERTS = 10; private int nVerts; private Vertex[] vertices; private boolean[][] adjMatrix; public Graph() { adjMatrix = int[MAX_VERTS][MAX_VERTS]; } public void addVertex(int value) { vertics[nVerts++] = new Vertex(value); } public void addEdge(int start, int end) { adjMatrix[start][end] = 1; } public static Graph build() { Graph graph = new Graph(); for (i = 0; i < 10; i++) { graph.add(i); } addEdge() } }
tianlinliu/ctci
chapter4-Trees-and-Graphs/Solution2_isConnected/Graph.java
Java
mit
589
package com.github.badoualy.telegram.tl.api.messages; import com.github.badoualy.telegram.tl.TLContext; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.github.badoualy.telegram.tl.StreamUtils.readInt; import static com.github.badoualy.telegram.tl.StreamUtils.writeInt; import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID; import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32; /** * @author Yannick Badoual [email protected] * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ public class TLSentEncryptedMessage extends TLAbsSentEncryptedMessage { public static final int CONSTRUCTOR_ID = 0x560f8935; private final String _constructor = "messages.sentEncryptedMessage#560f8935"; public TLSentEncryptedMessage() { } public TLSentEncryptedMessage(int date) { this.date = date; } @Override public void serializeBody(OutputStream stream) throws IOException { writeInt(date, stream); } @Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public void deserializeBody(InputStream stream, TLContext context) throws IOException { date = readInt(stream); } @Override public int computeSerializedSize() { int size = SIZE_CONSTRUCTOR_ID; size += SIZE_INT32; return size; } @Override public String toString() { return _constructor; } @Override public int getConstructorId() { return CONSTRUCTOR_ID; } public int getDate() { return date; } public void setDate(int date) { this.date = date; } }
badoualy/kotlogram
tl/src/main/java/com/github/badoualy/telegram/tl/api/messages/TLSentEncryptedMessage.java
Java
mit
1,762
package org.jabref.logic.integrity; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.l10n.Localization; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class ValidCitationKeyCheckerTest { private final ValidCitationKeyChecker checker = new ValidCitationKeyChecker(); @ParameterizedTest @MethodSource("provideCitationKeys") void citationKeyValidity(Optional optionalArgument, String citationKey) { assertEquals(optionalArgument, checker.checkValue(citationKey)); } private static Stream<Arguments> provideCitationKeys() { return Stream.of( Arguments.of(Optional.of(Localization.lang("empty citation key")), ""), Arguments.of(Optional.empty(), "Seaver2019"), Arguments.of(Optional.of(Localization.lang("Invalid citation key")), "Seaver_2019}") ); } }
JabRef/jabref
src/test/java/org/jabref/logic/integrity/ValidCitationKeyCheckerTest.java
Java
mit
1,069
package com.xeiam.xchange.okcoin.service.polling; import java.io.IOException; import com.xeiam.xchange.Exchange; import com.xeiam.xchange.okcoin.FuturesContract; import com.xeiam.xchange.okcoin.dto.trade.OkCoinOrderResult; import com.xeiam.xchange.okcoin.dto.trade.OkCoinTradeResult; public class OkCoinTradeServiceRaw extends OKCoinBaseTradePollingService { /** * Constructor * * @param exchange */ protected OkCoinTradeServiceRaw(Exchange exchange) { super(exchange); } public OkCoinTradeResult trade(String symbol, String type, String rate, String amount) throws IOException { OkCoinTradeResult tradeResult = okCoin.trade(apikey, symbol, type, rate, amount, signatureCreator); return returnOrThrow(tradeResult); } public OkCoinTradeResult cancelOrder(long orderId, String symbol) throws IOException { OkCoinTradeResult tradeResult = okCoin.cancelOrder(apikey, orderId, symbol, signatureCreator); return returnOrThrow(tradeResult); } public OkCoinOrderResult getOrder(long orderId, String symbol) throws IOException { OkCoinOrderResult orderResult = okCoin.getOrder(apikey, orderId, symbol, signatureCreator); return returnOrThrow(orderResult); } public OkCoinOrderResult getOrderHistory(String symbol, String status, String currentPage, String pageLength) throws IOException { OkCoinOrderResult orderResult = okCoin.getOrderHistory(apikey, symbol, status, currentPage, pageLength, signatureCreator); return returnOrThrow(orderResult); } /** OkCoin.com Futures API **/ public OkCoinTradeResult futuresTrade(String symbol, String type, String price, String amount, FuturesContract prompt, int matchPrice) throws IOException { OkCoinTradeResult tradeResult = okCoin.futuresTrade(apikey, symbol, prompt.getName(), type, price, amount, matchPrice, signatureCreator); return returnOrThrow(tradeResult); } public OkCoinTradeResult futuresCancelOrder(long orderId, String symbol, FuturesContract prompt) throws IOException { OkCoinTradeResult tradeResult = okCoin.futuresCancelOrder(apikey, orderId, symbol, prompt.getName(), signatureCreator); return returnOrThrow(tradeResult); } public OkCoinOrderResult getFuturesOrder(long orderId, String symbol, String currentPage, String pageLength, FuturesContract prompt) throws IOException { OkCoinOrderResult orderResult = okCoin.getFuturesOrder(apikey, orderId, symbol, "0", currentPage, pageLength, prompt.getName(), signatureCreator); return returnOrThrow(orderResult); } }
coingecko/XChange
xchange-okcoin/src/main/java/com/xeiam/xchange/okcoin/service/polling/OkCoinTradeServiceRaw.java
Java
mit
2,545
package com.hyh.arithmetic.search_words; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import java.util.List; /** * @author Administrator * @description * @data 2020/6/8 */ public class SearchWordsActivity extends Activity { private static final String TAG = "TreeNodeActivity_"; /** * [0,1,null,3,2] * 2 * 1 */ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button button = new Button(this); button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); button.setText("测试"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { char[][] chars = new char[7][4]; chars[0] = new char[]{'a', 'a', 'a', 'a'}; chars[1] = new char[]{'a', 'a', 'a', 'a'}; chars[2] = new char[]{'a', 'a', 'a', 'a'}; chars[3] = new char[]{'a', 'a', 'a', 'a'}; chars[4] = new char[]{'b', 'c', 'd', 'e'}; chars[5] = new char[]{'f', 'i', 'j', 'k'}; chars[6] = new char[]{'l', 'm', 'n', 'o'}; String[] strings = new String[]{"aaaaaaaab", "aaaaaaaac", "aaaaaaaad", "aaaaaaaae" , "aaaaaaaaf", "aaaaaaaai", "aaaaaaaaj", "aaaaaaaak" , "aaaaaaaal", "aaaaaaaam", "aaaaaaaan", "aaaaaaaao" , "aaaaaaaaab", "aaaaaaaabc", "aaaaaaaacd", "aaaaaaade" , "aaaaaaaaef", "aaaaaaaafi", "aaaaaaaaij", "aaaaaaakl" , "aaaaaaaalm", "aaaaaaaamn", "aaaaaaaano", "aaaaaaaoa" , "aaaaaaaabf", "aaaaaaaaed", "aaaaaaaadj", "aaaaaaacb" }; List<String> words = new Solution5().findWords(chars, strings); Log.d(TAG, "onClick: "); } }); setContentView(button); } }
EricHyh/FileDownloader
ArithmeticDemo/src/main/java/com/hyh/arithmetic/search_words/SearchWordsActivity.java
Java
mit
2,219
package android.net; import io.myweb.test.support.LocalWire; import java.io.*; public class LocalSocket { private InputStream inputStream; private OutputStream outputStream; public LocalSocket() { this(null, null); } public LocalSocket(InputStream inputStream, OutputStream outputStream) { this.inputStream = inputStream; this.outputStream = outputStream; } public OutputStream getOutputStream() throws IOException { return outputStream; } public InputStream getInputStream() throws IOException { return inputStream; } public FileDescriptor getFileDescriptor() { return new FileDescriptor(); } public void shutdownOutput() throws IOException { } public void close() throws IOException { } public int getSendBufferSize() throws IOException { return 1111; } public void connect(LocalSocketAddress localSocketAddress) throws IOException { LocalWire.ClientsSideStreams clientsSideStreams = LocalWire.getInstance().connect(); inputStream = clientsSideStreams.getInputStream(); outputStream = clientsSideStreams.getOutputStream(); } }
mywebio/mywebio-sdk
mywebio-test/src/test/java/android/net/LocalSocket.java
Java
mit
1,094
package jpower.event; import jpower.core.Wrapper; import java.util.ArrayList; import java.util.List; /** * Base Implementation of the JPower Event Bus */ public class EventBus implements IEventBus { /** * The Registered Handlers */ protected final List<RegisteredHandler> handlers; /** * Creates a new Event Bus */ public EventBus() { handlers = new ArrayList<>(); } /** * {@inheritDoc} */ @Override public void register(final Object object) { handlers.add(new RegisteredHandler(object).setAnnotationType(EventHandler.class).registerMethods()); } /** * {@inheritDoc} */ @Override public boolean unregister(final Object object) { RegisteredHandler handlerToRemove = null; for (RegisteredHandler handler : handlers) { if (handler.getObject() == object) { handlerToRemove = handler; } } if (handlerToRemove == null) { return false; } handlers.remove(handlerToRemove); return true; } /** * {@inheritDoc} */ @Override public void post(final Object event) { Wrapper<Boolean> didRun = new Wrapper<>(false); handlers.forEach(handler -> { if (handler.executeEvent(event)) { didRun.set(true); } }); if (!DeadEvent.class.isAssignableFrom(event.getClass()) && !didRun.get()) { post(new DeadEvent(event)); } } }
DirectMyFile/JPower
modules/Event/src/main/java/jpower/event/EventBus.java
Java
mit
1,462
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Employee; import DataAccessLayer.TicketPriceHandler; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author namvh */ public class DeleteTicketPriceHandler extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet DeleteTicketPriceHandler</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet DeleteTicketPriceHandler at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("ticketPriceID") == null) { String referer = request.getHeader("Referer"); response.sendRedirect(referer); return; } String ticketPriceID = request.getParameter("ticketPriceID"); if ("".equals(ticketPriceID)) { String referer = request.getHeader("Referer"); response.sendRedirect(referer); return; } TicketPriceHandler handler = new TicketPriceHandler(); try { if (handler.remove(ticketPriceID)) { response.sendRedirect("/employee/ticket.jsp"); return; } String referer = request.getHeader("Referer"); response.sendRedirect(referer); } catch (SQLException | ClassNotFoundException ex) { Logger.getLogger(DeleteTicketPriceHandler.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
NGUp/BlueSky
BlueSkyProject/src/java/Employee/DeleteTicketPriceHandler.java
Java
mit
4,046
package com.mypurecloud.sdk.v2.guest; public enum PureCloudRegionHosts { us_east_1( "https://api.mypurecloud.com"), eu_west_1("https://api.mypurecloud.ie"), ap_southeast_2( "https://api.mypurecloud.com.au"), ap_northeast_1("https://api.mypurecloud.jp"), eu_central_1("https://api.mypurecloud.de"), us_west_2("https://api.usw2.pure.cloud"), ca_central_1("https://api.cac1.pure.cloud"), ap_northeast_2("https://api.apne2.pure.cloud"), eu_west_2("https://api.euw2.pure.cloud"), ap_south_1("https://api.aps1.pure.cloud"), us_east_2("https://api.use2.us-gov-pure.cloud"); private String apiHost; PureCloudRegionHosts(String apiHost) { this.apiHost = apiHost; } public String getApiHost() { return apiHost; } }
MyPureCloud/platform-client-sdk-common
resources/sdk/purecloudjava-guest/extensions/PureCloudRegionHosts.java
Java
mit
789
/* * Copyright (c) 2010-2022 Mark Allen, Norbert Bartels. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.restfb.integration; import com.restfb.DefaultFacebookClient; import com.restfb.FacebookClient; import com.restfb.Version; import com.restfb.integration.base.RestFbIntegrationTestBase; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; class DebugTokenITCase extends RestFbIntegrationTestBase { @Test void checkDebugToken() { DefaultFacebookClient client = new DefaultFacebookClient(getTestSettings().getUserAccessToken(), Version.VERSION_3_1); FacebookClient.DebugTokenInfo debugTokenInfo = client.debugToken("abc"); assertNotNull(debugTokenInfo); } }
restfb/restfb
src/test/java/com/restfb/integration/DebugTokenITCase.java
Java
mit
1,770
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.actions.order; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.orderprocessing.model.OrderProcessModel; import de.hybris.platform.payment.PaymentService; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.processengine.action.AbstractProceduralAction; import org.apache.log4j.Logger; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; /** * Sends cancellation to adyen transactions */ public class AdyenCancelOrRefundAction extends AbstractProceduralAction<OrderProcessModel> { private static final Logger LOG = Logger.getLogger(AdyenCancelOrRefundAction.class); private PaymentService paymentService; @Override public void executeAction(final OrderProcessModel process) throws Exception { final OrderModel order = process.getOrder(); LOG.info("Cancelling order: " + order.getCode()); for (PaymentTransactionModel transactionModel : order.getPaymentTransactions()) { if (!PAYMENT_PROVIDER.equals(transactionModel.getPaymentProvider())) { continue; } PaymentTransactionEntryModel cancelledTransaction = paymentService.cancel(transactionModel.getEntries().get(0)); } } public PaymentService getPaymentService() { return paymentService; } public void setPaymentService(PaymentService paymentService) { this.paymentService = paymentService; } }
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/actions/order/AdyenCancelOrRefundAction.java
Java
mit
2,511
package com.infinityworks.common.lang; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Supplier; /** * Additions to lists */ public final class ListExtras { public static boolean isNullOrEmpty(List<?> underTest) { return underTest == null || underTest.isEmpty(); } public static boolean noneNull(Collection<?> underTest) { return underTest != null && underTest.stream().allMatch(o -> o != null); } /** * Executes the supplied function n times and returns the results * * @param supplier the operation to invoke * @param n the number of times to invoke the operation * @param <T> the return type * @return a collection with the results of the invocations */ public static <T> List<T> times(Supplier<T> supplier, int n) { List<T> elements = new ArrayList<>(); for (int i = 0; i < n; i++) { elements.add(supplier.get()); } return elements; } private ListExtras() { throw new UnsupportedOperationException("Do not instantiate"); } }
celestial-winter/vics
common/src/main/java/com/infinityworks/common/lang/ListExtras.java
Java
mit
1,145
package dev.paytrack.paytrack.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.FileOutputStream; import java.io.IOException; public class FileManager { private static Context context; private static FileManager ourInstance; public static FileManager getInstance(Context mContext) { context = mContext; if (ourInstance == null) { ourInstance = new FileManager(); } return ourInstance; } public String saveToInternalStorage(String name, Bitmap bitmapImage) { FileOutputStream fos = null; try { fos = context.openFileOutput(name, Context.MODE_PRIVATE); bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } return name; } public Bitmap loadImageFromStorage(Integer alternative) { // FileInputStream fis = null; // try { // fis = context.openFileInput(name); // return BitmapFactory.decodeStream(fis); // } catch (FileNotFoundException e) { return BitmapFactory.decodeResource(context.getResources(), alternative); // } finally { // if (fis != null) { // try { // fis.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } } public static Bitmap resourceToBitmap(Integer alternative) { return BitmapFactory.decodeResource(context.getResources(), alternative); } }
victorpm5/paytrack
app/src/main/java/dev/paytrack/paytrack/utils/FileManager.java
Java
mit
1,876
package com.sutromedia.android.lib.html; import org.stringtemplate.v4.*; import java.util.List; import com.sutromedia.android.lib.model.IGroup; import com.sutromedia.android.lib.model.IEntryComment; public class HtmlTemplate { private ST mHtmlTemplate; private boolean mUseComments; public HtmlTemplate(String html) { mHtmlTemplate = new ST(html, '$', '$'); mHtmlTemplate.add("cssLinkColor", "#3678BF"); mHtmlTemplate.add("externalWebsiteColor", "#4688CF"); mHtmlTemplate.add("bodyTextFontSize", "15"); mHtmlTemplate.add("rightMargin", "10"); mHtmlTemplate.add("leftMargin", "10"); mHtmlTemplate.add("cssTextColor", "#424242"); mUseComments = false; } public void setAttribute(String attribute, Object value) { mHtmlTemplate.add(attribute, value); } public void setGroups(List<IGroup> groups) { if (groups.size()>0) { mHtmlTemplate.add("groups", groups.toArray()); } } public void setComments(final List<IEntryComment> comments) { int count = comments.size(); mHtmlTemplate.add("comments", Integer.toString(count)); if (count>1) { mHtmlTemplate.add("many_comments", true); } if (count==1) { mHtmlTemplate.add("single_comment", true); } if (count>0) { mHtmlTemplate.add("first_comment", comments.get(0)); } } public void useComments(boolean useComments) { mUseComments = useComments; } public String getResult() { mHtmlTemplate.add("use_comments", mUseComments); return mHtmlTemplate.render(); } }
sutromedia/android-travel-guide
android-app-core/src/com/sutromedia/android/lib/html/HtmlTemplate.java
Java
mit
1,761
package fq.geom.nurbs; /** * This class contains Algorithms from <i>The NURBS Book</i>. * * @author FuQiang * */ public class Algorithms { /** * Determine the knot span index * * @param u - * parameter value * @param deg - * degree of B-Spline basis function * @param knots - * nonperiodic knot vector * * @return the kont span index */ static public int FindSpan(double u, int deg, double[] knots) { int low, high, mid; int n = knots.length - deg - 2; // special case if (u >= knots[n + 1]) return n; if (u <= knots[deg]) return deg; // do binary search low = deg; high = n + 1; mid = (low + high) / 2; while (u < knots[mid] || u >= knots[mid + 1]) { if (u < knots[mid]) high = mid; else low = mid; mid = (low + high) / 2; } return (mid); } /** * @param u - * parameter value * @param span - * kont span index * @param deg - * degree of B-Spline basis function * @param knots - * nonperiodic knot vector * * @return all the nonvanishing basis functions: N[0],...,N[p]. */ static public double[] BasisFuns(double u, int span, int deg, double[] knots) { double[] N = new double[deg + 1]; N[0] = 1.0; double[] left = new double[deg + 1]; double[] right = new double[deg + 1]; double saved, temp; for (int j = 1; j <= deg; j++) { left[j] = u - knots[span + 1 - j]; right[j] = knots[span + j] - u; saved = 0.0; for (int r = 0; r < j; r++) { temp = N[r] / (right[r + 1] + left[j - r]); N[r] = saved + right[r + 1] * temp; saved = left[j - r] * temp; } N[j] = saved; } return N; } /** * Generate nonperiodic knot vectors, within range [0,1] * * @param n - * (n+1) is the number of control points * @param deg - * degree of the B-spline basis functions * @return Generated nonperiodic knot vectors */ static public double[] GenKnots(int n, int deg) { int m = n + deg + 1; double inv = 1 / (double) (n - deg + 1); double[] U = new double[m + 1]; for (int i = 0; i <= m; i++) { if (i <= deg) U[i] = 0.0; else if (i > deg && i <= n) U[i] = (double) (i - deg) * inv; else U[i] = 1.0; } return U; } /** * Generate nonperiodic knot vectors, within range [0,1] * * @param n - * (n+1) is the number of control points * @param deg - * degree of the B-spline basis functions * @return Generated nonperiodic knot vectors */ static public boolean IsKnotsValid(int n, int deg, double[] newKnots) { // m = n + p + 1 int m = n + deg + 1; if(newKnots.length != m+1) return false; if(newKnots[m] <= newKnots[0]) return false; for (int i = 0; i < m; i++) { if(newKnots[i+1] < newKnots[i]) return false; } //for (int i =0; i<deg;i++) { // if(newKnots[i] != newKnots[i+1]) // return false; // if(newKnots[m - i] != newKnots[m-i-1]) // return false; //} return true; } /** * Compute the nonzero basis functions and their derivatives, up to and * including the nth derivative (n<=deg). * * @param u - * parameter value * @param n - * nth derivative * @param span - * knot vector span index * @param deg - * degree of basis function * @param U - * knot vector * @return A two-dimensional array, Ders[][]<br> * Ders[k][j] is the kth derivative of the function * N(span-deg+j,deg),<br> * where k:[0,n] and j:[0,p] */ static public double[][] DersBasisFuns(double u, int n, int span, int deg, double[] U) { double[][] ders = new double[n + 1][deg + 1]; double[] left = new double[deg + 1]; double[] right = new double[deg + 1]; double[][] ndu = new double[deg + 1][deg + 1]; double saved, temp; int j, r; ndu[0][0] = 1.0; for (j = 1; j <= deg; j++) { left[j] = u - U[span + 1 - j]; right[j] = U[span + j] - u; saved = 0.0; for (r = 0; r < j; r++) { // Lower triangle ndu[j][r] = right[r + 1] + left[j - r]; temp = ndu[r][j - 1] / ndu[j][r]; // Upper triangle ndu[r][j] = saved + right[r + 1] * temp; saved = left[j - r] * temp; } ndu[j][j] = saved; } // load the basis functions for (j = 0; j <= deg; j++) { ders[0][j] = ndu[j][deg]; } // compute the derivatives, Eq.[2.9] the NURBS Book double[][] a = new double[2][deg + 1]; for (r = 0; r <= deg; r++) { // loop over function index int s1, s2; s1 = 0; s2 = 1; a[0][0] = 1.0; // compute the kth derivative for (int k = 1; k <= n; k++) { double d; int rk, pk, j1, j2; d = 0.0; rk = r - k; pk = deg - k; if (r >= k) { a[s2][0] = a[s1][0] / ndu[pk + 1][rk]; d = a[s2][0] * ndu[rk][pk]; } if (rk >= -1) { j1 = 1; } else { j1 = -rk; } if (r - 1 <= pk) { j2 = k - 1; } else { j2 = deg - r; } for (j = j1; j <= j2; j++) { a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j]; d += a[s2][j] * ndu[rk + j][pk]; } if (r <= pk) { a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r]; d += a[s2][j] * ndu[r][pk]; } ders[k][r] = d; j = s1; s1 = s2; s2 = j; // switch rows } } // Multiply through by the correct factors // Eq [2.9] of the NURBS Book r = deg; for (int k = 1; k <= n; k++) { for (j = 0; j <= deg; j++) ders[k][j] *= r; r *= (deg - k); } return ders; } /** * Compute binomial coefficients, and store in an array * * @return An array of binomial coefficients, Bin[K][I] * * <pre> * k! * Bin[k][i] = ----------- * i! (k-i)! * </pre> */ public static double[][] BinomialCoef(int K, int I) { double Bin[][] = new double[K + 1][I + 1]; int k, i; // Setup the first line Bin[0][0] = 1.0; for (i = I; i > 0; --i) Bin[0][i] = 0.0; // Setup the other lines for (k = 0; k < K; k++) { Bin[k + 1][0] = 1.0; for (i = 1; i <= I; i++) { if (k + 1 < i) Bin[k][i] = 0.0; else Bin[k + 1][i] = Bin[k][i] + Bin[k][i - 1]; } } return Bin; } }
fq/NURBS4Matlab
src/fq/geom/nurbs/Algorithms.java
Java
mit
6,240
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos.implementation.changefeed.implementation; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; import static com.azure.cosmos.BridgeInternal.setProperty; class ChangeFeedStartFromBeginningImpl extends ChangeFeedStartFromInternal { public ChangeFeedStartFromBeginningImpl() { super(); } @Override public void populatePropertyBag() { super.populatePropertyBag(); synchronized(this) { setProperty( this, Constants.Properties.CHANGE_FEED_START_FROM_TYPE, ChangeFeedStartFromTypes.BEGINNING); } } @Override public void populateRequest(RxDocumentServiceRequest request) { // We don't need to set any headers to start from the beginning } @Override public boolean supportsFullFidelityRetention() { return false; } }
Azure/azure-sdk-for-java
sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedStartFromBeginningImpl.java
Java
mit
1,050
package com.example.sahilnaran.presenters.home; import com.example.sahilnaran.domain.repositories.GithubDomain; import java.util.List; public class IMainContract { public interface View { void showLoadedGithubReposCount(int size); void showStoredGithubReposCount(int size); void setDarkThemeActivated(); void setDarkThemeNotActivated(); } public interface Presenter { void onTakeView(View view); void requestAllApiGithubRepos(); void getAllSqliteGithubRepos(); void clearAllSqliteGithubRepos(); void toggleTheme(); } }
sahilNaran/layeredMvp
presenters/src/main/java/com/example/sahilnaran/presenters/home/IMainContract.java
Java
mit
620
package org.innovateuk.ifs.management.competition.setup.application.populator; import org.innovateuk.ifs.application.service.QuestionRestService; import org.innovateuk.ifs.application.service.SectionService; import org.innovateuk.ifs.commons.exception.ObjectNotFoundException; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionSetupQuestionResource; import org.innovateuk.ifs.management.competition.setup.application.form.QuestionForm; import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm; import org.innovateuk.ifs.form.resource.QuestionResource; import org.innovateuk.ifs.form.resource.SectionResource; import org.innovateuk.ifs.question.service.QuestionSetupCompetitionRestService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Arrays; import java.util.Optional; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionSetupQuestionResourceBuilder.newCompetitionSetupQuestionResource; import static org.innovateuk.ifs.form.builder.QuestionResourceBuilder.newQuestionResource; import static org.innovateuk.ifs.form.builder.SectionResourceBuilder.newSectionResource; import static org.junit.Assert.*; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.Silent.class) public class QuestionFormPopulatorTest { @InjectMocks private QuestionFormPopulator populator; @Mock private QuestionSetupCompetitionRestService questionSetupCompetitionRestService; @Mock private QuestionRestService questionRestService; @Mock private SectionService sectionService; private Long questionId = 7890L; private Long questionNotFoundId = 12904L; private QuestionResource questionResource = newQuestionResource().withId(questionId).build(); private CompetitionResource competitionResource; @Test public void populateForm_withoutErrors() { CompetitionSetupQuestionResource resource = newCompetitionSetupQuestionResource() .withNumberOfUploads(0) .withAppendix(false) .build(); SectionResource sectionResource = newSectionResource().withQuestions(Arrays.asList(1L, 2L)).build(); when(questionRestService.findById(questionId)).thenReturn(restSuccess(questionResource)); when(questionSetupCompetitionRestService.getByQuestionId(questionId)).thenReturn(restSuccess(resource)); when(sectionService.getSectionByQuestionId(questionId)).thenReturn(sectionResource); CompetitionSetupForm result = populator.populateForm(competitionResource, Optional.of(questionId)); assertTrue(result instanceof QuestionForm); QuestionForm form = (QuestionForm) result; assertEquals(form.getQuestion(), resource); } @Test public void populateForm_questionShouldNotBeRemovableIfLastInSection() { CompetitionSetupQuestionResource resource = newCompetitionSetupQuestionResource() .withAppendix(false) .withNumberOfUploads(0) .build(); SectionResource sectionWithOneQuestion = newSectionResource().withQuestions(Arrays.asList(1L)).build(); when(questionRestService.findById(questionId)).thenReturn(restSuccess(questionResource)); when(questionSetupCompetitionRestService.getByQuestionId(questionId)).thenReturn(restSuccess(resource)); when(sectionService.getSectionByQuestionId(questionId)).thenReturn(sectionWithOneQuestion); QuestionForm result = (QuestionForm) populator.populateForm(competitionResource, Optional.of(questionId)); assertFalse(result.isRemovable()); } @Test public void populateForm_questionShouldBeRemovableIfNotLastInSection() { CompetitionSetupQuestionResource resource = newCompetitionSetupQuestionResource() .withAppendix(false) .withNumberOfUploads(0) .build(); SectionResource sectionWithMultipleQuestions = newSectionResource().withQuestions(Arrays.asList(1L, 2L)).build(); when(questionRestService.findById(questionId)).thenReturn(restSuccess(questionResource)); when(questionSetupCompetitionRestService.getByQuestionId(questionId)).thenReturn(restSuccess(resource)); when(sectionService.getSectionByQuestionId(questionId)).thenReturn(sectionWithMultipleQuestions); QuestionForm result = (QuestionForm) populator.populateForm(competitionResource, Optional.of(questionId)); assertTrue(result.isRemovable()); } @Test(expected = ObjectNotFoundException.class) public void populateForm_withErrors() { when(questionSetupCompetitionRestService.getByQuestionId(questionNotFoundId)).thenThrow( new ObjectNotFoundException()); CompetitionSetupForm result = populator.populateForm(competitionResource, Optional.of(questionNotFoundId)); assertEquals(null, result); } @Test(expected = ObjectNotFoundException.class) public void populateForm_formWithNoObjectIdErrors() { assertNull(populator.populateForm(competitionResource, Optional.empty())); } }
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-competition-mgt-service/src/test/java/org/innovateuk/ifs/management/competition/setup/application/populator/QuestionFormPopulatorTest.java
Java
mit
5,354
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; public class Main { // Regex patterns for finding links and keywords private static Pattern linkPattern = Pattern.compile("<a .*?href=\"(.*?)\".*?>(.*?)</a>", Pattern.DOTALL | Pattern.MULTILINE), careerPattern = Pattern.compile("[^a-z]((career)|(job)|(position)|(team))(?:[^a-z]|s[^a-z])", Pattern.DOTALL | Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), internPattern = Pattern.compile("[^a-z](((intern)|(internship))|(co(-|)op)|(student))(?:[^a-z]|s[^a-z])", Pattern.DOTALL | Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); // List used to store any links that through errors private static List<String> errorLinks = new LinkedList<>(); // List used to store links for checking for duplicates private static List<String> visitedLinks = new LinkedList<>(); public static void main(String[] args) { // Keep getting websites to search until exit while(true){ // Get the current website to search String website = JOptionPane.showInputDialog(null, "Enter Website to get links from to search for jobs", "Website Please", JOptionPane.QUESTION_MESSAGE); // If no website was given quit if(website==null) System.exit(0); // Ask for name of output files and if output should be links in HTML String file = JOptionPane.showInputDialog(null, "Output File Name:", "File", JOptionPane.QUESTION_MESSAGE); int format = JOptionPane.showConfirmDialog(null, "Format output for HTML?", "Format", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); // Search the given site for jobs and check if was succesful List<String> websites = getJobSites(website); if(websites==null){ JOptionPane.showMessageDialog(null, "Error with given URL!"); continue; } // Write found job sites to file writeListToFile(websites, file+" Jobs", format==JOptionPane.YES_OPTION); // Write any sites that threw an error to file writeListToFile(errorLinks, file+" Errors", format==JOptionPane.YES_OPTION); // Let the user know the process is done JOptionPane.showMessageDialog(null, "Done"); } } /** * Writes the given list to the given file name using HTML format or not depending on given value * * @param list List to write to file * @param file File to write to * @param format If should use HTML format */ private static void writeListToFile(List<String> list, String file, boolean format){ // Create list for checking duplicates List<String> dupList = new LinkedList<>(); // Write the list to file BufferedWriter fileWriter = null; try { // Create writer to file= fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(file+" Jobs.txt")))); // Write all items in the list to the file for(String item : list) { // Check for duplicates if(!dupList.contains(item)){ // Format for HTML if chosen and write to file if(format) fileWriter.write("<a href=\""+item+"\">"+item+"</a>"); else fileWriter.write(item); fileWriter.newLine(); dupList.add(item); } } } catch (Exception e) { // Print error to console (Shouldn't happen?) e.printStackTrace(); } finally { // Make sure writer closes if opened if(fileWriter!=null){ try { fileWriter.close(); } catch (IOException e) { // Print error to console (Shouldn't happen?) e.printStackTrace(); } } } } /** * Gets all the pages that are linked to by the given website and returns the sites that reference internship keywords * * @param website The website to get pages to search * @return The pages that are refrenced by the given website that have inten keywords */ private static List<String> getJobSites(String website){ // Get the website and matcher (If website not found return null) List<String> websites = new LinkedList<String>(); String html = getHtml(website); if(html==null) return null; Matcher htmlMatcher = linkPattern.matcher(html); // Get the number of links int numLinks = 0; while (htmlMatcher.find()) numLinks++; htmlMatcher.reset(); //create the loading bar and JPanel for it final JPanel tempPanel = new JPanel(); JProgressBar progressBar = new JProgressBar(0, numLinks); progressBar.setValue(0); progressBar.setStringPainted(true); tempPanel.add(progressBar); //Open a message dialog in a thread with the loading bar that if closed, will stop the program. new Thread(new Runnable(){ public void run() { JOptionPane.showMessageDialog(null, tempPanel, "Loading", JOptionPane.PLAIN_MESSAGE); System.exit(0); } }).start(); // Search each site and search for pages with intern keywords while (htmlMatcher.find()){ websites.addAll(getInternSites(htmlMatcher.group(1))); visitedLinks.clear(); progressBar.setValue(progressBar.getValue()+1); } // Return all pages found with intern keywords return websites; } private static List<String> getInternSites(String website){ // Get the website and matcher (If website not found return empty list) List<String> jobs = new LinkedList<String>(); visitedLinks.add(website); String html = getHtml(website); if(html==null) return jobs; Matcher htmlMatcher = linkPattern.matcher(html); // Check links for career keywords to search more pages and search those while (htmlMatcher.find()) if(careerPattern.matcher(htmlMatcher.group(2)).find() &&!visitedLinks.contains(htmlMatcher.group(1))){ jobs.addAll(getInternSites(htmlMatcher.group(1))); } // Check this page for intern keywords and add it if so and then return the whole list if(internPattern.matcher(html).find()) jobs.add(website); // Return all current sites found with intern keywords return jobs; } /** * Gets the HTML of the given website as a String * * @param url The URL of the website to get the HTML of * @return The HTML of the website */ private static String getHtml(String url){ // Get the html of the page String html; Scanner scanner = null; try { // Open connection to URL and trick it to thinking Java is firefox URLConnection connection = new URL(url).openConnection(); connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"); // Create a scanner on the connection and get the html from that scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); html = scanner.next(); }catch ( Exception ex ) { // If the errored link is actually a link (i.e. starts with http) add it to the error list if(url.startsWith("http")) errorLinks.add(url); // Return null since couldn't get the html return null; } finally { // Close the scanner just in case it is open if(scanner!=null) scanner.close(); } // replace special characters and return the html html = html.replaceAll("&ndash;", "-"); html = html.replaceAll("&mdash;", "—"); html = html.replaceAll("&iexcl;", "¡"); html = html.replaceAll("&iquest;", "¿"); html = html.replaceAll("&quot;", "\""); html = html.replaceAll("&ldquo;", "“"); html = html.replaceAll("&rdquo;", "”"); html = html.replaceAll("&lsquo;", "‘"); html = html.replaceAll("&rsquo;", "’"); html = html.replaceAll("&raquo;", "«"); html = html.replaceAll("&rdquo;", "»"); html = html.replaceAll("&nbsp;", " "); html = html.replaceAll("&amp;", "&"); html = html.replaceAll("&cent;", "¢"); html = html.replaceAll("&copy;", "©"); html = html.replaceAll("&divide;", "÷"); html = html.replaceAll("&gt;", ">"); html = html.replaceAll("&lt;", "<"); html = html.replaceAll("&micro;", "µ"); html = html.replaceAll("&middot;", "·"); html = html.replaceAll("&para;", "¶"); html = html.replaceAll("&plusmn;", "±"); html = html.replaceAll("&euro;", "€"); html = html.replaceAll("&pound;", "£"); html = html.replaceAll("&reg;", "®"); html = html.replaceAll("&sect;", "§"); html = html.replaceAll("&trade;", "™"); html = html.replaceAll("&yen;", "¥"); html = html.replaceAll("&times;", "×"); html = html.replaceAll("&hellip;", "…"); html = html.replaceAll("“", "“"); html = html.replaceAll("â€", "”"); return html; } }
NecroTheif/Internship-Finder
src/Main.java
Java
mit
9,213
package org.virtue.game.entity.combat.impl; import java.util.Optional; import org.virtue.game.entity.Entity; import org.virtue.game.entity.combat.impl.melee.MeleeFollower; import org.virtue.game.entity.combat.impl.range.RangeFollower; import org.virtue.game.entity.player.Player; import org.virtue.game.map.CoordGrid; import org.virtue.game.map.movement.path.Path; import org.virtue.game.map.movement.path.PathfinderProvider; /** * Interface for combat following handlers. * @author Emperor * */ public abstract class FollowingType { /** * The melee following type. */ public static final FollowingType MELEE = new MeleeFollower(); /** * The range following type. */ public static final FollowingType RANGE = new RangeFollower(); /** * The magic following type. */ public static final FollowingType MAGIC = new RangeFollower();//TODO /** * Follows the locked target. * @param entity The entity following the target. * @param lock The locked target. * @return {@code True} if the entity is in correct distance to attack the target. */ public boolean follow(Entity entity, Entity lock) { if (!entity.getCurrentTile().withinDistance(lock.getCurrentTile(), 20)) { entity.getCombatSchedule().releaseLock(); return false; } Interaction interaction = getInteraction(entity, lock); if (interaction == Interaction.STILL) { entity.getMovement().reset(); return true; } CoordGrid destination = lock.getCurrentTile(); if (entity.getCurrentTile().equals(destination)) { Optional<Path> path = PathfinderProvider.findAdjacent(lock); if (!path.isPresent() || !entity.getMovement().setWaypoints(path.get().getPoints())) { entity.getCombatSchedule().releaseLock(); return false; } } else if (!entity.getMovement().hasSteps() || !destination.isAdjacent(entity.getMovement().getDestination())) { Path path = PathfinderProvider.find(entity, lock, false, entity instanceof Player ? PathfinderProvider.SMART : PathfinderProvider.DUMB); if (path == null || !path.isSuccessful() || !entity.getMovement().setWaypoints(path.getPoints())) { entity.getCombatSchedule().releaseLock(); return false; } } return interaction == Interaction.MOVING; } /** * Gets the next destination. * @param entity The entity. * @param lock The target. * @return The next destination. */ public CoordGrid getNextDestination(Entity entity, Entity lock) { return lock.getCurrentTile(); } /** * If the entity can attack from its current location. * @param entity The attacking entity. * @param lock The locked target. * @return {@code True} if so. */ public abstract Interaction getInteraction(Entity entity, Entity lock); /** * Checks if the mover is standing on an invalid position. * @param l The location. * @return {@code True} if so. */ public static boolean isInsideEntity(CoordGrid l, Entity lock) { if (lock.getMovement().hasSteps()) { return false; } CoordGrid loc = lock.getCurrentTile(); int size = lock.getSize(); if (l.getX() >= size + loc.getX() || lock.getSize() + l.getX() <= loc.getX()) { return false; } if (loc.getY() + size <= l.getY() || l.getY() + lock.getSize() <= loc.getY()) { return false; } return true; } /** * Combat movement interaction types. * @author Emperor * */ public static enum Interaction { /** * Can't currently interact. */ NONE, /** * Can currently interact and doesn't have to move. */ STILL, /** * Can interact but has to move. */ MOVING; } }
Sundays211/VirtueRS3
src/main/java/org/virtue/game/entity/combat/impl/FollowingType.java
Java
mit
3,581
package eu.bcvsolutions.idm.core.api.domain; import org.springframework.http.HttpStatus; import eu.bcvsolutions.idm.core.notification.api.domain.NotificationLevel; /** * Enum class for formatting response messages (mainly errors). * Every enum contains a string message and corresponding https HttpStatus code. * * Used http codes: * - 2xx - success * - 4xx - client errors (validations, conflicts ...) * - 5xx - server errors * * ImmutableMap can be used for code parameters - linked map is needed for parameter ordering. * Lookout - ImmutableMap parameter values cannot be {@code null}! * * @author Radek Tomiška */ public enum CoreResultCode implements ResultCode { // // 2xx OK(HttpStatus.OK, "ok"), ACCEPTED(HttpStatus.ACCEPTED, " "), DELETED(HttpStatus.ACCEPTED, "Request to delete content accepted."), DRY_RUN(HttpStatus.NO_CONTENT, "Dry run mode"), DIRTY_STATE(HttpStatus.CREATED, "For entity id [%s] was set dirty state flag."), // // Commons 4xx BAD_REQUEST(HttpStatus.BAD_REQUEST, "The value is wrong!"), BAD_VALUE(HttpStatus.BAD_REQUEST, "The value %s is wrong!"), BAD_UUID(HttpStatus.BAD_REQUEST, "The value %s is not uuid!"), CODE_CONFLICT(HttpStatus.CONFLICT, "Record with given code already exists, by constraint [%s]."), NAME_CONFLICT(HttpStatus.CONFLICT, "Record with for given name already exists, by constraint [%s]"), CONFLICT(HttpStatus.CONFLICT, "%s"), NULL_ATTRIBUTE(HttpStatus.BAD_REQUEST, "Attribute '%s' is NULL."), NOT_FOUND(HttpStatus.NOT_FOUND, "%s not found."), ENTITY_NOT_FOUND(HttpStatus.NOT_FOUND, "Entity type [%s] with id [%s] not found.", NotificationLevel.INFO), CONTENT_DELETED(HttpStatus.CONFLICT, "Content [%s] with type [%s] was deleted. Operation cannot be executed and will be canceled."), WF_WARNING(HttpStatus.BAD_REQUEST, "Warning occured during workflow execution: %s"), WF_TASK_FILTER_INVOLVED_ONLY(HttpStatus.BAD_REQUEST, "Task filter 'onlyInvolved' cannot be set to FALSE via REST!"), BAD_FILTER(HttpStatus.BAD_REQUEST, "The filter is wrong!"), UNMODIFIABLE_ATTRIBUTE_CHANGE(HttpStatus.BAD_REQUEST, "Attribute %s for class %s can't be changed!"), UNMODIFIABLE_DELETE_FAILED(HttpStatus.BAD_REQUEST, "Unmodifiable record [%s] can't be deleted!"), OPTIMISTIC_LOCK_ERROR(HttpStatus.CONFLICT, "Record was modified with the different process or identity. Try to reload the record and then retry the operation."), // http ENDPOINT_NOT_FOUND(HttpStatus.NOT_FOUND, "The given endpoint doesn't exist!"), METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, "Method is not allowed!"), // auth errors AUTH_FAILED(HttpStatus.UNAUTHORIZED, "Authentication failed - bad credentials."), AUTH_BLOCKED(HttpStatus.UNAUTHORIZED, "Authentication failed - login for identity [%s] is blocked due [%s]. Seconds from now [%s]."), AUTH_EXPIRED(HttpStatus.UNAUTHORIZED, "Authentication expired.", NotificationLevel.INFO), CAS_TICKET_VALIDATION_FAILED(HttpStatus.UNAUTHORIZED, "Authentication failed - CAS ticket validation failed."), CAS_LOGIN_SERVER_URL_NOT_CONFIGURED(HttpStatus.UNAUTHORIZED, "CAS authentication failed - CAS server url is not configured."), CAS_LOGOUT_SERVER_URL_NOT_CONFIGURED(HttpStatus.UNAUTHORIZED, "CAS logout failed - CAS server url is not configured."), CAS_LOGIN_SERVER_NOT_AVAILABLE(HttpStatus.UNAUTHORIZED, "CAS authentication failed - CAS server is not available."), CAS_IDM_LOGIN_ADMIN_ONLY(HttpStatus.UNAUTHORIZED, "CAS authentication is enabled, appication admin can sign in by IdM only."), CAS_LOGOUT_SERVER_NOT_AVAILABLE(HttpStatus.UNAUTHORIZED, "CAS logout failed - CAS server is not available."), TOKEN_NOT_FOUND(HttpStatus.UNAUTHORIZED, "Token not found."), TOKEN_READ_FAILED(HttpStatus.BAD_REQUEST, "Wrong token given."), TWO_FACTOR_INIT_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Two factor authentication is not available."), TWO_FACTOR_AUTH_REQIURED(HttpStatus.UNAUTHORIZED, "Verification code is needed.", NotificationLevel.INFO), TWO_FACTOR_VERIFICATION_CODE_FAILED(HttpStatus.UNAUTHORIZED, "Verification code is not valid."), TWO_FACTOR_GENERATE_CODE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Verification code cannot be generated."), AUTHORITIES_CHANGED(HttpStatus.UNAUTHORIZED, "Authorities changed or user logged out, log in again.", NotificationLevel.INFO), LOG_IN(HttpStatus.UNAUTHORIZED, "You need to be logged in."), LOG_IN_FAILED(HttpStatus.UNAUTHORIZED, "Log in failed."), XSRF(HttpStatus.UNAUTHORIZED, "XSRF cookie failed."), FORBIDDEN(HttpStatus.FORBIDDEN, "Forbidden."), FORBIDDEN_ENTITY(HttpStatus.FORBIDDEN, "Forbidden: entity [%s], permission [%s], type [%s]."), FORBIDDEN_CODEABLE_ENTITY(HttpStatus.FORBIDDEN, "Forbidden: Entity with ID [%s], permission [%s], type [%s], code [%s]."), DUPLICATE_EXTERNAL_ID(HttpStatus.CONFLICT, "Entity type [%s] with external identifier [%s] already exist (id: [%s])."), DUPLICATE_EXTERNAL_CODE(HttpStatus.CONFLICT, "Entity type [%s] with external code [%s] already exist (id: [%s])."), ENTITY_TYPE_NOT_EXTERNAL_IDENTIFIABLE(HttpStatus.BAD_REQUEST, "Entity type [%s] is not external identifiable."), ENTITY_TYPE_NOT_EXTERNAL_CODEABLE(HttpStatus.BAD_REQUEST, "Entity type [%s] is not external codeable."), ENTITY_TYPE_NOT_DISABLEABLE(HttpStatus.BAD_REQUEST, "Entity type [%s] is not disableable."), CORRELATION_PROPERTY_NOT_FOUND(HttpStatus.BAD_REQUEST, "Entity type [%s] does not contains the correlation property [%s]."), CORRELATION_PROPERTY_WRONG_TYPE(HttpStatus.BAD_REQUEST, "Entity type [%s] and property [%s] has wrong type. Only String or UUID is supported now."), // data SEARCH_ERROR(HttpStatus.BAD_REQUEST, "Error during searching entities. Error: %s"), UNMODIFIABLE_LOCKED(HttpStatus.CONFLICT, "This entity [%s] cannot be modified (is locked)!"), // filter FILTER_IMPLEMENTATION_NOT_FOUND(HttpStatus.CONFLICT, "Filter implementation [%s] for property [%s] not found. Repair configuration property [%s]."), FILTER_PROPERTY_NOT_SUPPORTED(HttpStatus.NOT_IMPLEMENTED, "Filter for property [%s] for entity [%s] is not supported and cannot be used."), FILTER_SIZE_EXCEEDED(HttpStatus.BAD_REQUEST, "Filter for property [%s] for entity [%s] - count of values exceeded, given [%s] values, max [%s]."), // identity IDENTITY_ALREADY_DISABLED_MANUALLY(HttpStatus.BAD_REQUEST, "Identity [%s] is already disabled manually, cannot be disable twice."), IDENTITY_NOT_DISABLED_MANUALLY(HttpStatus.BAD_REQUEST, "Identity [%s] is not disabled manually [%s], cannot be enabled."), IDENTITYIMAGE_WRONG_FORMAT(HttpStatus.BAD_REQUEST, "Uploaded file is not an image!"), IDENTITY_USERNAME_EXIST(HttpStatus.CONFLICT, "Username [%s] already exists!"), IDENTITY_UNABLE_GENERATE_UNIQUE_USERNAME(HttpStatus.CONFLICT, "Unable to generate unique username. All numbers from set range have been used!"), IDENTITY_DELETE_FAILED_HAS_CONTRACTS(HttpStatus.CONFLICT, "Identity [%s] cannot be deleted - have assigned contracts."), IDENTITY_PROFILE_IMAGE_WRONG_CONTENT_TYPE(HttpStatus.BAD_REQUEST, "Profile image has wrong content type [%s]. Image content types (image/*) are supported only."), IDENTITY_PROFILE_IMAGE_MAX_FILE_SIZE_EXCEEDED(HttpStatus.BAD_REQUEST, "Profile image file size [%s] exceeded maximum [%s]."), // password change PASSWORD_CHANGE_NO_SYSTEM(HttpStatus.BAD_REQUEST, "No system selected."), PASSWORD_CHANGE_CURRENT_FAILED_IDM(HttpStatus.BAD_REQUEST, "Given current password doesn't match to current idm password."), PASSWORD_CHANGE_FAILED(HttpStatus.BAD_REQUEST, "Password change failed: %s."), PASSWORD_CHANGE_ACCOUNT_FAILED(HttpStatus.CONFLICT, "Password change failed on accounts [%s]."), PASSWORD_CHANGE_ACCOUNT_SUCCESS(HttpStatus.OK, "Password is changed on accounts [%s]."), PASSWORD_CHANGE_ALL_ONLY(HttpStatus.BAD_REQUEST, "Password change is enabled for all systems only. Select all systems (idm, all accounts)"), PASSWORD_CHANGE_DISABLED(HttpStatus.BAD_REQUEST, "Password change is disabled"), PASSWORD_EXPIRED(HttpStatus.UNAUTHORIZED, "Password expired"), MUST_CHANGE_IDM_PASSWORD(HttpStatus.UNAUTHORIZED, "User [%s] has to change password"), PASSWORD_DOES_NOT_MEET_POLICY(HttpStatus.BAD_REQUEST, "Password does not match password policy: %s", NotificationLevel.INFO), PASSWORD_PREVALIDATION(HttpStatus.ACCEPTED, "Password does not match password policy: %s"), PASSWORD_CANNOT_CHANGE(HttpStatus.BAD_REQUEST, "You cannot change your password yet. Please try it again after [%s]."), // password create PASSWORD_CANNOT_BE_CREATED(HttpStatus.BAD_REQUEST, "Password cannot be created"), TASK_SAME_DELEGATE_AS_CURRENT_IDENTITY(HttpStatus.BAD_REQUEST, "You cannot create self delegation [%s]"), // tree TREE_NODE_BAD_PARENT(HttpStatus.BAD_REQUEST, "Tree node [%s], have bad parent."), TREE_NODE_EMPTY_CODE(HttpStatus.BAD_REQUEST, "Empty code for newly saved tree node."), TREE_NODE_BAD_TYPE(HttpStatus.BAD_REQUEST, "Tree node [%s], have bad type."), TREE_NODE_BAD_CHILDREN(HttpStatus.BAD_REQUEST, "Tree node [%s], have bad children."), TREE_NODE_BAD_NICE_NAME(HttpStatus.CONFLICT, "Nice name [%s] is found at same level."), TREE_NODE_DELETE_FAILED_HAS_CHILDREN(HttpStatus.CONFLICT, "Tree node [%s] has children, cannot be deleted. Remove them at first."), TREE_NODE_DELETE_FAILED_HAS_CONTRACTS(HttpStatus.CONFLICT, "Tree node [%s] has contract assigned, cannot be deleted. Remove them at first."), TREE_NODE_DELETE_FAILED_HAS_CONTRACT_POSITIONS(HttpStatus.CONFLICT, "Tree node [%s] has contract posistion assigned, cannot be deleted. Remove them at first."), TREE_NODE_DELETE_FAILED_HAS_CONTRACT_SLICES(HttpStatus.CONFLICT, "Tree node [%s] has contract slice assigned, cannot be deleted. Remove them at first."), TREE_NODE_DELETE_FAILED_HAS_ROLE(HttpStatus.CONFLICT, "Tree node [%s] has assigned automatic roles. Remove automatic roles at first."), TREE_TYPE_DELETE_FAILED_HAS_CHILDREN(HttpStatus.CONFLICT, "Tree type [%s] has children, cannot be deleted. Remove them at first."), TREE_TYPE_DELETE_FAILED_HAS_CONTRACTS(HttpStatus.CONFLICT, "Tree type [%s] has contract assigned, cannot be deleted. Remove them at first."), // role catalogs ROLE_CATALOGUE_BAD_PARENT(HttpStatus.BAD_REQUEST, "Role catalogue [%s] has bad parent."), ROLE_CATALOGUE_DELETE_FAILED_HAS_CHILDREN(HttpStatus.CONFLICT, "Role catalogue [%s] has children, cannot be deleted. Remove them at first."), ROLE_CATALOGUE_FORCE_DELETE_HAS_CHILDREN(HttpStatus.FOUND, "Role catalogue [%s] has catalogue items (children). Remove sub catalogue items before or use force delete."), ROLE_CATALOGUE_BAD_NICE_NAME(HttpStatus.CONFLICT, "Nice name [%s] is found at same level."), // MODULE_NOT_DISABLEABLE(HttpStatus.BAD_REQUEST, "Module [%s] is not disableable."), MODULE_DISABLED(HttpStatus.BAD_REQUEST, "Module [%s] is disabled."), CONFIGURATION_DISABLED(HttpStatus.BAD_REQUEST, "Configuration [%s] is disabled."), CONFIGURATION_SWITCH_INSTANCE_NOT_CHANGED(HttpStatus.BAD_REQUEST, "Previous instance is the same as newly used for asynchronous processing [%s]. Instance will not be changed."), CONFIGURATION_SWITCH_INSTANCE_MORE_PREVIOUS_FOUND(HttpStatus.FOUND, "Found more previously used instances for asynchronous processing [%s].", NotificationLevel.INFO), CONFIGURATION_SWITCH_INSTANCE_SUCCESS(HttpStatus.OK, "Instance for asynchronous processing changed from [%s] to [%s]. Updated [%s] scheduled tasks, [%s] created long runnung tasks and [%s] created events."), // role ROLE_DELETE_FAILED_IDENTITY_ASSIGNED(HttpStatus.CONFLICT, "Role [%s] cannot be deleted - some identites have role assigned."), ROLE_DELETE_FAILED_HAS_TREE_NODE(HttpStatus.CONFLICT, "Role [%s] has assigned automatic roles. Remove automatic roles at first."), ROLE_DELETE_FAILED_AUTOMATIC_ROLE_ASSIGNED(HttpStatus.CONFLICT, "Role [%s] cannot be deleted - some automatic roles by attribe has assigned this role."), ROLE_DELETE_FAILED_HAS_COMPOSITION(HttpStatus.CONFLICT, "Role [%s] cannot be deleted - composition is defined. Remove role composition at first."), ROLE_CODE_ENVIRONMENT_CONFLICT(HttpStatus.CONFLICT, "Role code [%s] cannot be combined with environment [%s]. Use base code with environment instead."), ROLE_CODE_REQUIRED(HttpStatus.BAD_REQUEST, "Role code (code or base code) is required."), // groovy script GROOVY_SCRIPT_VALIDATION(HttpStatus.BAD_REQUEST, "Script contains compillation errors."), GROOVY_SCRIPT_SYNTAX_VALIDATION(HttpStatus.BAD_REQUEST, "Script contains syntaxt error: [%s] at line [%s]."), GROOVY_SCRIPT_SECURITY_VALIDATION(HttpStatus.BAD_REQUEST, "Script did not pass security inspection!"), GROOVY_SCRIPT_NOT_ACCESSIBLE_CLASS(HttpStatus.BAD_REQUEST, "Class [%s] isn't accessible!"), GROOVY_SCRIPT_NOT_ACCESSIBLE_SERVICE(HttpStatus.BAD_REQUEST, "Service [%s] isn't accessible!"), GROOVY_SCRIPT_EXCEPTION(HttpStatus.BAD_REQUEST, "Script has some errors: [%s]"), GROOVY_SCRIPT_INVALID_CATEGORY(HttpStatus.BAD_REQUEST, "Script call script from invalid category: [%s]"), // eav FORM_VALUE_WRONG_TYPE(HttpStatus.BAD_REQUEST, "Form value [%s] for attribute [%s] has to be type of [%s], given [%s]"), FORM_ATTRIBUTE_DELETE_FAILED_HAS_VALUES(HttpStatus.CONFLICT, "Form attribute [%s] cannot be deleted - some form values already using this attribute."), FORM_ATTRIBUTE_CHANGE_PERSISTENT_TYPE_FAILED_HAS_VALUES(HttpStatus.CONFLICT, "Persistent type for form attribute [%s] cannot be changed - some form values already using this attribute. Data migrations are not implemented."), FORM_ATTRIBUTE_CHANGE_CONFIDENTIAL_FAILED_HAS_VALUES(HttpStatus.CONFLICT, "Confidential flag for form attribute [%s] cannot be changed - some form values already using this attribute. Data migrations are not implemented."), FORM_ATTRIBUTE_DELETE_FAILED_SYSTEM_ATTRIBUTE(HttpStatus.CONFLICT, "Form attribute [%s] cannot be deleted - this attribute is flaged as system attribute."), FORM_ATTRIBUTE_DELETE_FAILED_ROLE_ATTRIBUTE(HttpStatus.CONFLICT, "Form attribute [%s] cannot be deleted - is using as role-attribute for role [%s]."), FORM_DEFINITION_DELETE_FAILED_SYSTEM_DEFINITION(HttpStatus.CONFLICT, "Form definition [%s] cannot be deleted - this definition is flaged as system definition."), FORM_DEFINITION_INCOMPATIBLE_CHANGE(HttpStatus.CONFLICT, "Form definition [%s][%s] cannot be updated. Attribute's [%s] property [%s] cannot be updated automatically [%s to %s]. Provide change script for updating form definition or define new form definition (~new version)."), FORM_DEFINITION_DELETE_FAILED_MAIN_FORM(HttpStatus.CONFLICT, "Form definition [%s] cannot be deleted - this definition is flaged as main. Select another one as main before deletion."), FORM_DEFINITION_UPDATE_FAILED_MAIN_FORM(HttpStatus.CONFLICT, "Form definition [%s] cannot be updated - this definition was flaged as main. Select another one as main instead."), FORM_ATTRIBUTE_DELETE_FAILED_AUTOMATIC_ROLE_RULE_ASSIGNED(HttpStatus.CONFLICT, "Form attribute [%s] cannot be deleted - some automatic rules use this attribute."), FORM_DEFINITION_DELETE_FAILED_ROLE(HttpStatus.CONFLICT, "Form definition [%s] cannot be deleted - role [%s] using that defintion."), FORM_INVALID(HttpStatus.BAD_REQUEST, "Form is not valid. Attributes: [%s]."), FORM_VALIDATION_NOT_SUPPORTED(HttpStatus.BAD_REQUEST, "Form validation type [%s] is not supported for persistent type [%s] for attribute [%s]."), FORM_ATTRIBUTE_INVALID_REGEX(HttpStatus.BAD_REQUEST, "Regular expression [%s] for the form attribute [%s] is not valid."), FORM_VALUE_DELETE_FAILED_IS_REQUIRED(HttpStatus.CONFLICT, "Form values [%s] cannot be deleted. Form attribute [%s] is defined as required. Change form attribute definition if values are needed to be removed."), FORM_PROJECTION_WRONG_VALIDATION_CONFIGURATION(HttpStatus.CONFLICT, "Form projection [%s] is wrongly configured. Fix configured form validations."), // audit AUDIT_REVISION_NOT_SAME(HttpStatus.BAD_REQUEST, "Audit revision are not same."), AUDIT_ENTITY_CLASS_NOT_FOUND(HttpStatus.NOT_FOUND, "Entity class [%s] not found."), AUDIT_ENTITY_CLASS_IS_NOT_FILLED(HttpStatus.NOT_FOUND, "Entity class isn't filled."), // PASSWORD_POLICY_DEFAULT_TYPE(HttpStatus.CONFLICT, "Default password policy is exist. Name [%s]"), PASSWORD_POLICY_DEFAULT_TYPE_NOT_EXIST(HttpStatus.NOT_FOUND, "Default password policy is not exist."), PASSWORD_POLICY_BAD_TYPE(HttpStatus.BAD_REQUEST, "Password policy has bad type: [%s]."), PASSWORD_POLICY_VALIDATION(HttpStatus.BAD_REQUEST, "Password policy validation problem."), PASSWORD_POLICY_MAX_LENGTH_LOWER(HttpStatus.BAD_REQUEST, "Password policy has max length lower than min length."), PASSWORD_POLICY_ALL_MIN_REQUEST_ARE_HIGHER(HttpStatus.BAD_REQUEST, "Password policy has sum of all minimum request higher than maximum length."), PASSWORD_POLICY_MAX_AGE_LOWER(HttpStatus.BAD_REQUEST, "Password policy has max password age lower than min age."), PASSWORD_POLICY_MAX_RULE(HttpStatus.BAD_REQUEST, "Password policy: minimum rules to fulfill must be [%s] or lower."), PASSWORD_POLICY_NEGATIVE_VALUE(HttpStatus.BAD_REQUEST, "Password policy can not contain negative values. Attribute: [%s]"), PASSWORD_POLICY_BLOCK_TIME_IS_REQUIRED(HttpStatus.BAD_REQUEST, "Attribute 'Max login attempts' attribute has value, but time of blocking missing (for policy [%s])!"), PASSWORD_POLICY_INVALID_SETTING(HttpStatus.BAD_REQUEST, "No generated password is able to meet policy constraints."), // SCHEDULER_INVALID_CRON_EXPRESSION(HttpStatus.BAD_REQUEST, "Cron expression [%s] is invalid."), SCHEDULER_UNSUPPORTED_TASK_TRIGGER(HttpStatus.BAD_REQUEST, "Task trigger [%s] is not supported."), SCHEDULER_CREATE_TASK_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), SCHEDULER_DELETE_TASK_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), SCHEDULER_INTERRUPT_TASK_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), SCHEDULER_CREATE_TRIGGER_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), SCHEDULER_DELETE_TRIGGER_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), SCHEDULER_PAUSE_TRIGGER_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), SCHEDULER_RESUME_TRIGGER_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), SCHEDULER_DRY_RUN_NOT_SUPPORTED(HttpStatus.BAD_REQUEST, "Task type [%s] does not support dry run mode."), // // logger LOGGER_LEVEL_NOT_FOUND(HttpStatus.BAD_REQUEST, "Logger level [%s] does not exist. Available logger levels [TRACE, DEBUG, INFO, WARN, ERROR]."), // LONG_RUNNING_TASK_NOT_FOUND(HttpStatus.BAD_REQUEST, "Task type [%s] can not be instantiated"), LONG_RUNNING_TASK_NOT_RUNNING(HttpStatus.BAD_REQUEST, "Task [%s] is not running - can not be innterrupted or cancelled."), LONG_RUNNING_TASK_DIFFERENT_INSTANCE(HttpStatus.BAD_REQUEST, "Task [%s] has different instance [%s], can not be accessed from this instance [%s]."), LONG_RUNNING_TASK_IS_RUNNING(HttpStatus.BAD_REQUEST, "Task [%s] is already running - can not be started twice."), LONG_RUNNING_TASK_ACCEPTED(HttpStatus.ACCEPTED, "Concurrent task is already running. Task will be started asynchronously after concurrent task ends."), LONG_RUNNING_TASK_DELETE_FAILED_IS_RUNNING(HttpStatus.BAD_REQUEST, "Task [%s] is already running - cannot be deleted. Cancel task or wait to complete."), LONG_RUNNING_TASK_IS_PROCESSED(HttpStatus.BAD_REQUEST, "Task [%s] is already processed - can not be started twice"), LONG_RUNNING_TASK_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Task [%s] type [%s] ended on instance [%s] with exception."), LONG_RUNNING_TASK_ITEM_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Processing task item for candidate [%s] ended with exception."), LONG_RUNNING_TASK_CANCELED_BY_RESTART(HttpStatus.GONE, "Task [%s] type [%s] on instance [%s] was canceled during restart."), LONG_RUNNING_TASK_INTERRUPT(HttpStatus.INTERNAL_SERVER_ERROR, "Task [%s] type [%s] on instance [%s] was interrupted."), LONG_RUNNING_TASK_INIT_FAILED(HttpStatus.BAD_REQUEST, "Task [%s] type [%s] has invalid properties."), LONG_RUNNING_TASK_PARTITIAL_DOWNLOAD(HttpStatus.PARTIAL_CONTENT, "Task finished successfully, result can be download as separate attachment."), LONG_RUNNING_TASK_NOT_RECOVERABLE(HttpStatus.INTERNAL_SERVER_ERROR, "Task [%s] type [%s] cannot run again, is not recoverable."), // PASSWORD_EXPIRATION_TASK_DAYS_BEFORE(HttpStatus.BAD_REQUEST, "'Days before' parameter is required and has to be number greater than zero, given [%s]."), PASSWORD_EXPIRATION_TODAY_INFO(HttpStatus.NOT_MODIFIED, "Password is valid till today. Password expiration will be published next day."), // AUTOMATIC_ROLE_TASK_EMPTY(HttpStatus.BAD_REQUEST, "Automatic role id is required."), AUTOMATIC_ROLE_TASK_INVALID(HttpStatus.BAD_REQUEST, "Set one of automatic role by tree structure or by attribute."), AUTOMATIC_ROLE_TREE_TASK_INVALID(HttpStatus.BAD_REQUEST, "Set at least one of automatic role by tree structure."), AUTOMATIC_ROLE_ASSIGN_NOT_COMPLETE(HttpStatus.BAD_REQUEST, "Role [%s] by automatic role [%s] was not processed completely."), AUTOMATIC_ROLE_ASSIGN_TASK_NOT_COMPLETE(HttpStatus.BAD_REQUEST, "Role [%s] by automatic role [%s] was not assigned for identity [%s]."), AUTOMATIC_ROLE_ASSIGN_TASK_ROLE_ASSIGNED(HttpStatus.OK, "Role [%s] by automatic role [%s] for identity [%s] is assigned."), AUTOMATIC_ROLE_ASSIGN_TASK_ROLE_REMOVED(HttpStatus.OK, "Role [%s] by automatic role [%s] for identity [%s] is removed."), AUTOMATIC_ROLE_ALREADY_ASSIGNED(HttpStatus.OK, "Role [%s] by automatic role [%s] for identity [%s] is assigned."), AUTOMATIC_ROLE_ALREADY_ASSIGNED_TO_CONTRACT(HttpStatus.CONFLICT, "Role [%s] by automatic role [%s] for contract [%s] and position [%s] is already assigned."), AUTOMATIC_ROLE_CONTRACT_IS_NOT_VALID(HttpStatus.BAD_REQUEST, "Role [%s] by automatic role [%s] for identity [%s] was not assigned, contract is not valid (skip)."), AUTOMATIC_ROLE_REMOVE_TASK_NOT_COMPLETE(HttpStatus.BAD_REQUEST, "Role [%s] by automatic role [%s] was not removed for identity [%s]."), AUTOMATIC_ROLE_REMOVE_TASK_RUN_CONCURRENTLY(HttpStatus.BAD_REQUEST, "Automatic role [%s] is removed in concurent task [%s]"), AUTOMATIC_ROLE_REMOVE_TASK_ADD_RUNNING(HttpStatus.BAD_REQUEST, "Automatic role [%s] is added in concurent task [%s], wait for task is complete, after removal."), AUTOMATIC_ROLE_REMOVE_HAS_ASSIGNED_ROLES(HttpStatus.CONFLICT, "Remove automatic role [%s] is not complete, some identity roles [%s] were assigned to identities in the meantime."), AUTOMATIC_ROLE_TASK_RUNNING(HttpStatus.ACCEPTED, "Automatic role is processed in concurent task [%s], wait for task is complete."), AUTOMATIC_ROLE_RULE_ATTRIBUTE_EMPTY(HttpStatus.BAD_REQUEST, "Rule for automatic role hasn't filled necessary attribute: [%s]."), AUTOMATIC_ROLE_RULE_INVALID_COMPARSION_WITH_MULTIPLE_ATTIBUTE(HttpStatus.BAD_REQUEST, "Comparsion [%s] cannot be used with multiple form attribute."), AUTOMATIC_ROLE_RULE_COMPARSION_IS_ONLY_FOR_NUMERIC_ATTRIBUTE(HttpStatus.BAD_REQUEST, "Comparsion [%s] can be used only with numeric form attribute."), AUTOMATIC_ROLE_RULE_INVALID_COMPARSION_BOOLEAN(HttpStatus.BAD_REQUEST, "Comparsion [%s] cannot be used with boolean types."), AUTOMATIC_ROLE_RULE_PERSISTENT_TYPE_TEXT(HttpStatus.BAD_REQUEST, "Persistent type TEXT isn't allowed."), AUTOMATIC_ROLE_PROCESS_TASK_NOT_COMPLETE(HttpStatus.BAD_REQUEST, "Automatic role [%s] was not process correctly, failed contracts add: [%s], failed contracts remove: [%s]."), AUTOMATIC_ROLE_SKIPPED(HttpStatus.ACCEPTED, "Recount of automatic roles was skipped."), AUTOMATIC_ROLE_SKIPPED_INVALID_CONTRACT(HttpStatus.ACCEPTED, "Recount of automatic roles for invalid contract was skipped."), // // role tree node ROLE_TREE_NODE_TYPE_EXISTS(HttpStatus.CONFLICT, "Role tree node for this role id: [%s], tree node id: [%s] and recursion type [%s] already exists"), // // forest index FOREST_INDEX_DISABLED(HttpStatus.BAD_REQUEST, "Forest index is disabled. Enable configuration property [%s]."), FOREST_INDEX_RUNNING(HttpStatus.CONFLICT, "Rebuilding index for forest tree type [%s] already running."), // // notification NOTIFICATION_SYSTEM_TEMPLATE_DELETE_FAILED(HttpStatus.BAD_REQUEST, "System template [%s] can't be deleted."), NOTIFICATION_TOPIC_AND_LEVEL_EXISTS(HttpStatus.CONFLICT, "Configuration can not be saved. Topic [%s] and null level exists!"), NOTIFICATION_TEMPLATE_ERROR_XML_SCHEMA(HttpStatus.BAD_REQUEST, "Failed load template [%s], error in xml schema."), NOTIFICATION_TEMPLATE_MORE_CODE_FOUND(HttpStatus.CONFLICT, "More templates in resource found for code: [%s]."), NOTIFICATION_TEMPLATE_XML_FILE_NOT_FOUND(HttpStatus.NOT_FOUND, "XML file for template code: [%s] not found."), NOTIFICATION_SENDER_IMPLEMENTATION_NOT_FOUND(HttpStatus.CONFLICT, "Sender implementation [%s] for type [%s] not found. Repair configuration property [%s]."), NOTIFICATION_NOT_SENT(HttpStatus.CONFLICT, "Notification was not sent. Notification configuration for topic [%s] not found or is disabled."), NOTIFICATION_CONFIGURATION_RECIPIENT_NOT_FOUND(HttpStatus.BAD_REQUEST, "Recipients are empty. Recipients are required for for notification configuration with topic [%s] with redirect enabled."), NOTIFICATION_TEMPLATE_DELETE_FAILED_USED_CONFIGURATION(HttpStatus.CONFLICT, "Notification template [%s] cannot be deleted, it is used in [%s] notification configuration(s)."), NOTIFICATION_TEMPLATE_DELETE_FAILED_USED_NOTIFICATION(HttpStatus.CONFLICT, "Notification template [%s] cannot be deleted, it is used in [%s] notification(s)."), // // scripts SCRIPT_MORE_CODE_FOUND(HttpStatus.CONFLICT, "More scripts in resource found for code: [%s]."), SCRIPT_XML_FILE_NOT_FOUND(HttpStatus.NOT_FOUND, "XML file for script code: [%s] not found."), // // Role request ROLE_REQUEST_NO_EXECUTE_IMMEDIATELY_RIGHT(HttpStatus.FORBIDDEN, "You do not have right for immidiately execute role request [%s]!"), ROLE_REQUEST_EXECUTE_WRONG_STATE(HttpStatus.BAD_REQUEST, "Request is in state [%s], only state APPROVED and CONCEPT can be executed!"), ROLE_REQUEST_APPLICANTS_NOT_SAME(HttpStatus.BAD_REQUEST, "Some concept/s role in role request [%s] have different applicant than [%s]!"), ROLE_REQUEST_EXECUTED_CANNOT_DELETE(HttpStatus.BAD_REQUEST, "Request [%s] in EXECUTED state cannot be deleted!"), ROLE_REQUEST_AUTOMATICALLY_NOT_ALLOWED(HttpStatus.BAD_REQUEST, "Field 'requested by' in request [%s] cannot be 'AUTOMATICALLY' via REST API!"), ROLE_REQUEST_UNVALID_CONCEPT_ATTRIBUTE(HttpStatus.BAD_REQUEST, "Concept [%s] (for role [%s]) in the request [%s] has unvalid attribute [%s]!"), ROLE_REQUEST_SYSTEM_STATE_CANCELED(HttpStatus.INTERNAL_SERVER_ERROR, "Request system state was canceled from state [%s]!"), // IDENTITY_ROLE_UNVALID_ATTRIBUTE(HttpStatus.BAD_REQUEST, "Identity-role [%s] (for role [%s]) has unvalid attribute [%s]!"), // // Recaptcha RECAPTCHA_SECRET_KEY_MISSING(HttpStatus.INTERNAL_SERVER_ERROR, "Recaptcha component is wrong configured, property [%s] is missing - configure property value."), RECAPTCHA_CHECK_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Recaptcha check failed, error codes [%s]"), RECAPTCHA_SERVICE_UNAVAILABLE(HttpStatus.INTERNAL_SERVER_ERROR, "Recaptcha service is unavailable: %s"), // // Crypt CRYPT_DEMO_KEY_NOT_FOUND(HttpStatus.BAD_REQUEST, "Demo key: [%s] cannot be found! Please create primary key: [%s] or fix demo key."), CRYPT_INITIALIZATION_PROBLEM(HttpStatus.BAD_REQUEST, "Initialization problem, algorithm [%s]."), // AUTHORIZATION_POLICY_GROUP_AUTHORIZATION_TYPE(HttpStatus.BAD_REQUEST, "When authorization type is filled [%s] then groupPermission has to be filled too [%s]."), // // Common 5xx INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "%s"), NOT_IMPLEMENTED(HttpStatus.INTERNAL_SERVER_ERROR, "Not implemented: %s"), NOT_SUPPORTED(HttpStatus.INTERNAL_SERVER_ERROR, "Not supported: %s"), WF_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error occured during workflow execution: %s"), MODEL_MAPPER_SERVICE_INIT_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Service [%s] cannot be used, model mapper is wrongly inited, try to restart this application."), // // backup and redeploy BACKUP_FOLDER_FOUND(HttpStatus.OK, "Backup folder [%s] is configured in application properties."), BACKUP_FOLDER_NOT_FOUND(HttpStatus.BAD_REQUEST, "Backup folder doesn't exist in application properties, please specify this property: [%s]."), BACKUP_FAIL(HttpStatus.BAD_REQUEST, "Backup for script code: [%s] failed. Error message: [%s]."), DEPLOY_ERROR(HttpStatus.BAD_REQUEST, "Failed load entity from path [%s]."), DEPLOY_SCRIPT_FOLDER_FOUND(HttpStatus.OK, "Folder (or classpath) setting for redeploy scripts [%s] is configured in application properties."), DEPLOY_TEMPLATE_FOLDER_FOUND(HttpStatus.OK, "Folder (or classpath) setting for redeploy templates [%s] is configured in application properties."), XML_JAXB_INIT_ERROR(HttpStatus.BAD_REQUEST, "Failed init JAXB instance."), // // Rest template WRONG_PROXY_CONFIG(HttpStatus.INTERNAL_SERVER_ERROR, "Wrong configuration of http proxy. The required format is '[IP]:[PORT]'. Example: '153.25.16.8:1234'"), // // Automatic role request AUTOMATIC_ROLE_REQUEST_START_WITHOUT_RULE(HttpStatus.BAD_REQUEST, "Automatic role request must have at least one rule [%s]"), // ECM ATTACHMENT_INIT_DEFAULT_STORAGE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Creating directory for default storage [%s] in temp directory failed."), ATTACHMENT_INIT_DEFAULT_TEMP_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Creating directory for default temp storage [%s] in temp directory failed."), ATTACHMENT_CREATE_TEMP_FILE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Creating temporary file [%s] in temp directory [%s] failed."), ATTACHMENT_UPDATE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Update attachment [%s] with owner [%s][%s] failed."), ATTACHMENT_CREATE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Create attachment [%s] with owner [%s][%s] failed."), ATTACHMENT_DATA_NOT_FOUND(HttpStatus.NOT_FOUND, "Binary data for attachment [%s:%s] - [%s] not found."), ATTACHMENT_SIZE_LIMIT_EXCEEDED(HttpStatus.BAD_REQUEST, "The attachment data exceeds its maximum permitted size of [%s] bytes."), // // Events EVENT_CANCELED_BY_RESTART(HttpStatus.GONE, "Event [%s] type [%s] on instance [%s] was canceled during restart."), EVENT_DUPLICATE_CANCELED(HttpStatus.OK, "Event [%s] type [%s] for owner [%s] on instance [%s] was canceled, it is duplicate to event [%s]."), EVENT_ALREADY_CLOSED(HttpStatus.OK, "Event is already closed, will be logged only."), EVENT_ACCEPTED(HttpStatus.ACCEPTED, "Event type [%s] for owner [%s] on instance [%s] was put into queue and will be processed asynchronously."), EVENT_EXECUTE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Event [%s] type [%s] for owner [%s] on instance [%s] failed."), EVENT_EXECUTE_PROCESSOR_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Event [%s] failed in processor [%s]."), EVENT_CONTENT_DELETED(HttpStatus.CONFLICT, "Content for event [%s] type [%s] for owner [%s] on instance [%s] was deleted. Event cannot be executed and will be canceled."), EVENT_NOT_RUNNING(HttpStatus.BAD_REQUEST, "Entity event [%s] is not running - can not be cancelled.", NotificationLevel.INFO), // // Identity bulk actions BULK_ACTION_BAD_FILTER(HttpStatus.BAD_REQUEST, "Filter must be instance of [%s], given instance [%s]."), BULK_ACTION_REQUIRED_PROPERTY(HttpStatus.BAD_REQUEST, "Property [%s] is required."), BULK_ACTION_ONLY_ONE_FILTER_CAN_BE_APPLIED(HttpStatus.BAD_REQUEST, "Only one filtering option can be applied."), BULK_ACTION_MODULE_DISABLED(HttpStatus.BAD_REQUEST, "Action [%s] can't be processed. Module [%s] is disabled."), BULK_ACTION_ENTITIES_ARE_NOT_SPECIFIED(HttpStatus.BAD_REQUEST, "Bulk action hasn't specified entities or filter."), BULK_ACTION_INSUFFICIENT_PERMISSION(HttpStatus.FORBIDDEN, "Insufficient permissions for execute bulk action [%s] on record [%s] with code [%s]."), BULK_ACTION_CONTRACT_NOT_FOUND(HttpStatus.NOT_FOUND, "Contract for identity: [%s] not found."), BULK_ACTION_ROLE_NOT_FOUND(HttpStatus.NOT_FOUND, "Roles for remove not found for identity: [%s]."), BULK_ACTION_IDENTITY_REMOVE_ROLE_FAILED(HttpStatus.NOT_FOUND, "Roles for identity [%s] not removed. Roles not found or cannot be removed (its automatic role, business role or for insufficient permissions)."), BULK_ACTION_NOT_AUTHORIZED_CONTRACT_GUARANTEE (HttpStatus.FORBIDDEN, "Insufficient permissions [%s] for the guarantee [%s] for contract [%s]."), BULK_ACTION_NO_CONTRACT_GUARANTEE_EXISTS (HttpStatus.NOT_FOUND, "No contract guarantees found."), BULK_ACTION_TOO_MANY_CONTRACT_GUARANTEE_EXIST (HttpStatus.FORBIDDEN, "Too many contract guarantees found."), BULK_ACTION_TOO_MANY_USERS_SELECTED (HttpStatus.FORBIDDEN, "Too many users selected for this bulk action."), BULK_ACTION_NOT_AUTHORIZED_MODIFY_CONTRACT (HttpStatus.FORBIDDEN, "Insufficient permissions for [%s] contract modification."), BULK_ACTION_NOT_AUTHORIZED_ASSING_ROLE_FOR_CONTRACT (HttpStatus.FORBIDDEN, "Insufficient permissions to assign role for contract [%s]."), // Role bulk actions ROLE_DELETE_BULK_ACTION_NUMBER_OF_IDENTITIES(HttpStatus.FOUND, "Role [%s] has [%s] role-identities."), ROLE_FORCE_DELETE_BULK_ACTION_NUMBER_OF_IDENTITIES(HttpStatus.FOUND, "Role [%s] is assigned [%s] to users. Remove assigned roles before or use force delete."), ROLE_DELETE_BULK_ACTION_CONCEPTS_TO_MODIFY(HttpStatus.FOUND, "[%s] request concepts need to be modified. It may tak a while."), // // Contract and slices CONTRACT_DELETE_FAILED_ROLE_ASSIGNED(HttpStatus.CONFLICT, "Contract [%s] cannot be deleted - have assigned roles."), CONTRACT_IS_CONTROLLED_CANNOT_BE_MODIFIED(HttpStatus.CONFLICT, "Contract [%s] is controlled by slices. It cannot be modified directly!"), CONTRACT_IS_CONTROLLED_CANNOT_BE_DELETED(HttpStatus.CONFLICT, "Contract [%s] is controlled by slices. It cannot be deleted directly!"), CONTRACT_IS_CONTROLLED_GUARANTEE_CANNOT_BE_MODIFIED(HttpStatus.CONFLICT, "Contract [%s] is controlled by slices. Contract guarantee cannot be modified directly!"), CONTRACT_IS_CONTROLLED_GUARANTEE_CANNOT_BE_DELETED(HttpStatus.CONFLICT, "Contract [%s] is controlled by slices. Contract guarantee cannot be deleted directly!"), CONTRACT_SLICE_DUPLICATE_CANDIDATES(HttpStatus.CONFLICT, "We found more then once slice which should be use as contract. This is not allowed. None from this slices will be used as contract. It means contracts [%s] are in incorrect state now!"), // // Universal requests REQUEST_EXECUTED_CANNOT_DELETE(HttpStatus.BAD_REQUEST, "Request [%s] in EXECUTED state cannot be deleted!"), DTO_CANNOT_BE_CONVERT_TO_JSON(HttpStatus.INTERNAL_SERVER_ERROR, "DTO [%s] cannot be convert to the JSON!"), JSON_CANNOT_BE_CONVERT_TO_DTO(HttpStatus.INTERNAL_SERVER_ERROR, "JSON [%s] cannot be convert to the DTO!"), REQUEST_CUD_OPERATIONS_NOT_ALLOWED(HttpStatus.BAD_REQUEST, "CUD operations are not allowed on that controller [%s]. Use request endpoint!"), REQUEST_NO_EXECUTE_IMMEDIATELY_RIGHT(HttpStatus.FORBIDDEN, "You do not have right (REQUEST_ADMIN) for immidiately execute request [%s]!"), REQUEST_ITEM_IS_NOT_VALID(HttpStatus.BAD_REQUEST, "DTO [%s] in the request item [%s] is not valid!"), REQUEST_NO_WF_DEF_FOUND(HttpStatus.BAD_REQUEST, "No approval workflow definition found for entity type [%s]!"), REQUEST_OWNER_WAS_DELETED(HttpStatus.GONE, "Owner [%s] was deleted!"), REQUEST_OWNER_FROM_OTHER_REQUEST_WAS_DELETED(HttpStatus.GONE, "Owner [%s] from other request [%s] was deleted!"), REQUEST_CANNOT_BE_EXECUTED_NONE_ITEMS(HttpStatus.BAD_REQUEST, "Request [%s] cannot be executed. He doesn't have any request items!"), REQUEST_ITEM_CANNOT_BE_EXECUTED(HttpStatus.BAD_REQUEST, "Request item [%s] cannot be executed. Must be in state APPROVED or CONCEPT, but is in state [%s]!"), REQUEST_ITEM_CANNOT_BE_CREATED(HttpStatus.BAD_REQUEST, "Request item cannot be created/changed for object [%s]. Parent request must be in state INPROGRESS or CONCEPT or EXCEPTION, but is in state [%s]!"), REQUEST_ITEM_NOT_EXECUTED_PARENT_CANCELED(HttpStatus.BAD_REQUEST, "Request item [%s] could not be executed, because is using DTO from terminated item [%s]!"), REQUEST_ITEM_WRONG_FORM_DEFINITON_IN_VALUES(HttpStatus.BAD_REQUEST, "Request item [%s] could not be saved, because is contains attribute values with wrong form definition! Currently using form definition in the role [%s] is [%s]!"), // // Role composition ROLE_COMPOSITION_RUN_CONCURRENTLY(HttpStatus.ACCEPTED, "Other role composition is already in processing by task [%s]. Role composition [%s] will be processed asynchronously."), ROLE_COMPOSITION_ASSIGN_ROLE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Role [%s] by role composition was not assigned."), ROLE_COMPOSITION_ASSIGNED_ROLE_REMOVAL_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Identity role [%s] was not removed."), ROLE_COMPOSITION_REMOVE_TASK_RUN_CONCURRENTLY(HttpStatus.BAD_REQUEST, "Role composition [%s] is removed in concurent task [%s]."), ROLE_COMPOSITION_REMOVE_TASK_ADD_RUNNING(HttpStatus.BAD_REQUEST, "Role composition [%s] is added in concurent task [%s], wait for task is complete, before composition can be removed."), ROLE_COMPOSITION_REMOVE_HAS_ASSIGNED_ROLES(HttpStatus.CONFLICT, "Remove role composition [%s] is not complete, some identity roles [%s] were assigned to identities in the meantime."), // // generator GENERATOR_FORM_ATTRIBUTE_NOT_FOUND(HttpStatus.NOT_FOUND, "Form attribute for definition [%s] with code [%s] not found."), GENERATOR_FORM_DEFINITION_BAD_TYPE(HttpStatus.BAD_REQUEST, "Given form definition id [%s], has not type. Correct type: [%s]."), GENERATOR_SCRIPT_RETURN_NULL_OR_BAD_DTO_TYPE(HttpStatus.NOT_FOUND, "Script code [%s] return null or bad dto type. Returned value: [%s]."), // // Role form attribute ROLE_FORM_ATTRIBUTE_CHANGE_DEF_NOT_ALLOWED(HttpStatus.BAD_REQUEST, "Change of form definition for role [%s] is not allowed, because for this role exists some IdmRoleFormAttribute. First delete them."), // Export EXPORT_GENERATE_JSON_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "JSON generating from DTO [%s] failed!"), // Import IMPORT_ZIP_EXTRACTION_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Extraction of ZIP import failed!"), EXPORT_ZIP_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Export - Creation of a ZIP failed!"), IMPORT_VALIDATION_FAILED_NO_MANIFEST(HttpStatus.BAD_REQUEST, "Import validation failed. Manifest [%s] was not found!"), IMPORT_CONVERT_TO_DTO_FAILED(HttpStatus.BAD_REQUEST, "Convert file [%s] to DTO [%s] failed!"), IMPORT_IS_ALREADY_RUNNING(HttpStatus.BAD_REQUEST, "Import for [%s] cannot be execute, because is already running!"), EXPORT_IMPORT_FILTER_PARENT_FIELD_MUST_BE_UUID(HttpStatus.BAD_REQUEST, "Export/import parent field [%s] must be UUID and not null, but is [%s]!"), EXPORT_IMPORT_REFLECTION_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Export/import reflection failed!"), EXPORT_IMPORT_IO_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Export/import IO exception occurred!"), IMPORT_FIELD_EMBEDDED_ANNOTATION_MISSING(HttpStatus.BAD_REQUEST, "Annotation embedded was not found for field [%s]!"), IMPORT_FIELD_MUST_CONTAINS_UUID(HttpStatus.BAD_REQUEST, "Field must be UUID but is [%s]!"), IMPORT_ADVANCED_PARING_FAILED_NOT_FOUND(HttpStatus.NOT_FOUND, "Advanced paring failed for field [%s] in DTO [%s]. No DTO [%s] was found on target IdM!"), IMPORT_FAILED_ROOT_NOT_FOUND(HttpStatus.BAD_REQUEST, "No roots found for DTO type [%s]!"), IMPORT_EXECUTED_AS_DRYRUN(HttpStatus.NOT_MODIFIED, "Import executed as dry-run!"), IMPORT_CAN_EXECUTE_ONLY_ADMIN(HttpStatus.BAD_REQUEST, "Import can execute only super-admin!"), IMPORT_DTO_SKIPPED(HttpStatus.NOT_MODIFIED, "Imported DTO [%s] was skipped. Relation on this DTO was not found and this DTO type is marked as optional."), IMPORT_DTO_SKIPPED_DRY_RUN(HttpStatus.NOT_IMPLEMENTED, "Relation on this DTO was not found. Imported DTO [%s] was skipped, because is import executed as dry-run."), IMPORT_ADVANCED_PARING_NOT_FOUND_OPTIONAL(HttpStatus.NOT_FOUND, "Advanced paring failed for field [%s] in DTO [%s]. No DTO [%s] was found on target IdM and import was skipped for it!"), // Delegations DELEGATION_UNSUPPORTED_TYPE(HttpStatus.NOT_FOUND, "Delegation type [%s] is not supported!"), DELEGATION_DEFINITION_CANNOT_BE_UPDATED(HttpStatus.BAD_REQUEST, "Definition of a delegation cannot be updated!"), DELEGATION_DEFINITION_DELEGATOR_AND_DELEGATE_ARE_SAME(HttpStatus.BAD_REQUEST, "Delegator and delegate [%s] cannot be same for one delegation definition!"), MANUAL_TASK_DELEGATION_DELEGATOR_MISSING(HttpStatus.BAD_REQUEST, "Delegator not found. You must apply a filter by delegator (assigned user)!"), MANUAL_TASK_DELEGATION_DELEGATOR_IS_NOT_CANDIDATE(HttpStatus.BAD_REQUEST, "Delegator [%s] isn't candidate of the task [%s]!"), // Uniform password IDENTITY_UNIFORM_PASSWORD(HttpStatus.ACCEPTED, "Identity uniform password."), // Monitoring MONITORING_IGNORED(HttpStatus.ACCEPTED, "Monitoring is ignored."), MONITORING_RESULT(HttpStatus.OK, "Monitoring finished successfully with result."), MONITORING_DATABASE_TABLE(HttpStatus.FOUND, "Table [%s]([%s]) contains [%s] records.", NotificationLevel.SUCCESS), MONITORING_H2_DATABASE_ERROR(HttpStatus.BAD_REQUEST, "H2 database is used on server instance [%s]. H2 database is not supposed to be used for production environment.", NotificationLevel.ERROR), MONITORING_H2_DATABASE_WARNING(HttpStatus.BAD_REQUEST, "H2 database is used on server instance [%s] for [%s] environment.", NotificationLevel.WARNING), MONITORING_H2_DATABASE_SUCCESS(HttpStatus.OK, "H2 database is not used on server instance [%s]. Used database [%s].", NotificationLevel.SUCCESS), MONITORING_DEMO_ADMIN_WARNING(HttpStatus.BAD_REQUEST, "Demo admin credentials are used. Change admin user password.", NotificationLevel.WARNING), MONITORING_DEMO_ADMIN_NOT_FOUND(HttpStatus.OK, "Demo admin user not found.", NotificationLevel.SUCCESS), MONITORING_ENTITY_EVENT_ERROR(HttpStatus.CONFLICT, "Entity event queue contains [%s] errors.", NotificationLevel.ERROR), MONITORING_LONG_RUNNING_TASK_ERROR(HttpStatus.CONFLICT, "Long running task queue contains [%s] errors.", NotificationLevel.ERROR), MONITORING_LOGGING_EVENT_ERROR(HttpStatus.CONFLICT, "Logging events contains [%s] errors.", NotificationLevel.ERROR), MONITORING_EVENT_LOCK_QUEUE(HttpStatus.FOUND, "[%s] threads wait for entity event lock", NotificationLevel.SUCCESS); private final HttpStatus status; private final String message; private final NotificationLevel level; private CoreResultCode(HttpStatus status, String message) { this(status, message, null); } private CoreResultCode(HttpStatus status, String message, NotificationLevel level) { this.message = message; this.status = status; this.level = level; } @Override public String getCode() { return this.name(); } @Override public String getModule() { return "core"; } @Override public HttpStatus getStatus() { return status; } @Override public String getMessage() { return message; } @Override public NotificationLevel getLevel() { return level; } }
bcvsolutions/CzechIdMng
Realization/backend/core/core-api/src/main/java/eu/bcvsolutions/idm/core/api/domain/CoreResultCode.java
Java
mit
42,925
/* * Copyright (c) 2015 iLexiconn * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package net.ilexiconn.magister.container.sub; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class Classroom implements Serializable { @SerializedName("Naam") public String name; }
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/container/sub/Classroom.java
Java
mit
1,374
/* * * Citrus - A object-oriented, interpreted language that is designed to simplify * the creation of dynamic, immediate feedback graphical desktop applications. * * Copyright (c) 2005 Andrew Jensen Ko * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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. * */ package edu.cmu.hcii.citrus.views.behaviors; import edu.cmu.hcii.citrus.*; import edu.cmu.hcii.citrus.views.*; import edu.cmu.hcii.citrus.views.devices.Mouse; public class Resizable extends Behavior { public static final Text DONT_KNOW = new Text("Don't Know"); public static final Text MOVE = new Text("Move"); public static final Text RESIZE = new Text("Resize"); public static final Text RESIZE_LENGTH = new Text("Resize"); public static final Text MOVE_OFFSET = new Text("Move"); public static final Text NO_OP = new Text("NoOp"); public static final Dec<Text> moveOrResize = new Dec<Text>(DONT_KNOW); public static final Dec<Text> xAction = new Dec<Text>(DONT_KNOW); public static final Dec<Text> yAction = new Dec<Text>(DONT_KNOW); public static final Dec<View> tilePicked = new Dec<View>((Element)null, true); public static final Dec<List<Behavior>> behaviors = new Dec<List<Behavior>>(new List<Behavior>( new Behavior(App.mouse.pointer.moved, new Action() { public boolean evaluate(View t) { int xAction, yAction; java.awt.geom.Point2D frp = t.globalToLocal(App.mouse.pointer.getPosition()); if((frp.getX() - t.get(View.left).value) / t.get(View.width).value > .9) xAction = 1; else if((frp.getX() - t.get(View.left).value) / t.get(View.width).value < .1) xAction = 2; else xAction = 3; if((frp.getY() - t.get(View.top).value) / t.get(View.height).value > .9) yAction = 1; else if((frp.getY() - t.get(View.top).value) / t.get(View.height).value < .1) yAction = 2; else yAction = 3; if(xAction == 1 && yAction == 1) t.getWindow().setCursorTo(Mouse.RESIZE_SE_CURSOR); else if(xAction == 1 && yAction == 2) t.getWindow().setCursorTo(Mouse.RESIZE_NE_CURSOR); else if(xAction == 1 && yAction == 3) t.getWindow().setCursorTo(Mouse.RESIZE_W_CURSOR); else if(xAction == 2 && yAction == 1) t.getWindow().setCursorTo(Mouse.RESIZE_SW_CURSOR); else if(xAction == 2 && yAction == 2) t.getWindow().setCursorTo(Mouse.RESIZE_NW_CURSOR); else if(xAction == 2 && yAction == 3) t.getWindow().setCursorTo(Mouse.RESIZE_E_CURSOR); else if(xAction == 3 && yAction == 1) t.getWindow().setCursorTo(Mouse.RESIZE_N_CURSOR); else if(xAction == 3 && yAction == 2) t.getWindow().setCursorTo(Mouse.RESIZE_S_CURSOR); else if(xAction == 3 && yAction == 3) t.getWindow().setCursorTo(Mouse.MOVE_CURSOR); return true; } }), new Behavior(App.mouse.leftButton.pressed, new Action() { public boolean evaluate(View t) { // Pick the tile clicked on App.mouse.pointer.pick.evaluate(t); set(moveOrResize, DONT_KNOW); set(xAction, DONT_KNOW); set(yAction, DONT_KNOW); // If we haven't chosen actions yet, choose one of three actions for the x coordinate java.awt.geom.Point2D frp = App.mouse.pointer.positionRelativeToTilePicked(); double x = t.get(View.left).value; double y = t.get(View.top).value; double w = t.get(View.width).value; double h = t.get(View.height).value; double hp = t.get(View.hPad).value; double vp = t.get(View.vPad).value; if(get(moveOrResize) == DONT_KNOW || get(tilePicked) != t) { set(tilePicked, t); if((frp.getX() - x) / w > .9) set(xAction, RESIZE_LENGTH); else if((frp.getX() - x) / w < .1) set(xAction, MOVE_OFFSET); else set(xAction, NO_OP); if((frp.getY() - y) / h > .9) set(yAction, RESIZE_LENGTH); else if((frp.getY() - y) / h < .1) set(yAction, MOVE_OFFSET); else set(yAction, NO_OP); if(get(xAction) == NO_OP && get(yAction) == NO_OP) set(moveOrResize, MOVE); else set(moveOrResize, RESIZE); } return true; }}), new Behavior(App.mouse.pointer.dragged, new Action() { public boolean evaluate(View t) { if(App.mouse.pointer.isPicked(t)) { java.awt.geom.Point2D frp = App.mouse.pointer.positionRelativeToTilePicked(); double x = t.get(View.left).value; double y = t.get(View.top).value; double w = t.get(View.width).value; double h = t.get(View.height).value; double hp = t.get(View.hPad).value; double vp = t.get(View.vPad).value; // Right if(get(xAction) == RESIZE_LENGTH) { t.set(View.width, new Real(frp.getX() - x - hp)); } // Left else if(get(xAction) == MOVE_OFFSET) { t.set(View.width, new Real(w - (frp.getX() - x - hp))); t.set(View.left, new Real(frp.getX() - hp)); } // Middle else if(get(xAction) == NO_OP && get(moveOrResize) == MOVE) t.set(View.left, new Real(App.mouse.pointer.positionRelativeToPointPicked().getX())); // Bottom if(get(yAction) == RESIZE_LENGTH) t.set(View.height, new Real(frp.getY() - y - vp)); // Top else if(get(yAction) == MOVE_OFFSET) { t.set(View.height, new Real(h - (frp.getY() - y - vp))); t.set(View.top, new Real(frp.getY() - vp)); } // Middle else if(get(yAction) == NO_OP && get(moveOrResize) == MOVE) t.set(View.top, new Real(App.mouse.pointer.positionRelativeToPointPicked().getY())); return true; } else return false; }}), new Behavior(App.mouse.leftButton.released, new Action() { public boolean evaluate(View t) { if(App.mouse.pointer.getViewPicked() == t) { App.mouse.pointer.release.evaluate(t); return true; } else return false; }}) )); }
andyjko/citrus-barista
edu/cmu/hcii/citrus/views/behaviors/Resizable.java
Java
mit
6,289
package com.faforever.client.exception; public class ConfigurationException extends RuntimeException{ public ConfigurationException(String message, Throwable cause) { super(message, cause); } }
FAForever/downlords-faf-client
src/main/java/com/faforever/client/exception/ConfigurationException.java
Java
mit
205
package be.ugent.elis; /** * @deprecated */ public class Rational_Obsolete { int numerator = 0; int denominator = 0; public Rational_Obsolete(int iNumerator, int iDenominator) { numerator = iNumerator; denominator = iDenominator; } public Rational_Obsolete(int integer) { numerator = integer; denominator = 1; } public void abs() { numerator = Math.abs(numerator); denominator = Math.abs(denominator); } public static Rational_Obsolete multiply(Rational_Obsolete l, Rational_Obsolete r) { return new Rational_Obsolete(l.numerator * r.numerator, l.denominator * r.denominator); } public static Rational_Obsolete multiply(int l, Rational_Obsolete r) { return new Rational_Obsolete(l * r.numerator, r.denominator); } public static Rational_Obsolete multiply(Rational_Obsolete l, int r) { return new Rational_Obsolete(l.numerator * r, l.denominator); } private int scm(int a, int b) { return a*b; } public void add(Rational_Obsolete r) { int denScm = scm(denominator, r.denominator); numerator = ((numerator*denScm)/denominator + (r.numerator*denScm)/r.denominator); denominator = denScm; } public Rational_Obsolete clone() { return new Rational_Obsolete(numerator, denominator); } public CharSequence convertToString(int elementLength, boolean includeMinus) { String deno = ""; if (Math.abs(denominator) != 1) deno = String.format("/%d", Math.abs(denominator)); String numb = String.format("%d%s", Math.abs(numerator), deno); if (includeMinus && ((numerator > 0) ^ (denominator > 0)) && (numerator != 0)) numb = "-" + numb; while (numb.length() < elementLength) numb = " " + numb; return numb; } }
S391D4002S576/SARE
src/be/ugent/elis/Rational_Obsolete.java
Java
mit
1,694
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.github.lxyscls.jvmjava.classfile.attribute; import com.github.lxyscls.jvmjava.classfile.ClassReader; import com.github.lxyscls.jvmjava.classfile.constant.ConstantPool; /** * * @author sk-xinyilong */ public class CodeAttributeInfo extends AttributeInfo { private final ConstantPool cp; private final int maxStack; private final int maxLocals; private final byte[] code; private final ExceptionTableEntry[] eTable; private final AttributeInfo[] attributes; CodeAttributeInfo(ClassReader reader, ConstantPool cp) { this.cp = cp; maxStack = reader.readUint16(); maxLocals = reader.readUint16(); code = reader.readBytes((int)reader.readUint32()); int exceptionTableLen = reader.readUint16(); eTable = new ExceptionTableEntry[exceptionTableLen]; for (int i = 0; i < eTable.length; i++) { eTable[i] = new ExceptionTableEntry(reader.readUint16(), reader.readUint16(), reader.readUint16(), reader.readUint16()); } attributes = AttributeInfos.readAttributes(reader, cp); } public int getMaxStack() { return maxStack; } public int getMaxLocals() { return maxLocals; } public byte[] getCode() { return code; } public ExceptionTableEntry[] getExceptionTable() { return eTable; } public AttributeInfo[] getAttributes() { return this.attributes; } }
lxyscls/jvmjava
src/main/java/com/github/lxyscls/jvmjava/classfile/attribute/CodeAttributeInfo.java
Java
mit
1,761
package com.hexmonad.effectivearchitecture.ui.main; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.hexmonad.effectivearchitecture.R; import com.hexmonad.effectivearchitecture.data.model.Item; import butterknife.BindView; import butterknife.ButterKnife; /** * ItemsViewHolder */ public class ItemsViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.list_item_title_text_view) TextView titleTextView; @BindView(R.id.list_item_image_view) ImageView imageView; public ItemsViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public void bind(Item item) { titleTextView.setText(item.getName()); Glide.with(imageView.getContext()) .load(item.getImageUrl()) .into(imageView); } }
hexmonad/android-effective-architecture
app/src/main/java/com/hexmonad/effectivearchitecture/ui/main/ItemsViewHolder.java
Java
mit
943
package jacobi.core.sym; import java.util.function.BinaryOperator; import org.junit.Assert; import org.junit.Test; import jacobi.core.sym.eval.Arithmetic; public class FormulaTest { @Test public void test(){ BinaryOperator<Number> oper = Arithmetic::add; System.out.println(oper); } }
ykechan/jacobi
src/test/java/jacobi/core/sym/FormulaTest.java
Java
mit
317
package com.mopub.mobileads.test.support; import com.mopub.mobileads.factories.VastManagerFactory; import com.mopub.mobileads.util.vast.VastManager; import static org.mockito.Mockito.mock; public class TestVastManagerFactory extends VastManagerFactory { private VastManager mockVastManager = mock(VastManager.class); public static VastManager getSingletonMock() { return getTestFactory().mockVastManager; } private static TestVastManagerFactory getTestFactory() { return (TestVastManagerFactory) instance; } @Override public VastManager internalCreate() { return getTestFactory().mockVastManager; } }
eritiaLabsProjects/es.dsie.cordova.plugins.mobpartner
doc/AndroidPublisherSDK-master/MobPartnerWithMoPubDEMO/mopub-sdk/src/test/java/com/mopub/mobileads/test/support/TestVastManagerFactory.java
Java
mit
662
package com.cisco.app.dbmigrator.migratorapp.logging.codecs; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import org.bson.BsonReader; import org.bson.BsonString; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.Document; import org.bson.codecs.Codec; import org.bson.codecs.CollectibleCodec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import com.cisco.app.dbmigrator.migratorapp.logging.entities.SyncUser; import com.cisco.app.dbmigrator.migratorapp.logging.entities.SyncUser.UserDetailAttributes; public class SyncUserDetailCodec implements CollectibleCodec<SyncUser> { private Codec<Document> documentCodec; Logger logger =Logger.getLogger(this.getClass().getSimpleName()); public SyncUserDetailCodec(Codec<Document> documentCodec) { super(); this.documentCodec = documentCodec; } @Override public void encode(BsonWriter writer, SyncUser user, EncoderContext encoderContext) { logger.info("Start of Encode method"); Document document = new Document(); if (user.getUserid()!=null && !user.getUserid().isEmpty()){ document.append(String.valueOf(UserDetailAttributes._id), user.getUserid()); } if(user.getSourceDbMap()!=null && !user.getSourceDbMap().isEmpty()){ document.append(String.valueOf(UserDetailAttributes.sourceDbMap), user.getSourceDbMap()); } if(user.getTargetDbMap()!=null && !user.getTargetDbMap().isEmpty()){ document.append(String.valueOf(UserDetailAttributes.targetDbMap), user.getTargetDbMap()); } if(user.getUserRoles()!=null && !user.getUserRoles().isEmpty()){ document.append("roles", user.getUserRoles()); } documentCodec.encode(writer, document, encoderContext); logger.info("Encoder completed. Document formed is \n"+document); } @Override public Class<SyncUser> getEncoderClass() { return SyncUser.class; } @SuppressWarnings("unchecked") @Override public SyncUser decode(BsonReader reader, DecoderContext decoderContext) { logger.info("Start of decode method"); SyncUser user = new SyncUser(); Document document = documentCodec.decode(reader, decoderContext); user.setUserid(document.getString(String.valueOf(UserDetailAttributes._id))); user.setSourceDbMap((Map<String, Set<String>>) document.get(String.valueOf(UserDetailAttributes.sourceDbMap))); user.setTargetDbMap((Map<String, Set<String>>) document.get(String.valueOf(UserDetailAttributes.targetDbMap))); user.setUserRoles((List<String>) document.get("roles")); logger.info("Decode completed. Object formed is "+user.toString()); return user; } @Override public boolean documentHasId(SyncUser user) { return user.getUserid()==null; } @Override public SyncUser generateIdIfAbsentFromDocument(SyncUser user) { if (!documentHasId(user)) { user.setUserid((UUID.randomUUID().toString())); } return user; } @Override public BsonValue getDocumentId(SyncUser user) { return new BsonString(user.getUserid()); } }
gagoyal01/mongodb-rdbms-sync
src/main/java/com/cisco/app/dbmigrator/migratorapp/logging/codecs/SyncUserDetailCodec.java
Java
mit
3,102
package guitests; import javafx.scene.input.KeyCodeCombination; import seedu.tasklist.testutil.TestUtil; import org.testfx.api.FxRobot; /** * Robot used to simulate user actions on the GUI. * Extends {@link FxRobot} by adding some customized functionality and workarounds. */ public class GuiRobot extends FxRobot { public GuiRobot push(KeyCodeCombination keyCodeCombination) { return (GuiRobot) super.push(TestUtil.scrub(keyCodeCombination)); } }
CS2103AUG2016-F09-C1/main
src/test/java/guitests/GuiRobot.java
Java
mit
472
package com.infinityraider.agricraft.util; import com.google.common.base.Preconditions; import com.infinityraider.agricraft.AgriCraft; import com.infinityraider.agricraft.api.v1.AgriApi; import com.infinityraider.agricraft.api.v1.crop.IAgriCrop; import com.infinityraider.agricraft.api.v1.crop.IAgriGrowthStage; import com.infinityraider.agricraft.api.v1.plant.IAgriPlant; import com.infinityraider.agricraft.api.v1.plant.IAgriWeed; import com.infinityraider.agricraft.impl.v1.requirement.RequirementCache; import com.infinityraider.agricraft.impl.v1.stats.AgriStatRegistry; import com.infinityraider.agricraft.reference.AgriToolTips; import net.minecraft.block.BlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import javax.annotation.Nonnull; import java.util.function.Consumer; public class CropHelper { public static boolean rollForWeedAction(IAgriCrop crop) { if(AgriCraft.instance.getConfig().disableWeeds()) { return false; } World world = crop.world(); if(world == null) { return false; } if(crop.hasPlant()) { int resist = crop.getStats().getResistance(); int max = AgriStatRegistry.getInstance().resistanceStat().getMax(); // At 1 resist, 50/50 chance for weed growth tick // At 10 resist, 0% chance return world.getRandom().nextInt(max) >= (max + resist)/2; } return world.getRandom().nextBoolean(); } public static boolean checkGrowthSpace(IAgriCrop crop) { World world = crop.world(); if(world == null) { return false; } IAgriPlant plant = crop.getPlant(); IAgriGrowthStage stage = crop.getGrowthStage(); double height = plant.getPlantHeight(stage); while(height > 16) { int offset = ((int) height) / 16; BlockPos pos = crop.getPosition().up(offset); BlockState state = world.getBlockState(pos); if(!state.getBlock().isAir(state, world, pos)) { return false; } height -= 16; } return true; } public static void spawnWeeds(IAgriCrop crop) { World world = crop.world(); if(world == null) { return; } AgriApi.getWeedRegistry().stream() .filter(IAgriWeed::isWeed) .filter(weed -> world.getRandom().nextDouble() < weed.spawnChance(crop)) .findAny() .ifPresent(weed -> crop.setWeed(weed, weed.getInitialGrowthStage())); } public static void spreadWeeds(IAgriCrop crop) { if(AgriCraft.instance.getConfig().allowAggressiveWeeds() && crop.getWeeds().isAggressive()) { crop.streamNeighbours() .filter(IAgriCrop::isValid) .filter(nb -> !nb.hasWeeds()) .filter(CropHelper::rollForWeedAction) .forEach(nb -> nb.setWeed(crop.getWeeds(), crop.getWeeds().getInitialGrowthStage())); } } public static void executePlantHarvestRolls(IAgriCrop crop, @Nonnull Consumer<ItemStack> consumer) { World world = crop.world(); if(world == null) { return; } for (int trials = (crop.getStats().getGain() + 3) / 3; trials > 0; trials--) { crop.getPlant().getHarvestProducts(consumer, crop.getGrowthStage(), crop.getStats(), world.getRandom()); } } public static void addDisplayInfo(IAgriCrop crop, RequirementCache requirement, @Nonnull Consumer<ITextComponent> consumer) { // Validate Preconditions.checkNotNull(consumer); // Add plant information if (crop.hasPlant()) { //Add the plant data. consumer.accept(AgriToolTips.getPlantTooltip(crop.getPlant())); consumer.accept(AgriToolTips.getGrowthTooltip(crop.getGrowthStage(), crop.getGrowthPercentage())); //Add the stats crop.getStats().addTooltips(consumer); //Add the fertility information. requirement.addTooltip(consumer); } else { consumer.accept(AgriToolTips.NO_PLANT); } // Add weed information if(crop.hasWeeds()) { consumer.accept(AgriToolTips.getWeedTooltip(crop.getWeeds())); consumer.accept(AgriToolTips.getWeedGrowthTooltip(crop.getWeedGrowthPercentage())); } else { consumer.accept(AgriToolTips.NO_WEED); } // Add Soil Information crop.getSoil().map(soil -> { consumer.accept(AgriToolTips.getSoilTooltip(soil)); return true; }).orElseGet(() -> { consumer.accept(AgriToolTips.getUnknownTooltip(AgriToolTips.SOIL)); return false; }); } }
InfinityRaider/AgriCraft
src/main/java/com/infinityraider/agricraft/util/CropHelper.java
Java
mit
4,957
import java.io.*; import java.io.IOException; import java.net.URI; import java.lang.Integer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; //White, Tom (2012-05-10). Hadoop: The Definitive Guide (Kindle Locations 5375-5384). OReilly Media - A. Kindle Edition. public class HadoopGenerateFull { public static void main( String[] args) throws IOException { if (args.length !=2) { System.err.println("Usage: HadoopGenerateFull <number of bits> <output filename>."); System.exit(2); } int limit; int numBits = Integer.parseInt(args[0]); if(numBits > 31){ limit = 0; //expecting integer overflow } else { limit = (1 << numBits); } System.err.println("Limit: "+limit); String uri = args[1]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create( uri), conf); Path path = new Path( uri); NullWritable key = NullWritable.get(); IntWritable value = new IntWritable(); SequenceFile.Writer writer = null; try { writer = SequenceFile.createWriter( fs, conf, path, key.getClass(), value.getClass()); int value_i = 0; do { value.set(value_i); //System.out.printf("[%s]\t%s\t%s\n", writer.getLength(), key, value); writer.append( key, value); value_i++; } while(value_i != limit); System.err.println("Done."); } finally { IOUtils.closeStream( writer); } } }
bkimmett/fuzzyjoin
utilities/HadoopGenerateFull.java
Java
mit
1,833
package xyz.enhorse.lfp.media; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * 01.07.2015. */ public class FilmTest { @Test public void testToString() throws Exception { Film film = new Film("бэклит"); assertEquals("Media {бэклит (бэклит)}", film.toString()); film = new Film("глбеклит"); assertEquals("Media {глянцевый бэклит (глянцбэклит)}", film.toString()); film = new Film("СБРФ(267)4-560х1170_матбэклит"); assertEquals("Media {матовый бэклит (матбэклит)}", film.toString()); } }
enhorse/LFP-parser
src/test/java/xyz/enhorse/lfp/media/FilmTest.java
Java
mit
666
package sk.stuba.fiit.perconik.ivda.server.processes; import com.google.common.collect.ImmutableMap; import junit.framework.TestCase; import sk.stuba.fiit.perconik.ivda.activity.dto.EventDto; import sk.stuba.fiit.perconik.ivda.server.BankOfChunks; import sk.stuba.fiit.perconik.ivda.util.Configuration; import sk.stuba.fiit.perconik.ivda.util.lang.DateUtils; import sk.stuba.fiit.perconik.ivda.util.lang.GZIP; import java.io.File; import java.util.Date; import java.util.Iterator; public class PairingProcessesTest extends TestCase { private static final File processesFile = new File(Configuration.CONFIG_DIR, "processes.gzip"); /** * Tento test spusti funkcionality PairingProcessesTest, nasledne vytiahne procesy pre pouzivatela a ulozi ich. * * @throws Exception */ public void testProccessItem() throws Exception { Configuration.getInstance(); Date start = DateUtils.fromString("2010-01-01T00:00:00.000Z"); Date end = DateUtils.fromString("2020-11-09T00:00:00.000Z"); Iterator<EventDto> it = BankOfChunks.getEvents(start, end); PairingProcesses p = new PairingProcesses(); p.proccess(it); //p.printInfo(); p.clearAllUnfinished(); ImmutableMap<String, PerUserProcesses> map = p.getUserMapping(); GZIP.serialize(map, processesFile); } }
sekys/ivda
test/sk/stuba/fiit/perconik/ivda/server/processes/PairingProcessesTest.java
Java
mit
1,363
package hw.hw5; public class PERatioAnalyst extends AnalystDecorator { public PERatioAnalyst(StockAnalyst component) { super(component); } public String reasons() { return getComponent().reasons() + " and PERatio Analyzed"; } public double confidenceLevel() { return (getComponent().confidenceLevel() + priceEarningsConfidenceLevel()) / 2; } private double priceEarningsConfidenceLevel() { double cl = priceEarningsRatio() / 24; if (cl < .25) { cl = .25; } // If confidence level is below 25%, set it to 25% if (cl > .75) { cl = .75; } // If confidence level is above 75%, set it to 75% return cl; } private double priceEarningsRatio() { return Double.parseDouble(getComponent().getStockInfo().get("shareprice")) / Double.parseDouble(getComponent().getStockInfo().get("earnings")); } }
rootulp/school
ood/hw/src/hw/hw5/PERatioAnalyst.java
Java
mit
955
/* * commented and created at 22.12.2016 */ package de.m_bleil.java_api; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; import javafx.beans.Observable; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; /** * The Class ChangeListenerInspectionTest demonstrates the effect of reset value to old value using * a {@linkplain ChangeListener}. * * @author Marcus Bleil, www.m-bleil.de */ public class ChangeListenerInspectionTest { private StringProperty projectName; private StringProperty projectNameView; private AtomicInteger counterChangeListener; private AtomicInteger counterInvalidationListener; @Before public void setup() { projectName = new SimpleStringProperty("Project Java tutorial"); projectNameView = new SimpleStringProperty(projectName.get()); counterChangeListener = new AtomicInteger(); counterInvalidationListener = new AtomicInteger(); projectName.addListener((ObservableValue<? extends String> name, String oldName, String newName) -> { counterChangeListener.incrementAndGet(); if (newName == null || newName.length() == 0) { projectName.set(oldName); } }); projectName.addListener((Observable o) -> { counterInvalidationListener.incrementAndGet(); }); projectNameView.bindBidirectional(projectName); } @Test public void test_change_listener() { projectName.set(null); assertThat(counterChangeListener.get(), is(equalTo(2))); assertThat(counterInvalidationListener.get(), is(equalTo(2))); assertThat(projectName.get(), is(equalTo("Project Java tutorial"))); assertThat(projectNameView.get(), is(equalTo("Project Java tutorial"))); } @Test public void test_change_listener_1() { projectName.set(""); assertThat(counterChangeListener.get(), is(equalTo(2))); assertThat(counterInvalidationListener.get(), is(equalTo(2))); assertThat(projectName.get(), is(equalTo("Project Java tutorial"))); assertThat(projectNameView.get(), is(equalTo("Project Java tutorial"))); } @Test public void test_change_listener_2() { projectName.set("test"); assertThat(counterChangeListener.get(), is(equalTo(1))); assertThat(counterInvalidationListener.get(), is(equalTo(1))); assertThat(projectName.get(), is(equalTo("test"))); assertThat(projectNameView.get(), is(equalTo("test"))); } @Test public void test_change_listener_3() { projectName.set("test"); projectName.set("test"); assertThat(counterChangeListener.get(), is(equalTo(1))); assertThat(counterInvalidationListener.get(), is(equalTo(1))); assertThat(projectName.get(), is(equalTo("test"))); assertThat(projectNameView.get(), is(equalTo("test"))); } }
momolinus/tutorials
java/de/m_bleil/java_api/ChangeListenerInspectionTest.java
Java
mit
2,947
package com.mkl.eu.service.service.util; import com.mkl.eu.client.service.vo.enumeration.TerrainEnum; import com.mkl.eu.client.service.vo.enumeration.WarStatusEnum; import com.mkl.eu.client.service.vo.ref.Referential; import com.mkl.eu.client.service.vo.tables.Leader; import com.mkl.eu.client.service.vo.tables.Tables; import com.mkl.eu.service.service.persistence.oe.AbstractWithLossEntity; import com.mkl.eu.service.service.persistence.oe.GameEntity; import com.mkl.eu.service.service.persistence.oe.board.CounterEntity; import com.mkl.eu.service.service.persistence.oe.board.StackEntity; import com.mkl.eu.service.service.persistence.oe.country.PlayableCountryEntity; import com.mkl.eu.service.service.persistence.oe.diplo.WarEntity; import com.mkl.eu.service.service.persistence.oe.ref.province.AbstractProvinceEntity; import org.apache.commons.lang3.tuple.Pair; import java.util.List; import java.util.function.Predicate; import java.util.function.Supplier; /** * Utility for OE class. * * @author MKL. */ public interface IOEUtil { /** Mercantile countries that have a higher FTI/DTI. */ String[] MERCANTILE_COUNTRIES = new String[]{"danemark", "genes", "hollande", "portugal", "provincesne", "suede", "venise"}; /** * @param country whom we want the administrative value. * @return the administrative value of a country. */ int getAdministrativeValue(PlayableCountryEntity country); /** * @param country whom we want the diplomatic value. * @return the diplomatic value of a country. */ int getDiplomaticValue(PlayableCountryEntity country); /** * @param country whom we want the military value. * @return the military value of a country. */ int getMilitaryValue(PlayableCountryEntity country); /** * @param country whom we want the initiative. * @return the initiative of the country. */ int getInitiative(PlayableCountryEntity country); /** * @param country which we want the fti. * @param tables the tables (period is needed in the calculation). * @return the fti of the country, which can be minor, given the game (and so the period). */ int getFti(GameEntity game, Tables tables, String country); /** * @param country which we want the dti. * @param tables the tables (period is needed in the calculation). * @return the dti of the country, which can be minor, given the game (and so the period). */ int getDti(GameEntity game, Tables tables, String country); /** * @param game game containing all the counters. * @param country whom we want the stability. * @return the stability of a country. */ int getStability(GameEntity game, String country); /** * @param game game containing all the counters. * @param country whom we want the technology box. * @param land to wether we want the land or the naval technology advance. * @return the number of the box where the appropriate technology counter of the country is. */ int getTechnologyAdvance(GameEntity game, String country, boolean land); /** * @param province the province to settle. * @param discoveries the provinces that have been discovered. * @param sources the sources (COL/TP/Owned european province) of supply of the settlement. * @param friendlies the friendly terrains. * @return <code>true</code> if the province can be settled, <code>false</code> otherwise. */ boolean canSettle(AbstractProvinceEntity province, List<String> discoveries, List<String> sources, List<String> friendlies); /** * Rolls a die for a non identified country in the given game. * * @param game the game. * @return the result of a die 10. */ int rollDie(GameEntity game); /** * Rolls a die for a country in the given game. The country can ben <code>null</code> for general die roll. * * @param game the game. * @param country the country rolling the die. Can be <code>null</code>. * @return the result of a die 10. */ int rollDie(GameEntity game, String country); /** * Rolls a die for a country in the given game. The country can ben <code>null</code> for general die roll. * * @param game the game. * @param country the country rolling the die. Can be <code>null</code>. * @return the result of a die 10. */ int rollDie(GameEntity game, PlayableCountryEntity country); /** * Returns the stacks on the province for a given game. * The main purpose is to have the possibility to mock this method in tests. * * @param game the game. * @param province the province. * @return the stacks on the province. */ List<StackEntity> getStacksOnProvince(GameEntity game, String province); /** * @param game the game. * @param country the country. * @return the war status of the country. */ WarStatusEnum getWarStatus(GameEntity game, PlayableCountryEntity country); /** * @param country the country. * @param game the game. * @param includeInterventions flag to include enemy countries in limited or foreign intervention. * @return the list of country that are at war with the input country. */ List<String> getEnemies(PlayableCountryEntity country, GameEntity game, boolean includeInterventions); /** * @param stack the stack to check mobility. * @return <code>true</code> if the stack is mobile (can be moved), <code>false</code> otherwise. */ boolean isMobile(StackEntity stack); /** * @param provinceFrom origin. * @param provinceTo destination. * @param provinceToFriendly if the provinceTo is friendly (in case of doubt, it is not). * @return the move points needed to move from provinceFrom to provinceTo. If provinces * are not adjacent, returns -1. */ int getMovePoints(AbstractProvinceEntity provinceFrom, AbstractProvinceEntity provinceTo, boolean provinceToFriendly); /** * @param province the province. * @param game the game. * @return the name of the country owning the province. */ String getOwner(AbstractProvinceEntity province, GameEntity game); /** * @param province the province. * @param game the game. * @return the name of the country controlling the province. */ String getController(AbstractProvinceEntity province, GameEntity game); /** * @param country the country. * @param game the game. * @return the allies of the country (a country is considered allied to itself). */ List<String> getAllies(PlayableCountryEntity country, GameEntity game); /** * @param country the country. * @param game the game. * @return the enemies of the country. */ List<String> getEnemies(PlayableCountryEntity country, GameEntity game); /** * @param country the name of the country. * @param game the game. * @return the enemies of the country. */ List<String> getEnemies(String country, GameEntity game); /** * @param phasingCounters the counters of the phasing countries. * @param nonPhasingCounters the counters of the non phasing countries. * @param game the game. * @return the war related to this battle and a flag saying if the phasing side is the offensive side of the war. */ Pair<WarEntity, Boolean> searchWar(List<CounterEntity> phasingCounters, List<CounterEntity> nonPhasingCounters, GameEntity game); /** * @param country the country. * @param war the war. * @param offensive for the offensive side. * @return if the country is in the offensive side of the war. */ boolean isWarAlly(PlayableCountryEntity country, WarEntity war, boolean offensive); /** * @param war the war. * @param offensive to know if we want the offensive countries or the defensive ones. * @return the list of countries that are offensive or defensive. */ List<String> getWarFaction(WarEntity war, boolean offensive); /** * @param province the province. * @param game the game. * @return the natural level of the fortress of the province. */ int getNaturalFortressLevel(AbstractProvinceEntity province, GameEntity game); /** * @param province the province. * @param game the game. * @return the level of the fortress of the province. */ int getFortressLevel(AbstractProvinceEntity province, GameEntity game); /** * @param country the country. * @param land <code>true</code> if we want the land tech, naval tech otherwise. * @param referential the referential. * @param game the game. * @return the technology of the country. */ String getTechnology(String country, boolean land, Referential referential, GameEntity game); /** * @param counters stack whom we want the technology. * @param land <code>true</code> if we want the land tech, naval tech otherwise. * @param referential the referential. * @param tables the tables. * @param game the game. * @return the technology of a List of counters. */ String getTechnology(List<CounterEntity> counters, boolean land, Referential referential, Tables tables, GameEntity game); /** * @param counters stack whom we want the artillery bonus. * @param referential the referential. * @param tables the tables. * @param game the game. * @return the artillery bonus of a List of counters for siege and artillery fire modifier. */ int getArtilleryBonus(List<CounterEntity> counters, Referential referential, Tables tables, GameEntity game); /** * @param counters stack whom we want additional information. * @param referential the referential. * @return a List of ArmyInfo that holds additional information over the counters. */ List<ArmyInfo> getArmyInfo(List<CounterEntity> counters, Referential referential); /** * @param counters stack whom we want the artillery bonus. * @param tables the tables. * @param game the game. * @return the artillery bonus of a List of counters for siege and artillery fire modifier. */ int getArtilleryBonus(List<ArmyInfo> counters, Tables tables, GameEntity game); /** * @param counters stack whom we want the cavalry bonus. * @param terrain the terrain where the battle occurs. * @param tables the tables. * @param game the game. * @return <code>true</code> if the stack has a cavalry bonus in this terrain and turn. */ boolean getCavalryBonus(List<ArmyInfo> counters, TerrainEnum terrain, Tables tables, GameEntity game); /** * @param counters stack whom we want the assault bonus. * @param tables the tables. * @param game the game. * @return <code>true</code> if the stack has an assault bonus. */ boolean getAssaultBonus(List<CounterEntity> counters, Tables tables, GameEntity game); /** * @param province to retreat. * @param inFortress to know if the stack will hide in fortress. * @param stackSize size of the stack in case of hiding in the fortress. * @param country doing the retreat. * @param game the game. * @return <code>true</code> if the country can retreat in the province. */ boolean canRetreat(AbstractProvinceEntity province, boolean inFortress, double stackSize, PlayableCountryEntity country, GameEntity game); /** * @param counters the stack of counters. * @return <code>true</code> if the stack is veteran. */ boolean isStackVeteran(List<CounterEntity> counters); /** * @param losses initial losses. * @param sizeDiff size differential between the stacks. * @return the loss after size computation. */ AbstractWithLossEntity lossModificationSize(AbstractWithLossEntity losses, Integer sizeDiff); /** * @param counters of the stack. * @param tables the tables. * @param game the game. * @return the size of the stack for size comparison rules. */ Double getArmySize(List<ArmyInfo> counters, Tables tables, GameEntity game); /** * @param sizeFor size of the current stack. * @param sizeAgainst size of the opposing stack. * @return the size diff that the current stacks has over the opposing one. */ Integer getSizeDiff(Double sizeFor, Double sizeAgainst); /** * @param size of the stack. * @param land if it is a land battle. * @param rollDie for special case. If <code>null</code> then worst case happens. * @return the losses mitigation of the stack at the end of the battle because of its small size. */ AbstractWithLossEntity lossesMitigation(Double size, boolean land, Supplier<Integer> rollDie); /** * @param modifiedRollDie the modified die roll. Can be lower than <code>0</code>. * @return the losses of the retreat. */ AbstractWithLossEntity retreat(Integer modifiedRollDie); /** * @param country the country. * @param game the game. * @return the prosperity of the country: -1 for anti prosperous, +1 for prosperous, 0 for neither. */ int getProsperity(PlayableCountryEntity country, GameEntity game); /** * @param game the game. * @return the province box where the inflation box is. */ String getInflationBox(GameEntity game); /** * @param inflation the actual inflation. * @param country the country. * @param tables the tables. * @param game the game. * @return the minimal inflation lost at the end of the turn. */ int getMinimalInflation(int inflation, String country, Tables tables, GameEntity game); /** * @param stack the stack. * @return the country that should control this stack given the counters. In case of tie, choose a random one. */ String getController(StackEntity stack); /** * @param stack the stack. * @param tables the tables. * @param conditions the conditions on the leader (general for land, etc...). * @return the leader that should lead this stack given the counters. In case of tie, choose a random one. */ String getLeader(StackEntity stack, Tables tables, Predicate<Leader> conditions); /** * @param counters the counters. * @return the country that is naturally leading this counters (if tie, all eligible countries are returned). */ List<String> getLeadingCountries(List<CounterEntity> counters); /** * @param counters the counters. * @param tables the tables. * @param conditions the conditions on the leader (general for land, etc...). * @return the leader that will naturally lead this counters (if tie, all eligible leaders are returned). */ List<Leader> getLeaders(List<CounterEntity> counters, Tables tables, Predicate<Leader> conditions); }
FogiaFr/eu
service/eu-service-service/src/main/java/com/mkl/eu/service/service/util/IOEUtil.java
Java
mit
15,328
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.frontdoor.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for Transform. */ public final class Transform extends ExpandableStringEnum<Transform> { /** Static value Lowercase for Transform. */ public static final Transform LOWERCASE = fromString("Lowercase"); /** Static value Uppercase for Transform. */ public static final Transform UPPERCASE = fromString("Uppercase"); /** Static value Trim for Transform. */ public static final Transform TRIM = fromString("Trim"); /** Static value UrlDecode for Transform. */ public static final Transform URL_DECODE = fromString("UrlDecode"); /** Static value UrlEncode for Transform. */ public static final Transform URL_ENCODE = fromString("UrlEncode"); /** Static value RemoveNulls for Transform. */ public static final Transform REMOVE_NULLS = fromString("RemoveNulls"); /** * Creates or finds a Transform from its string representation. * * @param name a name to look for. * @return the corresponding Transform. */ @JsonCreator public static Transform fromString(String name) { return fromString(name, Transform.class); } /** @return known Transform values. */ public static Collection<Transform> values() { return values(Transform.class); } }
Azure/azure-sdk-for-java
sdk/frontdoor/azure-resourcemanager-frontdoor/src/main/java/com/azure/resourcemanager/frontdoor/models/Transform.java
Java
mit
1,614
package com.knowladgeduty.service; import com.knowladgeduty.model.Regulations; public interface RegulationsService extends AbstractService<Regulations,Long> { }
kogceweb/knowledgeduty
src/main/java/com/knowladgeduty/service/RegulationsService.java
Java
mit
164