text
stringlengths
7
1.01M
/* * Copyright (c) 2017 Livio, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Livio Inc. nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.smartdevicelink.streaming.video; import android.annotation.TargetApi; import android.app.Presentation; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.smartdevicelink.util.DebugTool; import java.lang.reflect.Constructor; import java.util.concurrent.Callable; /** * SdlRemoteDisplay is an abstract class that should be extended by developers to create their remote displays. * All logic for UI events can be stored in their extension. * * <br><br> <b>NOTE:</b> When the UI changes (buttons appear, layouts change, etc) the developer should call {@link #invalidate()} to alert any * other interfaces that are listening for those types of events. */ @TargetApi(17) public abstract class SdlRemoteDisplay extends Presentation { private static final String TAG = "SdlRemoteDisplay"; private static final int REFRESH_RATE_MS = 50; protected Window w; protected View mainView; protected final Handler handler = new Handler(); protected final Handler uiHandler = new Handler(Looper.getMainLooper()); protected Callback callback; public SdlRemoteDisplay(Context context, Display display) { super(context, display); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(TAG); w = getWindow(); startRefreshTask(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { w.setType(WindowManager.LayoutParams.TYPE_PRIVATE_PRESENTATION); } } protected void startRefreshTask() { handler.postDelayed(mStartRefreshTaskCallback, REFRESH_RATE_MS); } protected void stopRefreshTask() { handler.removeCallbacks(mStartRefreshTaskCallback); } protected final Runnable mStartRefreshTaskCallback = new Runnable() { public void run() { if (mainView == null) { mainView = w.getDecorView().findViewById(android.R.id.content); } if (mainView != null) { mainView.invalidate(); } handler.postDelayed(this, REFRESH_RATE_MS); } }; public View getMainView() { if (mainView == null) { mainView = w.getDecorView().findViewById(android.R.id.content); } return this.mainView; } public void invalidate() { // let listeners know the view has been invalidated if (callback != null) { callback.onInvalidated(this); } } public void handleMotionEvent(final MotionEvent motionEvent) { uiHandler.post(new Runnable() { @Override public void run() { mainView.dispatchTouchEvent(motionEvent); } }); } public void stop() { stopRefreshTask(); dismissPresentation(); } public void dismissPresentation() { uiHandler.post(new Runnable() { @Override public void run() { dismiss(); } }); } public interface Callback { void onCreated(SdlRemoteDisplay remoteDisplay); void onInvalidated(SdlRemoteDisplay remoteDisplay); } public static class Creator implements Callable<Boolean> { private final Context context; private final Display mDisplay; boolean presentationShowError = false; SdlRemoteDisplay remoteDisplay; final Class<? extends SdlRemoteDisplay> remoteDisplayClass; private final Handler uiHandler = new Handler(Looper.getMainLooper()); private final Callback callback; public Creator(Context context, Display display, SdlRemoteDisplay remoteDisplay, Class<? extends SdlRemoteDisplay> remoteDisplayClass, Callback callback) { this.context = context; this.mDisplay = display; this.remoteDisplay = remoteDisplay; this.remoteDisplayClass = remoteDisplayClass; this.callback = callback; } @Override public Boolean call() { uiHandler.post(new Runnable() { @Override public void run() { // Want to create presentation on UI thread so it finds the right Looper // when setting up the Dialog. if ((mDisplay != null) && (remoteDisplay == null || remoteDisplay.getDisplay() != mDisplay)) { try { Constructor constructor = remoteDisplayClass.getConstructor(Context.class, Display.class); remoteDisplay = (SdlRemoteDisplay) constructor.newInstance(context, mDisplay); } catch (Exception e) { e.printStackTrace(); DebugTool.logError(TAG, "Unable to create Presentation Class"); presentationShowError = true; return; } try { remoteDisplay.show(); remoteDisplay.callback = callback; if (callback != null) { callback.onCreated(remoteDisplay); } } catch (WindowManager.InvalidDisplayException ex) { DebugTool.logError(TAG, "Couldn't show presentation! Display was removed in the meantime.", ex); remoteDisplay = null; presentationShowError = true; } } } }); return presentationShowError; } } }
package de.beachboys.aoc2021; import de.beachboys.Day; import de.beachboys.DayTest; import de.beachboys.IOHelper; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.List; import java.util.stream.Stream; public class Day14Test extends DayTest { private final Day day = new Day14(); private static Stream<Arguments> provideTestDataForPart1() { return Stream.of( Arguments.of(List.of("NNCB", "", "CH -> B", "HH -> N", "CB -> H", "NH -> C", "HB -> C", "HC -> B", "HN -> C", "NN -> C", "BH -> H", "NC -> B", "NB -> B", "BN -> B", "BB -> N", "BC -> B", "CC -> N", "CN -> C"), 1588, null) ); } private static Stream<Arguments> provideTestDataForPart2() { return Stream.of( Arguments.of(List.of("NNCB", "", "CH -> B", "HH -> N", "CB -> H", "NH -> C", "HB -> C", "HC -> B", "HN -> C", "NN -> C", "BH -> H", "NC -> B", "NB -> B", "BN -> B", "BB -> N", "BC -> B", "CC -> N", "CN -> C"), 2188189693529L, null) ); } @ParameterizedTest @MethodSource("provideTestDataForPart1") public void testPart1(List<String> input, Object expected, IOHelper io) { testPart1(this.day, input, expected, io); } @ParameterizedTest @MethodSource("provideTestDataForPart2") public void testPart2(List<String> input, Object expected, IOHelper io) { testPart2(this.day, input, expected, io); } }
package JAVA_Design_Model_Iterator; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Collection collection = new MyCollection(); Iterator It = collection.iterator(); while(It.hasNext()){ System.out.println(It.next()); } } }
/* * This Java source file was generated by the Gradle 'init' task. */ package basiclibrary; import org.junit.Test; import static org.junit.Assert.*; public class LibraryTest { @Test public void testSomeLibraryMethod() { Library classUnderTest = new Library(); assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod()); } }
import java.io.* ; import java_cup.runtime.Symbol; public class XmlScan { public static void main(String arg[]) throws IOException { Yylex yy ; if (arg.length > 0) yy = new Yylex(new BufferedReader(new FileReader(arg[0]))) ; else yy = new Yylex(new BufferedReader(new InputStreamReader(System.in))) ; Symbol symb = yy.next_token(); while (symb.sym != sym.EOF){ if (symb.sym == sym.LT) { symb = yy.next_token(); if (symb.sym == sym.NAME) { System.out.println("Start element: "+symb.value); do { yy.yybegin(yy.ATTRIBUTE); symb = yy.next_token(); if(symb.sym == sym.ATTRIBUT) { System.out.println("Attribut : "+ symb.value); } } while ((symb.sym != sym.SLASHGT) && (symb.sym != sym.GT)); if (symb.sym == sym.SLASHGT) { System.out.println("End element"); } else { yy.yybegin(yy.INELEMENT); symb = yy.next_token(); if(symb.sym == sym.CONTENT && symb.value != null) { System.out.println("Contenue : "+symb.value); } } } } else if (symb.sym == sym.LTSLASH) { symb = yy.next_token(); if (symb.sym == sym.NAME) { System.out.println("End element: "+symb.value); do { symb = yy.next_token(); } while (symb.sym != sym.GT); } } else { symb = yy.next_token(); yy.yybegin(yy.YYINITIAL); } //System.out.println(yy.yystate()); } System.out.println("End of scanning"); } }
package com.peregud.travelhistoryrest.util; import com.peregud.travelhistoryrest.exception.PaginationException; import org.springframework.http.HttpStatus; import static com.peregud.travelhistoryrest.util.AppConstants.*; public class PageUtil { public static void validatePageNumberAndSize(int page, int size) { if (page < 0) { throw new PaginationException(HttpStatus.BAD_REQUEST, ERROR_NEGATIVE_PAGE); } if (size < 0) { throw new PaginationException(HttpStatus.BAD_REQUEST, ERROR_NEGATIVE_SIZE); } if (size > MAX_PAGE_SIZE) { throw new PaginationException(HttpStatus.BAD_REQUEST, ERROR_OVERSIZE + MAX_PAGE_SIZE); } } }
package slimeknights.tconstruct.tools.modifiers.traits; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerEvent; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.traits.AbstractTrait; import slimeknights.tconstruct.library.utils.ToolHelper; import slimeknights.tconstruct.tools.potion.TinkerPotion; public class TraitMomentum extends AbstractTrait { public static final TinkerPotion Momentum = new TinkerPotion(Util.getResource("momentum"), false, false); public TraitMomentum() { super("momentum", EnumChatFormatting.BLUE); } @Override public void miningSpeed(ItemStack tool, PlayerEvent.BreakSpeed event) { float boost = Momentum.getLevel(event.entityPlayer); boost /= 80f; // 40% boost max event.newSpeed += event.originalSpeed * boost; } @Override public void afterBlockBreak(ItemStack tool, World world, Block block, BlockPos pos, EntityLivingBase player, boolean wasEffective) { int level = 1; level += Momentum.getLevel(player); level = Math.min(32, level); int duration = (int) ((10f / ToolHelper.getMiningSpeed(tool)) * 1.5f * 20f); Momentum.apply(player, duration, level); } }
package examples.java11; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Predicate; public class LocalVariableSyntax { public static void main(String[] args) { var text = "Banana"; // Incompatible types: // text = 1; // Cannot infer type: // var a; // var nothing = null; // var bla = () -> System.out.println("Hallo"); // var method = LocalVariableSyntax::someMethod; var list1 = new ArrayList<>(); // ArrayList<Object> var list2 = new ArrayList<Map<String, List<Integer>>>(); for (var current : list2) { // current is of type: Map<String, List<Integer>> System.out.println(current); } Predicate<String> predicate1 = (@Deprecated var a) -> false; } void someMethod() {} }
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.ast; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.impl.Constant; import org.eclipse.jdt.internal.compiler.lookup.*; /** * Syntactic representation of a reference to a generic type. * Note that it might also have a dimension. */ public class ParameterizedQualifiedTypeReference extends ArrayQualifiedTypeReference { public TypeReference[][] typeArguments; /** * @param tokens * @param dim * @param positions */ public ParameterizedQualifiedTypeReference(char[][] tokens, TypeReference[][] typeArguments, int dim, long[] positions) { super(tokens, dim, positions); this.typeArguments = typeArguments; } public void checkBounds(Scope scope) { if (this.resolvedType == null) return; checkBounds( (ReferenceBinding) this.resolvedType.leafComponentType(), scope, this.typeArguments.length - 1); } public void checkBounds(ReferenceBinding type, Scope scope, int index) { // recurse on enclosing type if any, and assuming explictly part of the reference (index>0) if (index > 0 && type.enclosingType() != null) { checkBounds(type.enclosingType(), scope, index - 1); } if (type.isParameterizedTypeWithActualArguments()) { ParameterizedTypeBinding parameterizedType = (ParameterizedTypeBinding) type; ReferenceBinding currentType = parameterizedType.genericType(); TypeVariableBinding[] typeVariables = currentType.typeVariables(); if (typeVariables != null) { // argTypes may be null in error cases parameterizedType.boundCheck(scope, this.typeArguments[index]); } } } public TypeReference copyDims(int dim){ return new ParameterizedQualifiedTypeReference(this.tokens, this.typeArguments, dim, this.sourcePositions); } /** * @return char[][] */ public char [][] getParameterizedTypeName(){ int length = this.tokens.length; char[][] qParamName = new char[length][]; for (int i = 0; i < length; i++) { TypeReference[] arguments = this.typeArguments[i]; if (arguments == null) { qParamName[i] = this.tokens[i]; } else { StringBuffer buffer = new StringBuffer(5); buffer.append(this.tokens[i]); buffer.append('<'); for (int j = 0, argLength =arguments.length; j < argLength; j++) { if (j > 0) buffer.append(','); buffer.append(CharOperation.concatWith(arguments[j].getParameterizedTypeName(), '.')); } buffer.append('>'); int nameLength = buffer.length(); qParamName[i] = new char[nameLength]; buffer.getChars(0, nameLength, qParamName[i], 0); } } int dim = this.dimensions; if (dim > 0) { char[] dimChars = new char[dim*2]; for (int i = 0; i < dim; i++) { int index = i*2; dimChars[index] = '['; dimChars[index+1] = ']'; } qParamName[length-1] = CharOperation.concat(qParamName[length-1], dimChars); } return qParamName; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference#getTypeBinding(org.eclipse.jdt.internal.compiler.lookup.Scope) */ protected TypeBinding getTypeBinding(Scope scope) { return null; // not supported here - combined with resolveType(...) } /* * No need to check for reference to raw type per construction */ private TypeBinding internalResolveType(Scope scope, boolean checkBounds) { // handle the error here this.constant = Constant.NotAConstant; if ((this.bits & ASTNode.DidResolve) != 0) { // is a shared type reference which was already resolved if (this.resolvedType != null) { // is a shared type reference which was already resolved if (this.resolvedType != null) { // is a shared type reference which was already resolved if (this.resolvedType.isValidBinding()) { return this.resolvedType; } else { switch (this.resolvedType.problemId()) { case ProblemReasons.NotFound : case ProblemReasons.NotVisible : case ProblemReasons.InheritedNameHidesEnclosingName : TypeBinding type = this.resolvedType.closestMatch(); return type; default : return null; } } } } } this.bits |= ASTNode.DidResolve; boolean isClassScope = scope.kind == Scope.CLASS_SCOPE; Binding binding = scope.getPackage(this.tokens); if (binding != null && !binding.isValidBinding()) { this.resolvedType = (ReferenceBinding) binding; reportInvalidType(scope); // be resilient, still attempt resolving arguments for (int i = 0, max = this.tokens.length; i < max; i++) { TypeReference[] args = this.typeArguments[i]; if (args != null) { int argLength = args.length; for (int j = 0; j < argLength; j++) { TypeReference typeArgument = args[j]; if (isClassScope) { typeArgument.resolveType((ClassScope) scope); } else { typeArgument.resolveType((BlockScope) scope, checkBounds); } } } } return null; } PackageBinding packageBinding = binding == null ? null : (PackageBinding) binding; boolean typeIsConsistent = true; ReferenceBinding qualifyingType = null; for (int i = packageBinding == null ? 0 : packageBinding.compoundName.length, max = this.tokens.length; i < max; i++) { findNextTypeBinding(i, scope, packageBinding); if (!(this.resolvedType.isValidBinding())) { reportInvalidType(scope); // be resilient, still attempt resolving arguments for (int j = i; j < max; j++) { TypeReference[] args = this.typeArguments[j]; if (args != null) { int argLength = args.length; for (int k = 0; k < argLength; k++) { TypeReference typeArgument = args[k]; if (isClassScope) { typeArgument.resolveType((ClassScope) scope); } else { typeArgument.resolveType((BlockScope) scope); } } } } return null; } ReferenceBinding currentType = (ReferenceBinding) this.resolvedType; if (qualifyingType == null) { qualifyingType = currentType.enclosingType(); // if member type if (qualifyingType != null) { qualifyingType = currentType.isStatic() ? (ReferenceBinding) scope.environment().convertToRawType(qualifyingType, false /*do not force conversion of enclosing types*/) : scope.environment().convertToParameterizedType(qualifyingType); } } else { if (typeIsConsistent && currentType.isStatic() && (qualifyingType.isParameterizedTypeWithActualArguments() || qualifyingType.isGenericType())) { scope.problemReporter().staticMemberOfParameterizedType(this, scope.environment().createParameterizedType((ReferenceBinding)currentType.erasure(), null, qualifyingType)); typeIsConsistent = false; } ReferenceBinding enclosingType = currentType.enclosingType(); if (enclosingType != null && enclosingType.erasure() != qualifyingType.erasure()) { // qualifier != declaring/enclosing qualifyingType = enclosingType; // inherited member type, leave it associated with its enclosing rather than subtype } } // check generic and arity TypeReference[] args = this.typeArguments[i]; if (args != null) { TypeReference keep = null; if (isClassScope) { keep = ((ClassScope) scope).superTypeReference; ((ClassScope) scope).superTypeReference = null; } int argLength = args.length; TypeBinding[] argTypes = new TypeBinding[argLength]; boolean argHasError = false; ReferenceBinding currentOriginal = (ReferenceBinding)currentType.original(); for (int j = 0; j < argLength; j++) { TypeReference arg = args[j]; TypeBinding argType = isClassScope ? arg.resolveTypeArgument((ClassScope) scope, currentOriginal, j) : arg.resolveTypeArgument((BlockScope) scope, currentOriginal, j); if (argType == null) { argHasError = true; } else { argTypes[j] = argType; } } if (argHasError) { return null; } if (isClassScope) { ((ClassScope) scope).superTypeReference = keep; if (((ClassScope) scope).detectHierarchyCycle(currentOriginal, this)) return null; } TypeVariableBinding[] typeVariables = currentOriginal.typeVariables(); if (typeVariables == Binding.NO_TYPE_VARIABLES) { // check generic if (scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) { // below 1.5, already reported as syntax error scope.problemReporter().nonGenericTypeCannotBeParameterized(i, this, currentType, argTypes); return null; } this.resolvedType = (qualifyingType != null && qualifyingType.isParameterizedType()) ? scope.environment().createParameterizedType(currentOriginal, null, qualifyingType) : currentType; if (this.dimensions > 0) { if (this.dimensions > 255) scope.problemReporter().tooManyDimensions(this); this.resolvedType = scope.createArrayType(this.resolvedType, this.dimensions); } return this.resolvedType; } else if (argLength != typeVariables.length) { // check arity scope.problemReporter().incorrectArityForParameterizedType(this, currentType, argTypes); return null; } // check parameterizing non-static member type of raw type if (typeIsConsistent && !currentType.isStatic()) { ReferenceBinding actualEnclosing = currentType.enclosingType(); if (actualEnclosing != null && actualEnclosing.isRawType()) { scope.problemReporter().rawMemberTypeCannotBeParameterized( this, scope.environment().createRawType(currentOriginal, actualEnclosing), argTypes); typeIsConsistent = false; } } ParameterizedTypeBinding parameterizedType = scope.environment().createParameterizedType(currentOriginal, argTypes, qualifyingType); // check argument type compatibility if (checkBounds) // otherwise will do it in Scope.connectTypeVariables() or generic method resolution parameterizedType.boundCheck(scope, args); qualifyingType = parameterizedType; } else { ReferenceBinding currentOriginal = (ReferenceBinding)currentType.original(); if (isClassScope) if (((ClassScope) scope).detectHierarchyCycle(currentOriginal, this)) return null; if (currentOriginal.isGenericType()) { if (typeIsConsistent && qualifyingType != null && qualifyingType.isParameterizedType()) { scope.problemReporter().parameterizedMemberTypeMissingArguments(this, scope.environment().createParameterizedType(currentOriginal, null, qualifyingType)); typeIsConsistent = false; } qualifyingType = scope.environment().createRawType(currentOriginal, qualifyingType); // raw type } else { qualifyingType = (qualifyingType != null && qualifyingType.isParameterizedType()) ? scope.environment().createParameterizedType(currentOriginal, null, qualifyingType) : currentType; } } if (isTypeUseDeprecated(qualifyingType, scope)) reportDeprecatedType(qualifyingType, scope); this.resolvedType = qualifyingType; } // array type ? if (this.dimensions > 0) { if (this.dimensions > 255) scope.problemReporter().tooManyDimensions(this); this.resolvedType = scope.createArrayType(this.resolvedType, this.dimensions); } return this.resolvedType; } public StringBuffer printExpression(int indent, StringBuffer output) { int length = this.tokens.length; for (int i = 0; i < length - 1; i++) { output.append(this.tokens[i]); TypeReference[] typeArgument = this.typeArguments[i]; if (typeArgument != null) { output.append('<'); int max = typeArgument.length - 1; for (int j = 0; j < max; j++) { typeArgument[j].print(0, output); output.append(", ");//$NON-NLS-1$ } typeArgument[max].print(0, output); output.append('>'); } output.append('.'); } output.append(this.tokens[length - 1]); TypeReference[] typeArgument = this.typeArguments[length - 1]; if (typeArgument != null) { output.append('<'); int max = typeArgument.length - 1; for (int j = 0; j < max; j++) { typeArgument[j].print(0, output); output.append(", ");//$NON-NLS-1$ } typeArgument[max].print(0, output); output.append('>'); } if ((this.bits & IsVarArgs) != 0) { for (int i= 0 ; i < this.dimensions - 1; i++) { output.append("[]"); //$NON-NLS-1$ } output.append("..."); //$NON-NLS-1$ } else { for (int i= 0 ; i < this.dimensions; i++) { output.append("[]"); //$NON-NLS-1$ } } return output; } public TypeBinding resolveType(BlockScope scope, boolean checkBounds) { return internalResolveType(scope, checkBounds); } public TypeBinding resolveType(ClassScope scope) { return internalResolveType(scope, false); } public void traverse(ASTVisitor visitor, BlockScope scope) { if (visitor.visit(this, scope)) { for (int i = 0, max = this.typeArguments.length; i < max; i++) { if (this.typeArguments[i] != null) { for (int j = 0, max2 = this.typeArguments[i].length; j < max2; j++) { this.typeArguments[i][j].traverse(visitor, scope); } } } } visitor.endVisit(this, scope); } public void traverse(ASTVisitor visitor, ClassScope scope) { if (visitor.visit(this, scope)) { for (int i = 0, max = this.typeArguments.length; i < max; i++) { if (this.typeArguments[i] != null) { for (int j = 0, max2 = this.typeArguments[i].length; j < max2; j++) { this.typeArguments[i][j].traverse(visitor, scope); } } } } visitor.endVisit(this, scope); } }
package com.github.nija123098.configurationcodeloader.reader; import com.github.nija123098.configurationcodeloader.util.ConfigurationCodeLoaderException; import com.github.nija123098.configurationcodeloader.util.ConfigurationResults; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * A {@link ConfigurationReader} instance for reading configuration values * from member fields of instances or static fields of classes. * <p> * This class if built without concept of unsetting configuration values * as a class definition's fields are constant over the lifetime of the definition. * * @param <C> the base type of any variables produced by this class. * Only guaranteed as long as the {@link Class} configured as the source and {@link Predicate<Field>} * only results in fields who's variable values only are this type. */ public class VariableConfigurationReader<C> extends ReloadRequiredConfigurationReader<C> { /** * A dedicated annotation to put on {@link Field}s * in order to indicate that they should be used as configuration data. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Configuration { } /** * The default {@link Predicate<Field>} to decide what fields should be used for getting configuration data. * <p> * Filters for any fields with the {@link Configuration} annotation. */ private static final Predicate<Field> DEFAULT_FIELD_FILTER = field -> field.isAnnotationPresent(Configuration.class); /** * The object to get the value from if a member field, * null if reading should occur from a static field. */ private final Object sourceObject; /** * The list of fields to read. */ private final List<Field> fields; /** * Read configuration data from the provided {@link Class} * using the {@link VariableConfigurationReader#DEFAULT_FIELD_FILTER}. * * @param clazz the class to read configuration data from. */ public VariableConfigurationReader(Class<?> clazz) { this(clazz, null); } /** * Read configuration data from the provided variable from the type {@link Class} * using the {@link VariableConfigurationReader#DEFAULT_FIELD_FILTER}. * * @param clazz the class to read configuration data from. * @param sourceObject the object to get associated values from member fields. * @param <S> the type of the provided class. */ public <S> VariableConfigurationReader(Class<S> clazz, S sourceObject) { this(clazz, sourceObject, null); } /** * Read configuration data from the provided variable from the type {@link Class} * using the provided {@link Predicate<Field>} to filter which fields should provide configuration data. * * @param clazz the class to read configuration data from. * @param sourceObject the object to get associated values from member fields. * @param fieldFilter the filter to decide if a field should be used to provide configuration data. * @param <S> the type of the provided class. */ public <S> VariableConfigurationReader(Class<S> clazz, S sourceObject, Predicate<Field> fieldFilter) { this.sourceObject = sourceObject; this.fields = Stream.of(clazz.getDeclaredFields()) .filter(fieldFilter == null ? DEFAULT_FIELD_FILTER : fieldFilter) .collect(Collectors.toList()); } @SuppressWarnings("unchecked")// The specifier of the class must guarantee that variables are of type C @Override public ConfigurationResults<C> readValues() { ConfigurationResults<C> map = new ConfigurationResults<>(this.fields.size() + 1, 1); this.fields.forEach(field -> { try { map.put(field.getName(), (Optional<C>) Optional.ofNullable(field.get(this.sourceObject))); } catch (IllegalAccessException e) { throw new ConfigurationCodeLoaderException("Configuration variable not accessible: \"" + field.getDeclaringClass() + "#" + field.getName() + "\"", e); } }); return map; } }
/* Copyright 1995-2015 Esri 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. For additional information, contact: Environmental Systems Research Institute, Inc. Attn: Contracts Dept 380 New York Street Redlands, California, USA 92373 email: contracts@esri.com */ package com.esri.core.geometry; //This is a stub class OperatorGeodeticDensifyLocal extends OperatorGeodeticDensifyByLength { @Override public GeometryCursor execute(GeometryCursor geoms, double maxSegmentLengthMeters, SpatialReference sr, int curveType, ProgressTracker progressTracker) { throw new GeometryException("not implemented"); } @Override public Geometry execute(Geometry geom, double maxSegmentLengthMeters, SpatialReference sr, int curveType, ProgressTracker progressTracker) { throw new GeometryException("not implemented"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.hippo4j.common.model; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * Global remote pool info. */ @Getter @Setter public class GlobalRemotePoolInfo implements Serializable { private static final long serialVersionUID = 5447003335557127308L; /** * tenantId */ private String tenantId; /** * itemId */ private String itemId; /** * tpId */ private String tpId; /** * coreSize */ private Integer coreSize; /** * maxSize */ private Integer maxSize; /** * queueType */ private Integer queueType; /** * capacity */ private Integer capacity; /** * keepAliveTime */ private Integer keepAliveTime; /** * isAlarm */ private Integer isAlarm; /** * capacityAlarm */ private Integer capacityAlarm; /** * livenessAlarm */ private Integer livenessAlarm; /** * md5 */ private String md5; /** * content */ private String content; }
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-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.sakaiproject.calendar.api; import java.util.Collection; import java.util.List; import org.sakaiproject.calendar.api.CalendarEvent.EventAccess; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.javax.Filter; import org.sakaiproject.time.api.TimeRange; import org.sakaiproject.time.api.Time; import org.w3c.dom.Element; /** * <p>Calendar is the base interface for Calendar service calendars.</p> * <p>Calendars contains collections of CalendarEvents.</p> */ public interface Calendar extends Entity { /** * Access the context of the resource. * @return The context. */ public String getContext(); /** ** check if this calendar enables ical exports ** @return true if the calender allows exports; false if not **/ public boolean getExportEnabled(); /** ** set if this calendar enables ical exports **/ public void setExportEnabled( boolean enable ); /** ** Get the time of the last modify to this calendar ** @return String representation of current time **/ public Time getModified(); /** ** Set the time of the last modify for this calendar to now **/ public void setModified(); /** * check permissions for getEvents() and getEvent() on a SITE / calendar level. * @return true if the user is allowed to get events from the calendar, false if not. */ public boolean allowGetEvents(); /** * check permissions for getEvent() for a particular event. * @return true if the user is allowed to get the event from the calendar, false if not. */ public boolean allowGetEvent(String eventId); /** * Return a List of all or filtered events in the calendar. * The order in which the events will be found in the iteration is by event start date. * @param range A time range to limit the iterated events. May be null; all events will be returned. * @param filter A filtering object to accept events into the iterator, or null if no filtering is desired. * @return a List of all or filtered CalendarEvents in the calendar (may be empty). * @exception PermissionException if the user does not have read permission to the calendar. */ public List getEvents(TimeRange range, Filter filter) throws PermissionException; /** * Return a specific calendar event, as specified by event name. * @param eventId The id of the event to get. * @return the CalendarEvent that has the specified id. * @exception IdUnusedException If this id is not a defined event in this calendar. * @exception PermissionException If the user does not have any permissions to read the calendar. */ public CalendarEvent getEvent(String eventId) throws IdUnusedException, PermissionException; /** * Return the extra fields kept for each event in this calendar. * @return the extra fields kept for each event in this calendar, formatted into a single string. %%% */ public String getEventFields(); /** * check permissions for addEvent(). * @return true if the user is allowed to addEvent(...), false if not. */ public boolean allowAddEvent(); /** * Check if the user has permission to add a calendar-wide (not grouped) message. * * @return true if the user has permission to add a calendar-wide (not grouped) message. */ boolean allowAddCalendarEvent(); /** * Add a new event to this calendar. * @param range The event's time range. * @param displayName The event's display name (PROP_DISPLAY_NAME) property value. * @param description The event's description (PROP_DESCRIPTION) property value. * @param type The event's calendar event type (PROP_CALENDAR_TYPE) property value. * @param location The event's calendar event location (PROP_CALENDAR_LOCATION) property value. * @param access The event's access type site or grouped * @param groups The groups which can access this event * @param attachments The event attachments, a vector of Reference objects. * @return The newly added event. * @exception PermissionException If the user does not have permission to modify the calendar. */ public CalendarEvent addEvent(TimeRange range, String displayName, String description, String type, String location, EventAccess access, Collection groups, List attachments) throws PermissionException; /** * Add a new event to this calendar. * @param range The event's time range. * @param displayName The event's display name (PROP_DISPLAY_NAME) property value. * @param description The event's description (PROP_DESCRIPTION) property value. * @param type The event's calendar event type (PROP_CALENDAR_TYPE) property value. * @param location The event's calendar event location (PROP_CALENDAR_LOCATION) property value. * @param attachments The event attachments, a vector of Reference objects. * @return The newly added event. * @exception PermissionException If the user does not have permission to modify the calendar. */ public CalendarEvent addEvent(TimeRange range, String displayName, String description, String type, String location, List attachments) throws PermissionException; /** * Add a new event to this calendar. * Must commitEvent() to make official, or cancelEvent() when done! * @return The newly added event, locked for update. * @exception PermissionException If the user does not have write permission to the calendar. */ public CalendarEventEdit addEvent() throws PermissionException; /** * check permissions for editEvent() * @param id The event id. * @return true if the user is allowed to update the event, false if not. */ public boolean allowEditEvent(String eventId); /** * Return a specific calendar event, as specified by event name, locked for update. * Must commitEvent() to make official, or cancelEvent(), or removeEvent() when done! * @param eventId The id of the event to get. * @param editType add, remove or modifying calendar? * @return the Event that has the specified id. * @exception IdUnusedException If this name is not a defined event in this calendar. * @exception PermissionException If the user does not have any permissions to edit the event. * @exception InUseException if the event is locked for edit by someone else. */ public CalendarEventEdit getEditEvent(String eventId, String editType) throws IdUnusedException, PermissionException, InUseException; /** * Commit the changes made to a CalendarEventEdit object, and release the lock. * The CalendarEventEdit is disabled, and not to be used after this call. * @param edit The CalendarEventEdit object to commit. * @param intention The recurring event modification intention, * based on values in the GenericCalendarService "MOD_*", * used if the event is part of a recurring event sequence to determine how much of the sequence is changed by this commmit. */ public void commitEvent(CalendarEventEdit edit, int intention); /** * Commit the changes made to a CalendarEventEdit object, and release the lock. * The CalendarEventEdit is disabled, and not to be used after this call. * Note: if the event is a recurring event, the entire sequence is modified by this commit (MOD_ALL). * @param edit The CalendarEventEdit object to commit. */ public void commitEvent(CalendarEventEdit edit); /** * Cancel the changes made to a CalendarEventEdit object, and release the lock. * The CalendarEventEdit is disabled, and not to be used after this call. * @param edit The CalendarEventEdit object to commit. */ public void cancelEvent(CalendarEventEdit edit); /** * Merge in a new event as defined in the xml. * @param el The event information in XML in a DOM element. * @exception PermissionException If the user does not have write permission to the calendar. * @exception IdUsedException if the user id is already used. */ public CalendarEventEdit mergeEvent(Element el) throws PermissionException, IdUsedException; /** * check permissions for removeEvent(). * @param event The event from this calendar to remove. * @return true if the user is allowed to removeEvent(event), false if not. */ public boolean allowRemoveEvent(CalendarEvent event); /** * Remove an event from the calendar, one locked for edit. * @param edit The event from this calendar to remove. * @param intention The recurring event modification intention, * based on values in the GenericCalendarService "MOD_*", * used if the event is part of a recurring event sequence to determine how much of the sequence is removed. * @throws PermissionException if the end user does not have permission to remove. */ public void removeEvent(CalendarEventEdit edit, int intention) throws PermissionException; /** * Remove an event from the calendar, one locked for edit. * Note: if the event is a recurring event, the entire sequence is removed by this commit (MOD_ALL). * @param edit The event from this calendar to remove. * @throws PermissionException if the end user does not have permission to remove. */ public void removeEvent(CalendarEventEdit edit) throws PermissionException; /** * Get the collection of Groups defined for the context of this calendar that the end user has add event permissions in. * * @return The Collection (Group) of groups defined for the context of this calendar that the end user has add event permissions in, empty if none. */ Collection getGroupsAllowAddEvent(); /** * Get the collection of Group defined for the context of this calendar that the end user has get event permissions in. * * @return The Collection (Group) of groups defined for the context of this calendar that the end user has get event permissions in, empty if none. */ Collection getGroupsAllowGetEvent(); /** * Get the collection of Group defined for the context of this channel that the end user has remove event permissions in. * * @param own boolean flag indicating whether user owns event * * @return The Collection (Group) of groups defined for the context of this channel that the end user has remove event permissions in, empty if none. */ Collection getGroupsAllowRemoveEvent( boolean own ); /** * Checks if user has permission to modify any event (or fields) in this calendar * @param function * @return */ public boolean canModifyAnyEvent(String function); } // Calendar
/* * 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. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.transaction; /** * @version $Rev: 467742 $ $Date: 2010/04/07 16:52:44 $ */ public interface Synchronization { void beforeCompletion(); void afterCompletion(int status); }
/*- * ========================LICENSE_START================================= * Smartconfig Maven Plugin * * * Copyright (C) 2016 BruceZhang * * * 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. * =========================LICENSE_END================================== */ package com.alibaba.fastjson.serializer; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashSet; import java.util.TreeSet; /** * @author wenshao[szujobs@hotmail.com] */ public class CollectionSerializer implements ObjectSerializer { public final static CollectionSerializer instance = new CollectionSerializer(); public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { SerializeWriter out = serializer.getWriter(); if (object == null) { if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { out.write("[]"); } else { out.writeNull(); } return; } Type elementType = null; if (serializer.isEnabled(SerializerFeature.WriteClassName)) { if (fieldType instanceof ParameterizedType) { ParameterizedType param = (ParameterizedType) fieldType; elementType = param.getActualTypeArguments()[0]; } } Collection<?> collection = (Collection<?>) object; SerialContext context = serializer.getContext(); serializer.setContext(context, object, fieldName, 0); if (serializer.isEnabled(SerializerFeature.WriteClassName)) { if (HashSet.class == collection.getClass()) { out.append("Set"); } else if (TreeSet.class == collection.getClass()) { out.append("TreeSet"); } } try { int i = 0; out.append('['); for (Object item : collection) { if (i++ != 0) { out.append(','); } if (item == null) { out.writeNull(); continue; } Class<?> clazz = item.getClass(); if (clazz == Integer.class) { out.writeInt(((Integer) item).intValue()); continue; } if (clazz == Long.class) { out.writeLong(((Long) item).longValue()); if (out.isEnabled(SerializerFeature.WriteClassName)) { out.write('L'); } continue; } ObjectSerializer itemSerializer = serializer.getObjectWriter(clazz); itemSerializer.write(serializer, item, i - 1, elementType, 0); } out.append(']'); } finally { serializer.setContext(context); } } }
package com.github.alexnijjar.the_extractinator.mixin; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.github.alexnijjar.the_extractinator.TheExtractinator; import com.github.alexnijjar.the_extractinator.util.ModUtils; import com.google.gson.JsonElement; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import net.minecraft.recipe.RecipeManager; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; import net.minecraft.util.profiler.Profiler; @Mixin(RecipeManager.class) public class RecipeManagerMixin { // Blocks all non-supported recipes in the config. @Inject(method = "apply", at = @At("HEAD")) public void apply(Map<Identifier, JsonElement> map, ResourceManager resourceManager, Profiler profiler, CallbackInfo info) { List<Identifier> itemsToRemove = new ArrayList<>(); map.forEach((id, json) -> { if (id.toString().contains(TheExtractinator.MOD_ID + ":extractinator/")) { String path = id.getPath(); switch (TheExtractinator.CONFIG.extractinatorConfig.extractinatorRecipe) { case NONE -> { itemsToRemove.add(id); } case MINECRAFT -> { if (!path.contains("minecraft")) { itemsToRemove.add(id); } } case MODERN_INDUSTRIALIZATION -> { if (!path.contains("modern_industrialization") || !ModUtils.modLoaded("modern_industrialization")) { itemsToRemove.add(id); } } case TECH_REBORN -> { if (!path.contains("techreborn") || !ModUtils.modLoaded("techreborn")) { itemsToRemove.add(id); } } } } }); itemsToRemove.forEach(map.keySet()::remove); } }
package ru.sm.liquidfab; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
package de.pretrendr.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import de.pretrendr.boot.git.GitRepositoryState; /** * Manages requests concerning git related backend features. * * @author Tristan Schneider * */ @RequestMapping("/git") @RestController public class GitController { private final GitRepositoryState gitRepositoryState; /** * Autowired constructor. * * @param gitRepositoryState * autowired {@link GitRepositoryState} */ @Autowired public GitController(GitRepositoryState gitRepositoryState) { this.gitRepositoryState = gitRepositoryState; } /** * Retrieves the current state of git repo, line branch, last commit id, last * author and much more. * * @author Tristan Schneider * @return {@link ResponseEntity} containing information about current state of * git repo */ @RequestMapping(value = "/version", method = RequestMethod.GET) public ResponseEntity<GitRepositoryState> version() { return new ResponseEntity<GitRepositoryState>(gitRepositoryState, HttpStatus.OK); } }
package com.codepath.apps.restclienttemplate.models; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcel; @Parcel public class User { public String name; public String screenName; public String profileImageUrl; //empty constructor for parceler public User() {} public static User fromJson(JSONObject jsonObject) throws JSONException { User user = new User(); user.name = jsonObject.getString("name"); user.screenName = jsonObject.getString("screen_name"); user.profileImageUrl = jsonObject.getString("profile_image_url_https"); return user; } }
package com.javarush.task.pro.task07.task0713; public class Human extends Terran { }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 数据维度关系模型 * * @author auto create * @since 1.0, 2017-08-10 16:22:11 */ public class DataDim extends AlipayObject { private static final long serialVersionUID = 6362995152336886218L; /** * 维度名称,代表维度层级含义 不同维度间用“|”分割 */ @ApiField("dim_name") private String dimName; /** * 维度类型,并级或者层级 parallel 并列维度 hierarchical 层级维度 */ @ApiField("dim_type") private String dimType; /** * 维度值,代表维度层级的值 */ @ApiField("dim_value") private String dimValue; public String getDimName() { return this.dimName; } public void setDimName(String dimName) { this.dimName = dimName; } public String getDimType() { return this.dimType; } public void setDimType(String dimType) { this.dimType = dimType; } public String getDimValue() { return this.dimValue; } public void setDimValue(String dimValue) { this.dimValue = dimValue; } }
/* * Copyright (c) 2017 Armel Soro * * 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 org.rm3l.now4j.cli.subcommand; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.jetbrains.annotations.NotNull; import org.rm3l.now4j.contract.Now; public abstract class AbstractCommand { protected final Gson gson = new GsonBuilder().setPrettyPrinting().create(); @NotNull protected Now nowClient; public final void setNowClient(@NotNull final Now nowClient) { this.nowClient = nowClient; } public abstract void work() throws Exception; }
package com.alipay.api.domain; import java.util.List; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; /** * 用户信息申请记录查询响应模型 * * @author auto create * @since 1.0, 2020-09-21 17:21:30 */ public class AuthFieldResponse extends AlipayObject { private static final long serialVersionUID = 8394844878531499932L; /** * 用户信息申请记录列表 */ @ApiListField("records") @ApiField("auth_field_d_t_o") private List<AuthFieldDTO> records; public List<AuthFieldDTO> getRecords() { return this.records; } public void setRecords(List<AuthFieldDTO> records) { this.records = records; } }
package com.wust.entity; import java.util.Date; public class House { private int houseId; private int userId; private String houseTitle; private String houseType; private double houseFloorage; private double housePrice; private Date houseDate; private String district; private String street; private String contact; private String description; private String pubDate; private String filePath; public House(int houseId, int userId, String houseTitle, String houseType, double houseFloorage, double housePrice, Date houseDate, String district, String street, String contact, String description, String pubDate, String filePath) { super(); this.houseId = houseId; this.userId = userId; this.houseTitle = houseTitle; this.houseType = houseType; this.houseFloorage = houseFloorage; this.housePrice = housePrice; this.houseDate = houseDate; this.district = district; this.street = street; this.contact = contact; this.description = description; this.pubDate = pubDate; this.filePath = filePath; } public House(int userId, String houseTitle, String houseType, double houseFloorage, double housePrice, Date houseDate, String district, String street, String contact, String description, String pubDate, String filePath) { super(); this.userId = userId; this.houseTitle = houseTitle; this.houseType = houseType; this.houseFloorage = houseFloorage; this.housePrice = housePrice; this.houseDate = houseDate; this.district = district; this.street = street; this.contact = contact; this.description = description; this.pubDate = pubDate; this.filePath = filePath; } public House() { } public int getHouseId() { return houseId; } public void setHouseId(int houseId) { this.houseId = houseId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getHouseTitle() { return houseTitle; } public void setHouseTitle(String houseTitle) { this.houseTitle = houseTitle; } public String getHouseType() { return houseType; } public void setHouseType(String houseType) { this.houseType = houseType; } public double getHouseFloorage() { return houseFloorage; } public void setHouseFloorage(double houseFloorage) { this.houseFloorage = houseFloorage; } public double getHousePrice() { return housePrice; } public void setHousePrice(double housePrice) { this.housePrice = housePrice; } public Date getHouseDate() { return houseDate; } public void setHouseDate(Date houseDate) { this.houseDate = houseDate; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPubDate() { return pubDate; } public void setPubDate(String pubDate) { this.pubDate = pubDate; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } }
/** * 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. */ import java.lang.Override; import java.lang.UnsupportedOperationException; <@pp.dropOutputFile /> <@pp.changeOutputFile name="org/apache/drill/exec/store/StringOutputRecordWriter.java" /> <#include "/@includes/license.ftl" /> package org.apache.drill.exec.store; import com.google.common.collect.Lists; import org.apache.drill.exec.expr.TypeHelper; import org.apache.drill.exec.expr.holders.*; import org.apache.drill.exec.memory.TopLevelAllocator; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.record.BatchSchema; import org.apache.drill.exec.store.EventBasedRecordWriter.FieldConverter; import org.apache.drill.exec.vector.*; import org.apache.drill.exec.vector.complex.reader.FieldReader; import java.io.IOException; import java.lang.UnsupportedOperationException; import java.util.List; import java.util.Map; /** * Abstract implementation of RecordWriter interface which exposes interface: * {@link #writeHeader(List)} * {@link #addField(int,String)} * to output the data in string format instead of implementing addField for each type holder. * * This is useful for text format writers such as CSV, TSV etc. */ public abstract class StringOutputRecordWriter implements RecordWriter { private final BufferAllocator allocator; protected StringOutputRecordWriter(BufferAllocator allocator){ this.allocator = allocator; } public void updateSchema(BatchSchema schema) throws IOException { List<String> columnNames = Lists.newArrayList(); for (int i=0; i < schema.getFieldCount(); i++) { columnNames.add(schema.getColumn(i).getLastName()); } startNewSchema(columnNames); } @Override public FieldConverter getNewMapConverter(int fieldId, String fieldName, FieldReader reader) { throw new UnsupportedOperationException(); } public FieldConverter getNewRepeatedMapConverter(int fieldId, String fieldName, FieldReader reader) { throw new UnsupportedOperationException(); } public FieldConverter getNewRepeatedListConverter(int fieldId, String fieldName, FieldReader reader) { throw new UnsupportedOperationException(); } <#list vv.types as type> <#list type.minor as minor> <#list vv.modes as mode> @Override public FieldConverter getNew${mode.prefix}${minor.class}Converter(int fieldId, String fieldName, FieldReader reader) { return new ${mode.prefix}${minor.class}StringFieldConverter(fieldId, fieldName, reader); } public class ${mode.prefix}${minor.class}StringFieldConverter extends FieldConverter { <#if mode.prefix == "Repeated"> private Repeated${minor.class}Holder holder = new Repeated${minor.class}Holder(); <#else> private Nullable${minor.class}Holder holder = new Nullable${minor.class}Holder(); </#if> public ${mode.prefix}${minor.class}StringFieldConverter(int fieldId, String fieldName, FieldReader reader) { super(fieldId, fieldName, reader); } @Override public void writeField() throws IOException { <#if mode.prefix == "Nullable" > if (!reader.isSet()) { addField(fieldId, null); return; } <#elseif mode.prefix == "Repeated" > throw new UnsupportedOperationException("Repeated types are not supported."); } } <#break> </#if> reader.read(holder); <#if minor.class == "TinyInt" || minor.class == "UInt1" || minor.class == "UInt2" || minor.class == "SmallInt" || minor.class == "Int" || minor.class == "UInt4" || minor.class == "Float4" || minor.class == "BigInt" || minor.class == "UInt8" || minor.class == "Float8"> addField(fieldId, String.valueOf(holder.value)); <#elseif minor.class == "Bit"> addField(fieldId, holder.value == 0 ? "false" : "true"); <#elseif minor.class == "Date" || minor.class == "Time" || minor.class == "TimeTZ" || minor.class == "TimeStamp" || minor.class == "IntervalYear" || minor.class == "IntervalDay" || minor.class == "Interval" || minor.class == "Decimal9" || minor.class == "Decimal18" || minor.class == "Decimal28Dense" || minor.class == "Decimal38Dense" || minor.class == "Decimal28Sparse" || minor.class == "Decimal38Sparse"> // TODO: error check addField(fieldId, reader.readObject().toString()); <#elseif minor.class == "VarChar" || minor.class == "Var16Char" || minor.class == "VarBinary"> addField(fieldId, reader.readObject().toString()); <#else> throw new UnsupportedOperationException(String.format("Unsupported field type: %s"), holder.getCanonicalClass()); </#if> } } </#list> </#list> </#list> public void cleanup() throws IOException { } public abstract void startNewSchema(List<String> columnNames) throws IOException; public abstract void addField(int fieldId, String value) throws IOException; }
package pl.cyfronet.datanet.web.client.model; import java.util.Date; import java.util.List; import javax.validation.constraints.NotNull; import pl.cyfronet.datanet.model.beans.Entity; import pl.cyfronet.datanet.model.beans.Model; /** * Main purpose of this proxy is to allow creation of many new models. New model * will have generated id. * * @author marek */ public class ModelProxy extends Model implements Comparable<ModelProxy> { private static final long serialVersionUID = 1727938745935329386L; private Long newModelId; private Model model; private boolean dirty; public ModelProxy(@NotNull Model model) { this.model = model; } public ModelProxy(@NotNull Model model, @NotNull Long newModelId) { this.model = model; this.newModelId = newModelId; } @Override public long getId() { return newModelId != null ? newModelId : model.getId(); } public Model getModel() { return model; } @Override public void setId(long id) { model.setId(id); } @Override public String getName() { return model.getName(); } @Override public void setName(String name) { model.setName(name); } @Override public Date getTimestamp() { return model.getTimestamp(); } @Override public void setTimestamp(Date timestamp) { model.setTimestamp(timestamp); } @Override public List<Entity> getEntities() { return model.getEntities(); } @Override public void setEntities(List<Entity> entities) { model.setEntities(entities); } public void setDirty(boolean dirty) { this.dirty = dirty; } public boolean isDirty() { return dirty; } public boolean isNew() { return newModelId != null; } @Override public String toString() { return "ModelProxy [newModelId=" + newModelId + ", model=" + model + ", dirty=" + dirty + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((newModelId == null) ? 0 : newModelId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ModelProxy other = (ModelProxy) obj; if (getId() != other.getId()) return false; return true; } @Override public int compareTo(ModelProxy o) { return getName().compareToIgnoreCase(o.getName()); } }
/** * 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.zookeeper.server.quorum.flexible; import java.util.HashMap; import java.util.Set; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType; import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer; import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException; /** * This class implements a validator for majority quorums. The implementation is * straightforward. * */ public class QuorumMaj implements QuorumVerifier { private Map<Long, QuorumServer> allMembers = new HashMap<Long, QuorumServer>(); private HashMap<Long, QuorumServer> votingMembers = new HashMap<Long, QuorumServer>(); private HashMap<Long, QuorumServer> observingMembers = new HashMap<Long, QuorumServer>(); private long version = 0; private int half; public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do } public boolean equals(Object o) { if (!(o instanceof QuorumMaj)) { return false; } QuorumMaj qm = (QuorumMaj) o; if (qm.getVersion() == version) return true; if (allMembers.size() != qm.getAllMembers().size()) return false; for (QuorumServer qs : allMembers.values()) { QuorumServer qso = qm.getAllMembers().get(qs.id); if (qso == null || !qs.equals(qso)) return false; } return true; } /** * Defines a majority to avoid computing it every time. * */ public QuorumMaj(Map<Long, QuorumServer> allMembers) { this.allMembers = allMembers; for (QuorumServer qs : allMembers.values()) { if (qs.type == LearnerType.PARTICIPANT) { votingMembers.put(Long.valueOf(qs.id), qs); } else { observingMembers.put(Long.valueOf(qs.id), qs); } } half = votingMembers.size() / 2; } /** * 记录参与投票的服务器数量 * * @param props * @throws ConfigException */ public QuorumMaj(Properties props) throws ConfigException { for (Entry<Object, Object> entry : props.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (key.startsWith("server.")) { int dot = key.indexOf('.'); long sid = Long.parseLong(key.substring(dot + 1)); QuorumServer qs = new QuorumServer(sid, value); allMembers.put(Long.valueOf(sid), qs); if (qs.type == LearnerType.PARTICIPANT) { votingMembers.put(Long.valueOf(sid), qs); } else { observingMembers.put(Long.valueOf(sid), qs); } } else if (key.equals("version")) { version = Long.parseLong(value, 16); } } // 记录参与投票的服务器数量,排除 Observer half = votingMembers.size() / 2; } /** * Returns weight of 1 by default. * * @param id */ public long getWeight(long id) { return (long) 1; } public String toString() { StringBuilder sw = new StringBuilder(); for (QuorumServer member : getAllMembers().values()) { String key = "server." + member.id; String value = member.toString(); sw.append(key); sw.append('='); sw.append(value); sw.append('\n'); } String hexVersion = Long.toHexString(version); sw.append("version="); sw.append(hexVersion); return sw.toString(); } /** * 校验过半机制 * * Verifies if a set is a majority. Assumes that ackSet contains acks only * from votingMembers */ public boolean containsQuorum(Set<Long> ackSet) { return (ackSet.size() > half); } public Map<Long, QuorumServer> getAllMembers() { return allMembers; } public Map<Long, QuorumServer> getVotingMembers() { return votingMembers; } public Map<Long, QuorumServer> getObservingMembers() { return observingMembers; } public long getVersion() { return version; } public void setVersion(long ver) { version = ver; } }
/* * 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 morestatecapitals; /** * * @author nacer */ public class Capital { private String name; private int population; private float squareMileage; public Capital(String name, int population, float squareMileage){ this.name = name; this.population = population; this.squareMileage = squareMileage; } public String getName() {return this.name;} public int getPopulation() {return this.population;} public float getSquareMileage() {return this.squareMileage;} }
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2012 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.voice.type; import com.google.common.base.Objects; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import com.zimbra.common.soap.AccountConstants; import com.zimbra.common.soap.VoiceConstants; @XmlAccessorType(XmlAccessType.NONE) public class PhoneVoiceFeaturesInfo { /** * @zm-api-field-tag name * @zm-api-field-description Name */ @XmlAttribute(name=AccountConstants.A_NAME /* name */, required=true) private String name; /** * @zm-api-field-description */ @XmlElements({ @XmlElement(name=VoiceConstants.E_VOICE_MAIL_PREFS /* voicemailprefs */, type=VoiceMailPrefsFeature.class), @XmlElement(name=VoiceConstants.E_ANON_CALL_REJECTION /* anoncallrejection */, type=AnonCallRejectionFeature.class), @XmlElement(name=VoiceConstants.E_CALLER_ID_BLOCKING /* calleridblocking */, type=CallerIdBlockingFeature.class), @XmlElement(name=VoiceConstants.E_CALL_FORWARD /* callforward */, type=CallForwardFeature.class), @XmlElement(name=VoiceConstants.E_CALL_FORWARD_BUSY_LINE /* callforwardbusyline */, type=CallForwardBusyLineFeature.class), @XmlElement(name=VoiceConstants.E_CALL_FORWARD_NO_ANSWER /* callforwardnoanswer */, type=CallForwardNoAnswerFeature.class), @XmlElement(name=VoiceConstants.E_CALL_WAITING /* callwaiting */, type=CallWaitingFeature.class), @XmlElement(name=VoiceConstants.E_SELECTIVE_CALL_FORWARD /* selectivecallforward */, type=SelectiveCallForwardFeature.class), @XmlElement(name=VoiceConstants.E_SELECTIVE_CALL_ACCEPTANCE /* selectivecallacceptance */, type=SelectiveCallAcceptanceFeature.class), @XmlElement(name=VoiceConstants.E_SELECTIVE_CALL_REJECTION /* selectivecallrejection */, type=SelectiveCallRejectionFeature.class) }) private List<CallFeatureInfo> callFeatures = Lists.newArrayList(); public PhoneVoiceFeaturesInfo() { } public void setName(String name) { this.name = name; } public void setCallFeatures(Iterable <CallFeatureInfo> callFeatures) { this.callFeatures.clear(); if (callFeatures != null) { Iterables.addAll(this.callFeatures, callFeatures); } } public void addCallFeature(CallFeatureInfo callFeature) { this.callFeatures.add(callFeature); } public String getName() { return name; } public List<CallFeatureInfo> getCallFeatures() { return callFeatures; } public Objects.ToStringHelper addToStringInfo(Objects.ToStringHelper helper) { return helper .add("name", name) .add("callFeatures", callFeatures); } @Override public String toString() { return addToStringInfo(Objects.toStringHelper(this)).toString(); } }
package com.gyg9.android.task.delayedrunner; import android.util.Log; /** * 计划任务队列 * Created by gyliu on 15/10/9. */ public class PendingTaskQueue { private static final String TAG = "PendingTaskQueue"; private PendingTask head; private PendingTask tail; synchronized void enqueue(PendingTask pendingTask) { Log.d(TAG, "enqueue at " + Thread.currentThread().getName()); if (pendingTask == null) { throw new NullPointerException("null cannot be enqueued"); } if (tail != null) { tail.next = pendingTask; tail = pendingTask; } else if (head == null) { head = tail = pendingTask; } else { throw new IllegalStateException("Head present, but no tail"); } // notifyAll(); } synchronized PendingTask poll() { Log.d(TAG, "poll at " + Thread.currentThread().getName()); PendingTask pendingTask = head; if (head != null) { head = head.next; if (head == null) { tail = null; } } return pendingTask; } }
package com.tramchester.livedata.domain.DTO; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.tramchester.domain.places.Location; import com.tramchester.domain.reference.TransportMode; import com.tramchester.livedata.domain.liveUpdates.UpcomingDeparture; import com.tramchester.mappers.serialisation.LocalDateTimeJsonDeserializer; import com.tramchester.mappers.serialisation.LocalDateTimeJsonSerializer; import com.tramchester.mappers.serialisation.LocalTimeJsonSerializer; import java.time.Duration; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.Objects; @SuppressWarnings("unused") @JsonPropertyOrder(alphabetic = true) public class DepartureDTO implements Comparable<DepartureDTO> { // TODO Make from and destintaion StationRefDTO? private TransportMode transportMode; private String from; private String destination; private String carriages; private String status; private LocalDateTime dueTime; @JsonIgnore private LocalDateTime lastUpdated; public DepartureDTO(Location<?> from, UpcomingDeparture upcomingDeparture, LocalDateTime updateTime) { this(upcomingDeparture.getMode(), from.getName(), upcomingDeparture.getDestination().getName(), upcomingDeparture.getCarriages(), upcomingDeparture.getStatus(), upcomingDeparture.getWhen().toDate(updateTime.toLocalDate()), updateTime); } private DepartureDTO(TransportMode mode, String from, String destination, String carriages, String status, LocalDateTime dueTime, LocalDateTime lastUpdated) { this.transportMode = mode; this.from = from; this.destination = destination; this.carriages = carriages; this.status = status; this.dueTime = dueTime; this.lastUpdated = lastUpdated; } public DepartureDTO() { // for deserialisation } @JsonSerialize(using = LocalDateTimeJsonSerializer.class) @JsonDeserialize(using = LocalDateTimeJsonDeserializer.class) public LocalDateTime getDueTime() { return dueTime; } @JsonProperty(value = "when", access = JsonProperty.Access.READ_ONLY) @JsonSerialize(using = LocalTimeJsonSerializer.class) public LocalTime getWhenForLiveUpload() { // for keeping upload of live data consistent, not ideal but lots of historical data in S3 return dueTime.toLocalTime(); } public String getFrom() { return from; } public String getCarriages() { return carriages; } public String getStatus() { return status; } public String getDestination() { return destination; } public TransportMode getTransportMode() { return transportMode; } @Override public int compareTo(DepartureDTO other) { if (dueTime.equals(other.dueTime)) { // if same time use string ordering return destination.compareTo(other.destination); } // time ordering return dueTime.compareTo(other.dueTime); } @Override public String toString() { return "DepartureDTO{" + "transportMode=" + transportMode + ", from='" + from + '\'' + ", destination='" + destination + '\'' + ", carriages='" + carriages + '\'' + ", status='" + status + '\'' + ", dueTime=" + dueTime + ", lastUpdated=" + lastUpdated + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DepartureDTO that = (DepartureDTO) o; return transportMode == that.transportMode && from.equals(that.from) && destination.equals(that.destination) && carriages.equals(that.carriages) && status.equals(that.status) && dueTime.equals(that.dueTime) && lastUpdated.equals(that.lastUpdated); } @Override public int hashCode() { return Objects.hash(transportMode, from, destination, carriages, status, dueTime, lastUpdated); } @JsonProperty(value = "wait", access = JsonProperty.Access.READ_ONLY) public int getWait() { Duration duration = Duration.between(lastUpdated.truncatedTo(ChronoUnit.MINUTES), dueTime); long minutes = duration.toMinutes(); if (minutes<0) { return 0; } return (int) minutes; } }
/* * Copyright (c) 2005, 2016, 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 6270015 * @summary Light weight HTTP server * @run main/othervm -Dsun.net.httpserver.idleInterval=4 Test5 */ import com.sun.net.httpserver.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import java.io.*; import java.net.*; import java.security.*; import javax.net.ssl.*; /** * Test pipe-lining (no block) */ public class Test5 extends Test { static int count = 1; public static void main (String[] args) throws Exception { System.out.print ("Test5: "); Handler handler = new Handler(); InetSocketAddress addr = new InetSocketAddress (0); HttpServer server = HttpServer.create (addr, 0); int port = server.getAddress().getPort(); HttpContext c2 = server.createContext ("/test", handler); c2.getAttributes().put ("name", "This is the http handler"); ExecutorService exec = Executors.newCachedThreadPool(); server.setExecutor (exec); try { server.start (); doClient(port); System.out.println ("OK"); } finally { delay (); if (server != null) server.stop(2); if (exec != null) exec.shutdown(); } } static class Handler implements HttpHandler { volatile int invocation = 0; public void handle (HttpExchange t) throws IOException { InputStream is = t.getRequestBody(); Headers map = t.getRequestHeaders(); Headers rmap = t.getResponseHeaders(); int x = invocation ++; rmap.set ("XTest", Integer.toString (x)); switch (x) { case 0: checkBody (is, body1); break; case 1: checkBody (is, body2); break; case 2: checkBody (is, body3); break; case 3: checkBody (is, body4); break; } t.sendResponseHeaders (200, -1); t.close(); } } static void checkBody (InputStream is, String cmp) throws IOException { byte [] b = new byte [1024]; int count = 0, c; while ((c=is.read(b, count, b.length-count)) != -1) { count+=c; } is.close(); String s = new String (b, 0, count, "ISO8859_1"); if (!s.equals (cmp)) { throw new RuntimeException ("strings not equal"); } } static String body1 = "1234567890abcdefghij"; static String body2 = "2234567890abcdefghij0123456789"; static String body3 = "3wertyuiop"; static String body4 = "4234567890"; static String result = "HTTP/1.1 200 OK.*Xtest: 0.*"+ "HTTP/1.1 200 OK.*Xtest: 1.*"+ "HTTP/1.1 200 OK.*Xtest: 2.*"+ "HTTP/1.1 200 OK.*Xtest: 3.*"; public static void doClient (int port) throws Exception { String s = "GET /test/1.html HTTP/1.1\r\nContent-length: 20\r\n"+ "\r\n" +body1 + "GET /test/2.html HTTP/1.1\r\nContent-length: 30\r\n"+ "\r\n"+ body2 + "GET /test/3.html HTTP/1.1\r\nContent-length: 10\r\n"+ "\r\n"+ body3 + "GET /test/4.html HTTP/1.1\r\nContent-length: 10\r\n"+ "\r\n"+body4; Socket socket = new Socket ("localhost", port); OutputStream os = socket.getOutputStream(); os.write (s.getBytes()); InputStream is = socket.getInputStream(); int c, count=0; byte[] b = new byte [1024]; while ((c=is.read(b, count, b.length-count)) != -1) { count +=c; } is.close(); socket.close(); s = new String (b,0,count, "ISO8859_1"); if (!compare (s, result)) { System.err.println(" Expected [" + result + "]\n actual [" + s + "]"); throw new RuntimeException ("wrong string result"); } } static boolean compare (String s, String result) { Pattern pattern = Pattern.compile (result, Pattern.DOTALL|Pattern.CASE_INSENSITIVE ); Matcher matcher = pattern.matcher (s); return matcher.matches(); } }
/*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. **********************************************************************************************************************/ /** * This file is based on source code from the Hadoop Project (http://hadoop.apache.org/), licensed by the Apache * Software Foundation (ASF) under the Apache License, Version 2.0. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package eu.stratosphere.nephele.ipc; enum Status { SUCCESS(0), ERROR(1), FATAL(-1); int state; private Status(int state) { this.state = state; } }
package com.hubspot.jinjava.interpret; public class UnexpectedTokenException extends TemplateSyntaxException { private static final long serialVersionUID = 1L; private final String token; public UnexpectedTokenException(String token, int lineNumber, int startPosition) { super(token, "Unexpected token: " + token, lineNumber, startPosition); this.token = token; } public String getToken() { return token; } }
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert // Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2020.03.13 um 12:48:52 PM CET // package net.opengis.fes._2; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für AbstractProjectionClauseType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="AbstractProjectionClauseType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AbstractProjectionClauseType") public abstract class AbstractProjectionClauseType { }
/** * This file is licensed under the University of Illinois/NCSA Open Source License. See LICENSE.TXT for details. */ package edu.illinois.codingspectator.ui.tests.introduceparameterobject; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; import org.eclipse.jface.dialogs.IDialogConstants; import edu.illinois.codingspectator.ui.tests.CodingSpectatorBot; import edu.illinois.codingspectator.ui.tests.RefactoringTest; /** * * This test invokes an introduce parameter object refactoring on an overriding method, deselects * one of the parameter, previews the changes and finally cancels the refactoring. * * @author Mohsen Vakilian * */ @SuppressWarnings("restriction") public class T02 extends RefactoringTest { private static final String MENU_ITEM= "Introduce Parameter Object..."; private static final String SELECTION= "m1"; @Override protected String getTestFileName() { return "IntroduceParameterObjectTestFile"; } @Override protected void doExecuteRefactoring() { bot.selectElementToRefactor(getTestFileFullName(), 19, 9, SELECTION.length()); bot.invokeRefactoringFromMenu(MENU_ITEM); bot.clickButtons(IDialogConstants.YES_LABEL); bot.getBot().tableInGroup(RefactoringMessages.IntroduceParameterObjectWizard_type_group).getTableItem(0).uncheck(); bot.clickButtons(CodingSpectatorBot.PREVIEW_LABEL, IDialogConstants.CANCEL_LABEL); } }
package com.sun.amy.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.sun.amy.R; import com.sun.amy.adapter.LessonsAdapter; import com.sun.amy.data.LessonItemData; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static android.widget.LinearLayout.VERTICAL; public class LessonsActivity extends Activity { private RecyclerView mRecyclerView; private LessonsAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lessons); String lessonName = ""; String lessonDirectory = ""; Intent intent = getIntent(); if (intent.hasExtra("lesson_name")) { lessonName = intent.getStringExtra("lesson_name"); } if (intent.hasExtra("lesson_directory")) { lessonDirectory = intent.getStringExtra("lesson_directory"); } initView(lessonName); initData(lessonDirectory); } private void initView(String lessonName) { mRecyclerView = findViewById(R.id.recycler_view); LinearLayoutManager manager = new LinearLayoutManager(this); manager.setOrientation(VERTICAL); mRecyclerView.setLayoutManager(manager); TextView titleTextView = findViewById(R.id.tv_title); titleTextView.setText(lessonName); TextView dictTextView = findViewById(R.id.tv_dict); dictTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(LessonsActivity.this, DictActivity.class)); } }); } private void initData(String lessonDirectory) { List<LessonItemData> list = new ArrayList<>(); File amy = new File(Environment.getExternalStorageDirectory(), "amy"); if (amy.exists()) { File lesson = new File(amy, lessonDirectory); if (lesson.exists()) { File[] files = lesson.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { File config = new File(file, "config.ini"); if (config.exists()) { list.add(new LessonItemData(file.getName(), file.getPath())); } } } } } } Collections.sort(list); mAdapter = new LessonsAdapter(this, list); mRecyclerView.setAdapter(mAdapter); } }
/** * vertigo - application development platform * * Copyright (C) 2013-2020, Vertigo.io, team@vertigo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.vertigo.account.impl.authorization.dsl.rules; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import io.vertigo.account.authorization.definitions.rulemodel.RuleOperator; import io.vertigo.commons.peg.AbstractRule; import io.vertigo.commons.peg.PegChoice; import io.vertigo.commons.peg.PegRule; import io.vertigo.commons.peg.PegRules; /** * Parsing rule for boolean operator. * || or OR && and AND * @author npiedeloup */ final class DslOperatorRule<O extends RuleOperator> extends AbstractRule<O, List<Object>> { private final Map<String, O> operatorIndex; DslOperatorRule(final O[] operators, final String ruleName) { super(createMainRule(operators), ruleName); operatorIndex = (Map<String, O>) getOperatorIndex(operators); } private static PegRule<List<Object>> createMainRule(final RuleOperator[] operators) { final List<PegRule<?>> operatorRules = new ArrayList<>(); for (final String operator : getOperatorIndex(operators).keySet()) { operatorRules.add(PegRules.term(operator)); } return PegRules.sequence( DslSyntaxRules.SPACES, //0 PegRules.choice(operatorRules), //1 DslSyntaxRules.SPACES); //2 } private static Map<String, RuleOperator> getOperatorIndex(final RuleOperator[] operators) { final Map<String, RuleOperator> operatorIndex = new LinkedHashMap<>(); for (final RuleOperator operator : operators) { for (final String authorizedString : operator.authorizedString()) { operatorIndex.put(authorizedString, operator); } } return operatorIndex; } /** {@inheritDoc} */ @Override protected O handle(final List<Object> parsing) { final String operatorStr = (String) ((PegChoice) parsing.get(1)).getValue(); return operatorIndex.get(operatorStr); } }
/* * Copyright 2018-present Facebook, 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.facebook.buck.core.toolchain.impl; import com.facebook.buck.core.config.BuckConfig; import com.facebook.buck.core.toolchain.ToolchainProvider; import com.facebook.buck.core.toolchain.ToolchainProviderFactory; import com.facebook.buck.io.ExecutableFinder; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.rules.keys.config.RuleKeyConfiguration; import com.facebook.buck.util.ProcessExecutor; import com.google.common.collect.ImmutableMap; import org.pf4j.PluginManager; public class DefaultToolchainProviderFactory implements ToolchainProviderFactory { private final PluginManager pluginManager; private final ImmutableMap<String, String> environment; private final ProcessExecutor processExecutor; private final ExecutableFinder executableFinder; public DefaultToolchainProviderFactory( PluginManager pluginManager, ImmutableMap<String, String> environment, ProcessExecutor processExecutor, ExecutableFinder executableFinder) { this.pluginManager = pluginManager; this.environment = environment; this.processExecutor = processExecutor; this.executableFinder = executableFinder; } @Override public ToolchainProvider create( BuckConfig buckConfig, ProjectFilesystem projectFilesystem, RuleKeyConfiguration ruleKeyConfiguration) { return new DefaultToolchainProvider( pluginManager, environment, buckConfig, projectFilesystem, processExecutor, executableFinder, ruleKeyConfiguration); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elasticbeanstalk.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.elasticbeanstalk.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * RetrieveEnvironmentInfoRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RetrieveEnvironmentInfoRequestMarshaller implements Marshaller<Request<RetrieveEnvironmentInfoRequest>, RetrieveEnvironmentInfoRequest> { public Request<RetrieveEnvironmentInfoRequest> marshall(RetrieveEnvironmentInfoRequest retrieveEnvironmentInfoRequest) { if (retrieveEnvironmentInfoRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } Request<RetrieveEnvironmentInfoRequest> request = new DefaultRequest<RetrieveEnvironmentInfoRequest>(retrieveEnvironmentInfoRequest, "AWSElasticBeanstalk"); request.addParameter("Action", "RetrieveEnvironmentInfo"); request.addParameter("Version", "2010-12-01"); request.setHttpMethod(HttpMethodName.POST); if (retrieveEnvironmentInfoRequest.getEnvironmentId() != null) { request.addParameter("EnvironmentId", StringUtils.fromString(retrieveEnvironmentInfoRequest.getEnvironmentId())); } if (retrieveEnvironmentInfoRequest.getEnvironmentName() != null) { request.addParameter("EnvironmentName", StringUtils.fromString(retrieveEnvironmentInfoRequest.getEnvironmentName())); } if (retrieveEnvironmentInfoRequest.getInfoType() != null) { request.addParameter("InfoType", StringUtils.fromString(retrieveEnvironmentInfoRequest.getInfoType())); } return request; } }
package org.sgdk.resourcemanager.ui.panels.projectexplorer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import org.sgdk.resourcemanager.ui.ResourceManagerFrame; import org.sgdk.resourcemanager.ui.panels.projectexplorer.modals.ExportProjectDialog; public class ProjectPopupMenu extends FolderPopupMenu { /** * */ private static final long serialVersionUID = 1L; private ExportProjectDialog exportProjectDialog = null; public ProjectPopupMenu(ResourceManagerFrame parent) { super(parent); JMenuItem exportProject = new JMenuItem("ExportProject"); addSeparator(); exportProject.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(exportProjectDialog == null) { exportProjectDialog = new ExportProjectDialog(parent, getParentNode()); }else { exportProjectDialog.setVisible(true); } } }); add(exportProject); } }
package org.mltooling.core.utils.structures; import org.mltooling.core.utils.StringUtils; import java.io.*; import java.util.ArrayList; import java.util.Collection; public class CaseInsensitiveFrequencyList extends FrequencyList<String> { // ================ Constants =========================================== // private final static String DEFAULT_DELIMITER = ";"; // ================ Members ============================================= // public CaseInsensitiveFrequencyList() { super(); } public CaseInsensitiveFrequencyList(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } // ================ Constructors & Main ================================= // public static CaseInsensitiveFrequencyList loadFromFile(File file) { return loadFromFile(file, DEFAULT_DELIMITER); } public static CaseInsensitiveFrequencyList loadFromFile(File file, String outputDelimiter) { CaseInsensitiveFrequencyList frequencyList = new CaseInsensitiveFrequencyList(); try { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StringUtils.UTF_8_CHARSET)); String line = null; boolean firstLineFlag = true; while ((line = reader.readLine()) != null) { if (!StringUtils.isNullOrEmpty(line)) { if (firstLineFlag) { firstLineFlag = false; continue; } String[] slittedLine = line.split(outputDelimiter); if (slittedLine.length != 2) { continue; } String key = slittedLine[0]; int frequency = Integer.valueOf(slittedLine[1]); frequencyList.add(key, frequency); } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } } catch (IOException e) { e.printStackTrace(); } return frequencyList; } @Override public boolean contains(Object key) { return super.contains(lowerCaseKey(key)); } public boolean add(String key, int keyFreq) { return super.add(lowerCaseKey(key), keyFreq); } @Override public boolean add(String key) { return super.add(lowerCaseKey(key)); } @Override public boolean remove(Object key) { return super.remove(lowerCaseKey(key)); } @Override public boolean containsAll(Collection<?> items) { return super.containsAll(lowerCaseCollection(items)); } @Override public boolean addAll(Collection<? extends String> items) { Collection<String> newCollection = new ArrayList<>(); for (Object key : items) { newCollection.add(lowerCaseKey(key)); } return super.addAll(newCollection); } @Override public boolean retainAll(Collection<?> items) { return super.retainAll(lowerCaseCollection(items)); } @Override public boolean removeAll(Collection<?> items) { return super.removeAll(lowerCaseCollection(items)); } @Override public int getFreq(String key) { return super.getFreq(lowerCaseKey(key)); } @Override public String toString() { StringBuilder statsOutput = new StringBuilder(); for (String key : this.getSortedList()) { statsOutput.append(key).append(": ").append(this.getFreq(key)).append("; "); } return statsOutput.toString(); } // ================ Public Methods ====================================== // public void writeToFile(File file, int minFreq) { writeToFile(file, minFreq, DEFAULT_DELIMITER); } public void writeToFile(File file, int minFreq, String outputDelimiter) { try { FileOutputStream fileStream = new FileOutputStream(file, true); BufferedWriter fileWriter = new BufferedWriter(new OutputStreamWriter(fileStream, StringUtils.UTF_8_CHARSET)); fileWriter.write("key" + outputDelimiter + "frequency"); for (String key : this.getSortedList(true, minFreq)) { int freq = getFreq(key); key = key.replace(outputDelimiter, ","); fileWriter.write(System.getProperty("line.separator") + key + outputDelimiter + freq); } fileWriter.close(); fileStream.close(); } catch (IOException e) { e.printStackTrace(); } } // ================ Methods for/from SuperClass / Interfaces ============ // // ================ Public Methods ====================================== // // ================ Private Methods ===================================== // private Collection<?> lowerCaseCollection(Collection<?> items) { Collection<String> newCollection = new ArrayList<>(); for (Object key : items) { newCollection.add(lowerCaseKey(key)); } return newCollection; } private String lowerCaseKey(Object key) { return ((String) key).toLowerCase(); } // ================ Getter & Setter ===================================== // // ================ Builder Pattern ===================================== // // ================ Inner & Anonymous Classes =========================== // }
package application; public class Program { public static void main(String[] args) { String [] vect = new String [] {"Maria", "Bob", "Alex"}; for (int i=0; i<vect.length; i++) { System.out.println(vect[i]); } // with for each System.out.println("--------------------------"); for (String obj : vect) { System.out.println(obj); } } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.model.bpmn.impl.instance; import org.camunda.bpm.model.bpmn.BpmnModelInstance; import org.camunda.bpm.model.bpmn.builder.ReceiveTaskBuilder; import org.camunda.bpm.model.bpmn.instance.Message; import org.camunda.bpm.model.bpmn.instance.Operation; import org.camunda.bpm.model.bpmn.instance.ReceiveTask; import org.camunda.bpm.model.bpmn.instance.Task; import org.camunda.bpm.model.xml.ModelBuilder; import org.camunda.bpm.model.xml.impl.instance.ModelTypeInstanceContext; import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder; import org.camunda.bpm.model.xml.type.attribute.Attribute; import org.camunda.bpm.model.xml.type.reference.AttributeReference; import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.*; import static org.camunda.bpm.model.xml.type.ModelElementTypeBuilder.ModelTypeInstanceProvider; /** * The BPMN receiveTask element * * @author Sebastian Menski */ public class ReceiveTaskImpl extends TaskImpl implements ReceiveTask { protected static Attribute<String> implementationAttribute; protected static Attribute<Boolean> instantiateAttribute; protected static AttributeReference<Message> messageRefAttribute; protected static AttributeReference<Operation> operationRefAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ReceiveTask.class, BPMN_ELEMENT_RECEIVE_TASK) .namespaceUri(BPMN20_NS) .extendsType(Task.class) .instanceProvider(new ModelTypeInstanceProvider<ReceiveTask>() { public ReceiveTask newInstance(ModelTypeInstanceContext instanceContext) { return new ReceiveTaskImpl(instanceContext); } }); implementationAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPLEMENTATION) .defaultValue("##WebService") .build(); instantiateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_INSTANTIATE) .defaultValue(false) .build(); messageRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_MESSAGE_REF) .qNameAttributeReference(Message.class) .build(); operationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OPERATION_REF) .qNameAttributeReference(Operation.class) .build(); typeBuilder.build(); } public ReceiveTaskImpl(ModelTypeInstanceContext context) { super(context); } public ReceiveTaskBuilder builder() { return new ReceiveTaskBuilder((BpmnModelInstance) modelInstance, this); } public String getImplementation() { return implementationAttribute.getValue(this); } public void setImplementation(String implementation) { implementationAttribute.setValue(this, implementation); } public boolean instantiate() { return instantiateAttribute.getValue(this); } public void setInstantiate(boolean instantiate) { instantiateAttribute.setValue(this, instantiate); } public Message getMessage() { return messageRefAttribute.getReferenceTargetElement(this); } public void setMessage(Message message) { messageRefAttribute.setReferenceTargetElement(this, message); } public Operation getOperation() { return operationRefAttribute.getReferenceTargetElement(this); } public void setOperation(Operation operation) { operationRefAttribute.setReferenceTargetElement(this, operation); } }
/** * Copyright 2009-2013 Oy Vaadin Ltd * * 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.vaadin.addon.jpacontainer.metadata; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * An extended version of {@link PropertyMetadata} that provides additional * information about persistent properties. * * @author Petter Holmström (Vaadin Ltd) * @since 1.0 */ public class PersistentPropertyMetadata extends PropertyMetadata { private static final long serialVersionUID = -4097189601179456814L; /** * Enumeration defining the property access types. * * @author Petter Holmström (Vaadin Ltd) */ public enum AccessType { /** * The property is accessed as a JavaBean property using getters and * setters. */ METHOD, /** * The property is accessed directly as a field. */ FIELD } private final PropertyKind propertyKind; private final ClassMetadata<?> typeMetadata; transient final Field field; // Required for serialization protected final String fieldName; protected final Class<?> fieldDeclaringClass; /** * Creates a new instance of <code>PersistentPropertyMetadata</code>. * * @param name * the name of the property (must not be null). * @param type * the type of the property (must not be null). * @param propertyKind * the kind of the property, must be either * {@link PropertyKind#ONE_TO_MANY}, * {@link PropertyKind#MANY_TO_MANY}, * {@link PropertyKind#ELEMENT_COLLECTION} or * {@link PropertyKind#SIMPLE} . * @param field * the field that can be used to access the property (must not be * null). */ PersistentPropertyMetadata(String name, Class<?> type, PropertyKind propertyKind, Field field, Method setter) { super(name, type, null, setter); assert propertyKind == PropertyKind.ONE_TO_MANY || propertyKind == PropertyKind.MANY_TO_MANY || propertyKind == PropertyKind.ELEMENT_COLLECTION || propertyKind == PropertyKind.SIMPLE : "propertyKind must be ONE_TO_MANY or SIMPLE"; assert field != null : "field must not be null"; this.propertyKind = propertyKind; typeMetadata = null; this.field = field; fieldName = field.getName(); fieldDeclaringClass = field.getDeclaringClass(); } /** * Creates a new instance of <code>PersistentPropertyMetadata</code>. * * @param name * the name of the property (must not be null). * @param type * type type of the property (must not be null). * @param propertyKind * the kind of the property, must be either * {@link PropertyKind#ONE_TO_MANY}, * {@link PropertyKind#MANY_TO_MANY}, * {@link PropertyKind#ELEMENT_COLLECTION} or * {@link PropertyKind#SIMPLE} . * @param getter * the getter method that can be used to read the property value * (must not be null). * @param setter * the setter method that can be used to set the property value * (must not be null). */ PersistentPropertyMetadata(String name, Class<?> type, PropertyKind propertyKind, Method getter, Method setter) { super(name, type, getter, setter); assert propertyKind == PropertyKind.ONE_TO_MANY || propertyKind == PropertyKind.MANY_TO_MANY || propertyKind == PropertyKind.ELEMENT_COLLECTION || propertyKind == PropertyKind.SIMPLE : "propertyKind must be ONE_TO_MANY or SIMPLE"; assert getter != null : "getter must not be null"; assert setter != null : "setter must not be null"; this.propertyKind = propertyKind; typeMetadata = null; field = null; fieldName = null; fieldDeclaringClass = null; } /** * Creates a new instance of <code>PersistentPropertyMetadata</code>. * * @param name * the name of the property (must not be null). * @param type * the type metadata of the property (must not be null). * @param propertyKind * the kind of the property, must be either * {@link PropertyKind#MANY_TO_ONE}, * {@link PropertyKind#ONE_TO_ONE} or * {@link PropertyKind#EMBEDDED}. * @param field * the field that can be used to access the property (must not be * null). */ PersistentPropertyMetadata(String name, ClassMetadata<?> type, PropertyKind propertyKind, Field field, Method setter) { super(name, type!=null?type.getMappedClass():null, null, setter); assert type != null : "type must not be null"; assert propertyKind == PropertyKind.MANY_TO_ONE || propertyKind == PropertyKind.ONE_TO_ONE || propertyKind == PropertyKind.EMBEDDED : "propertyKind must be MANY_TO_ONE or EMBEDDED"; assert field != null : "field must not be null"; this.propertyKind = propertyKind; typeMetadata = type; this.field = field; fieldName = field.getName(); fieldDeclaringClass = field.getDeclaringClass(); } /** * Creates a new instance of <code>PersistentPropertyMetadata</code>. * * @param name * the name of the property (must not be null). * @param type * the type metadata of the property (must not be null). * @param propertyKind * the kind of the property, must be either * {@link PropertyKind#MANY_TO_ONE}, * {@link PropertyKind#ONE_TO_ONE} or * {@link PropertyKind#EMBEDDED}. * @param getter * the getter method that can be used to read the property value * (must not be null). * @param setter * the setter method that can be used to set the property value * (must not be null). */ PersistentPropertyMetadata(String name, ClassMetadata<?> type, PropertyKind propertyKind, Method getter, Method setter) { super(name, type!=null?type.getMappedClass():null, getter, setter); assert type != null : "type must not be null"; assert propertyKind == PropertyKind.MANY_TO_ONE || propertyKind == PropertyKind.ONE_TO_ONE || propertyKind == PropertyKind.EMBEDDED : "propertyKind must be MANY_TO_ONE or EMBEDDED"; assert getter != null : "getter must not be null"; assert setter != null : "setter must not be null"; this.propertyKind = propertyKind; typeMetadata = type; field = null; fieldName = null; fieldDeclaringClass = null; } /** * This constructor is used when deserializing the object. * * @see #readResolve() */ private PersistentPropertyMetadata(String name, ClassMetadata<?> typeMetadata, Class<?> type, PropertyKind propertyKind, Method getter, Method setter, Field field) { super(name, type, getter, setter); this.propertyKind = propertyKind; this.typeMetadata = typeMetadata; this.field = field; if (this.field == null) { fieldName = null; fieldDeclaringClass = null; } else { fieldName = field.getName(); fieldDeclaringClass = field.getDeclaringClass(); } } /** * The metadata of the property type, if it is embedded or a reference. * Otherwise, this method returns null. * * @see #getPropertyKind() */ public ClassMetadata<?> getTypeMetadata() { return typeMetadata; } /** * The kind of the property. */ @Override public PropertyKind getPropertyKind() { return propertyKind; } /** * The way the property value is accessed (as a JavaBean property or as a * field). */ public AccessType getAccessType() { return field != null ? AccessType.FIELD : AccessType.METHOD; } @Override public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { if (field != null) { return field.getAnnotation(annotationClass); } else { return super.getAnnotation(annotationClass); } } @Override public Annotation[] getAnnotations() { if (field != null) { return field.getAnnotations(); } else { return super.getAnnotations(); } } @Override public Object readResolve() throws ObjectStreamException { try { Field f = null; if (fieldName != null) { f = fieldDeclaringClass.getDeclaredField(fieldName); } Method getterM = null; if (getterName != null) { getterM = getterDeclaringClass.getDeclaredMethod(getterName); } Method setterM = null; if (setterName != null) { // use the type from field if possible. type is Vaadin property // type, which means that for primitive types we convert it to // wrapper type Class<?> setterType = (f == null) ? getType() : f.getType(); setterM = setterDeclaringClass.getDeclaredMethod(setterName, setterType); } return new PersistentPropertyMetadata(getName(), typeMetadata, getType(), propertyKind, getterM, setterM, f); } catch (Exception e) { e.printStackTrace(); throw new InvalidObjectException(e.getMessage()); } } /** * {@inheritDoc }. */ @Override public boolean isWritable() { return super.isWritable(); } /* * Note, that we only compare the mapped classes of the typeMetadata fields. * If we compared the typeMetadata fields themselves, we could run into an * infinite loop if there are circular references (e.g. a parent-property of * the same type) in the metadata. */ @Override public boolean equals(Object obj) { if (super.equals(obj)) { // Includes check of parameter type PersistentPropertyMetadata other = (PersistentPropertyMetadata) obj; return propertyKind.equals(other.propertyKind) && (typeMetadata == null ? other.typeMetadata == null : typeMetadata.getMappedClass().equals( other.typeMetadata.getMappedClass())) && (field == null ? other.field == null : field .equals(other.field)); } return false; } @Override public int hashCode() { int hash = super.hashCode(); hash = hash * 31 + propertyKind.hashCode(); if (typeMetadata != null) { hash = hash * 31 + typeMetadata.getMappedClass().hashCode(); } if (field != null) { hash = hash * 31 + field.hashCode(); } return hash; } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|types package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertFalse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|MiscTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|SmallTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|Order import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|PositionedByteRange import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|SimplePositionedMutableByteRange import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Rule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|rules operator|. name|ExpectedException import|; end_import begin_class annotation|@ name|Category argument_list|( block|{ name|MiscTests operator|. name|class block|, name|SmallTests operator|. name|class block|} argument_list|) specifier|public class|class name|TestOrderedInt8 block|{ specifier|private specifier|static specifier|final name|Byte index|[] name|VALUES init|= operator|new name|Byte index|[] block|{ literal|1 block|, literal|22 block|} decl_stmt|; annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestOrderedInt8 operator|. name|class argument_list|) decl_stmt|; annotation|@ name|Rule specifier|public name|ExpectedException name|exception init|= name|ExpectedException operator|. name|none argument_list|() decl_stmt|; annotation|@ name|Test specifier|public name|void name|testIsNullableIsFalse parameter_list|() block|{ specifier|final name|DataType argument_list|< name|Byte argument_list|> name|type init|= operator|new name|OrderedInt8 argument_list|( name|Order operator|. name|ASCENDING argument_list|) decl_stmt|; name|assertFalse argument_list|( name|type operator|. name|isNullable argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testEncodedClassIsByte parameter_list|() block|{ specifier|final name|DataType argument_list|< name|Byte argument_list|> name|type init|= operator|new name|OrderedInt8 argument_list|( name|Order operator|. name|ASCENDING argument_list|) decl_stmt|; name|assertEquals argument_list|( name|Byte operator|. name|class argument_list|, name|type operator|. name|encodedClass argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testEncodedLength parameter_list|() block|{ specifier|final name|PositionedByteRange name|buffer init|= operator|new name|SimplePositionedMutableByteRange argument_list|( literal|20 argument_list|) decl_stmt|; for|for control|( specifier|final name|DataType argument_list|< name|Byte argument_list|> name|type range|: operator|new name|OrderedInt8 index|[] block|{ operator|new name|OrderedInt8 argument_list|( name|Order operator|. name|ASCENDING argument_list|) block|, operator|new name|OrderedInt8 argument_list|( name|Order operator|. name|DESCENDING argument_list|) block|} control|) block|{ for|for control|( specifier|final name|Byte name|val range|: name|VALUES control|) block|{ name|buffer operator|. name|setPosition argument_list|( literal|0 argument_list|) expr_stmt|; name|type operator|. name|encode argument_list|( name|buffer argument_list|, name|val argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"encodedLength does not match actual, " operator|+ name|val argument_list|, name|buffer operator|. name|getPosition argument_list|() argument_list|, name|type operator|. name|encodedLength argument_list|( name|val argument_list|) argument_list|) expr_stmt|; block|} block|} block|} annotation|@ name|Test specifier|public name|void name|testEncodeNoSupportForNull parameter_list|() block|{ name|exception operator|. name|expect argument_list|( name|IllegalArgumentException operator|. name|class argument_list|) expr_stmt|; specifier|final name|DataType argument_list|< name|Byte argument_list|> name|type init|= operator|new name|OrderedInt8 argument_list|( name|Order operator|. name|ASCENDING argument_list|) decl_stmt|; name|type operator|. name|encode argument_list|( operator|new name|SimplePositionedMutableByteRange argument_list|( literal|20 argument_list|) argument_list|, literal|null argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testEncodedFloatLength parameter_list|() block|{ specifier|final name|PositionedByteRange name|buffer init|= operator|new name|SimplePositionedMutableByteRange argument_list|( literal|20 argument_list|) decl_stmt|; for|for control|( specifier|final name|OrderedInt8 name|type range|: operator|new name|OrderedInt8 index|[] block|{ operator|new name|OrderedInt8 argument_list|( name|Order operator|. name|ASCENDING argument_list|) block|, operator|new name|OrderedInt8 argument_list|( name|Order operator|. name|DESCENDING argument_list|) block|} control|) block|{ for|for control|( specifier|final name|Byte name|val range|: name|VALUES control|) block|{ name|buffer operator|. name|setPosition argument_list|( literal|0 argument_list|) expr_stmt|; name|type operator|. name|encodeByte argument_list|( name|buffer argument_list|, name|val argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"encodedLength does not match actual, " operator|+ name|val argument_list|, name|buffer operator|. name|getPosition argument_list|() argument_list|, name|type operator|. name|encodedLength argument_list|( name|val argument_list|) argument_list|) expr_stmt|; block|} block|} block|} block|} end_class end_unit
/* * Copyright (c) 2018 amy, All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mewna.catnip.cache; import com.grack.nanojson.JsonArray; import com.grack.nanojson.JsonObject; import com.mewna.catnip.Catnip; import com.mewna.catnip.cache.view.*; import com.mewna.catnip.entity.builder.PresenceBuilder; import com.mewna.catnip.entity.channel.Channel; import com.mewna.catnip.entity.channel.GuildChannel; import com.mewna.catnip.entity.channel.UserDMChannel; import com.mewna.catnip.entity.guild.Guild; import com.mewna.catnip.entity.guild.Member; import com.mewna.catnip.entity.guild.Role; import com.mewna.catnip.entity.impl.EntityBuilder; import com.mewna.catnip.entity.misc.Emoji.CustomEmoji; import com.mewna.catnip.entity.user.Presence; import com.mewna.catnip.entity.user.Presence.OnlineStatus; import com.mewna.catnip.entity.user.User; import com.mewna.catnip.entity.user.VoiceState; import com.mewna.catnip.util.rx.RxHelpers; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Single; import lombok.Getter; import lombok.experimental.Accessors; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.time.format.DateTimeFormatter; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.LongPredicate; import static com.mewna.catnip.shard.DiscordEvent.Raw; import static com.mewna.catnip.util.Utils.removeIf; /** * @author amy * @since 9/18/18. */ @Accessors(fluent = true, chain = true) @SuppressWarnings("unused") public abstract class MemoryEntityCache implements EntityCacheWorker { private static final Presence DEFAULT_PRESENCE = new PresenceBuilder().status(OnlineStatus.OFFLINE).build(); @SuppressWarnings("WeakerAccess") protected final MutableNamedCacheView<Guild> guildCache = createGuildCacheView(); @SuppressWarnings("WeakerAccess") protected final Map<Long, MutableNamedCacheView<Member>> memberCache = new ConcurrentHashMap<>(); @SuppressWarnings("WeakerAccess") protected final Map<Long, MutableNamedCacheView<Role>> roleCache = new ConcurrentHashMap<>(); @SuppressWarnings("WeakerAccess") protected final Map<Long, MutableNamedCacheView<GuildChannel>> guildChannelCache = new ConcurrentHashMap<>(); @SuppressWarnings("WeakerAccess") protected final Map<Long, MutableNamedCacheView<CustomEmoji>> emojiCache = new ConcurrentHashMap<>(); @SuppressWarnings("WeakerAccess") protected final Map<Long, MutableCacheView<VoiceState>> voiceStateCache = new ConcurrentHashMap<>(); @SuppressWarnings("WeakerAccess") protected final AtomicReference<User> selfUser = new AtomicReference<>(null); @Getter private Catnip catnip; private EntityBuilder entityBuilder; /** * Function used to map members to their name, for named cache views. * Used by the default {@link #createMemberCacheView()} and * {@link #members()} implementations. * <p> * Defaults to returning a member's effective name, which is their * nickname, if present, or their username. * * @return Function used to map members to their name. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected Function<Member, String> memberNameFunction() { return m -> { if(m.nick() != null) { return m.nick(); } final User u = user(m.idAsLong()); return u == null ? null : u.username(); }; } /** * Creates a new guild cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new guild cache view. * * @implNote Defaults to calling {@link #createNamedCacheView(Function)}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableNamedCacheView<Guild> createGuildCacheView() { return createNamedCacheView(Guild::name); } /** * Creates a new user cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new user cache view. * * @implNote Defaults to calling {@link #createNamedCacheView(Function)}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableNamedCacheView<User> createUserCacheView() { return createNamedCacheView(User::username); } /** * Creates a new DM channel cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new DM channel cache view. * * @implNote Defaults to calling {@link #createCacheView()}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableCacheView<UserDMChannel> createDMChannelCacheView() { return createCacheView(); } /** * Creates a new presence cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new presence cache view. * * @implNote Defaults to calling {@link #createCacheView()}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableCacheView<Presence> createPresenceCacheView() { return createCacheView(); } /** * Creates a new guild channel cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new guild channel cache view. * * @implNote Defaults to calling {@link #createNamedCacheView(Function)}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableNamedCacheView<GuildChannel> createGuildChannelCacheView() { return createNamedCacheView(GuildChannel::name); } /** * Creates a new role cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new role cache view. * * @implNote Defaults to calling {@link #createNamedCacheView(Function)}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableNamedCacheView<Role> createRoleCacheView() { return createNamedCacheView(Role::name); } /** * Creates a new member cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new member cache view. * * @implNote Defaults to calling {@link #createNamedCacheView(Function)}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableNamedCacheView<Member> createMemberCacheView() { return createNamedCacheView(memberNameFunction()); } /** * Creates a new emoji cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new emoji cache view. * * @implNote Defaults to calling {@link #createNamedCacheView(Function)}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableNamedCacheView<CustomEmoji> createEmojiCacheView() { return createNamedCacheView(CustomEmoji::name); } /** * Creates a new voice state cache view. Subclasses can override this method to * use a different cache view implementation. * * @return A new voice state cache view. * * @implNote Defaults to calling {@link #createCacheView()}. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected MutableCacheView<VoiceState> createVoiceStateCacheView() { return createCacheView(); } /** * Creates a new cache view. Subclasses can override this method to * use a different cache view implementation. * * @param <T> Type of the elements to be held by this view. * * @return A new cache view. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected <T> MutableCacheView<T> createCacheView() { return new DefaultCacheView<>(); } /** * Creates a new named cache view. Subclasses can override this method to * use a different cache view implementation. * * @param <T> Type of the elements to be held by this view. * * @return A new named cache view. */ @SuppressWarnings("WeakerAccess") @Nonnull @CheckReturnValue protected <T> MutableNamedCacheView<T> createNamedCacheView(@Nonnull final Function<T, String> nameFunction) { return new DefaultNamedCacheView<>(nameFunction); } protected abstract MutableNamedCacheView<User> userCache(int shardId); protected abstract MutableCacheView<UserDMChannel> dmChannelCache(int shardId); protected abstract MutableCacheView<Presence> presenceCache(int shardId); @SuppressWarnings("WeakerAccess") protected MutableNamedCacheView<Guild> guildCache(final int shardId) { return guildCache; } @SuppressWarnings("WeakerAccess") protected MutableNamedCacheView<Member> memberCache(final long guildId, final boolean onlyGet) { return onlyGet ? memberCache.get(guildId) : memberCache.computeIfAbsent(guildId, __ -> createMemberCacheView()); } @SuppressWarnings("WeakerAccess") protected void deleteMemberCache(final long guildId) { memberCache.remove(guildId); } @SuppressWarnings("WeakerAccess") protected MutableNamedCacheView<Role> roleCache(final long guildId, final boolean onlyGet) { return onlyGet ? roleCache.get(guildId) : roleCache.computeIfAbsent(guildId, __ -> createRoleCacheView()); } @SuppressWarnings("WeakerAccess") protected void deleteRoleCache(final long guildId) { roleCache.remove(guildId); } @SuppressWarnings("WeakerAccess") protected MutableNamedCacheView<GuildChannel> channelCache(final long guildId, final boolean onlyGet) { return onlyGet ? guildChannelCache.get(guildId) : guildChannelCache.computeIfAbsent(guildId, __ -> createGuildChannelCacheView()); } @SuppressWarnings("WeakerAccess") protected void deleteChannelCache(final long guildId) { guildChannelCache.remove(guildId); } @SuppressWarnings("WeakerAccess") protected MutableNamedCacheView<CustomEmoji> emojiCache(final long guildId, final boolean onlyGet) { return onlyGet ? emojiCache.get(guildId) : emojiCache.computeIfAbsent(guildId, __ -> createEmojiCacheView()); } @SuppressWarnings("WeakerAccess") protected void deleteEmojiCache(final long guildId) { emojiCache.remove(guildId); } @SuppressWarnings("WeakerAccess") protected MutableCacheView<VoiceState> voiceStateCache(final long guildId, final boolean onlyGet) { return onlyGet ? voiceStateCache.get(guildId) : voiceStateCache.computeIfAbsent(guildId, __ -> createVoiceStateCacheView()); } @SuppressWarnings("WeakerAccess") protected void deleteVoiceStateCache(final long guildId) { voiceStateCache.remove(guildId); } // Man these """async""" methods are a joke. protected <I, T> Single<T> or(final I id, final T data, final T def) { if(data == null && def == null) { return Single.error(new IllegalArgumentException("No entity for: " + id)); } else { return Single.just(Objects.requireNonNullElse(data, def)); } } protected <I, T> Single<T> or(final I id, final T data) { if(data == null) { return Single.error(new IllegalArgumentException("No entity for: " + id)); } else { return Single.just(data); } } @Nonnull @Override public Single<Guild> guildAsync(final long id) { return or(id, guild(id)); } @Nonnull @Override public Single<User> userAsync(final long id) { return or(id, user(id)); } @Nonnull @Override public Single<Presence> presenceAsync(final long id) { return or(id, presence(id), DEFAULT_PRESENCE); } @Nonnull @Override public Single<Member> memberAsync(final long guildId, final long id) { return or(id, member(guildId, id)); } @Nonnull @Override public Single<Role> roleAsync(final long guildId, final long id) { return or(id, role(guildId, id)); } @Nonnull @Override public Single<GuildChannel> channelAsync(final long guildId, final long id) { return or(id, channel(guildId, id)); } @Nonnull @Override public Single<UserDMChannel> dmChannelAsync(final long id) { return or(id, dmChannel(id)); } @Nonnull @Override public Single<CustomEmoji> emojiAsync(final long guildId, final long id) { return or(id, emoji(guildId, id)); } @Nonnull @Override public Single<VoiceState> voiceStateAsync(final long guildId, final long id) { return or(id, voiceState(guildId, id)); } @Nonnull @Override public Single<User> selfUserAsync() { return or("self user", selfUser()); } protected int shardId(final long entityId) { return (int) ((entityId >> 22) % catnip.shardManager().shardCount()); } private void cacheRole(final Role role) { roleCache(role.guildIdAsLong(), false).put(role.idAsLong(), role); } private void cacheMember(final Member member) { memberCache(member.guildIdAsLong(), false).put(member.idAsLong(), member); } private void cacheEmoji(final CustomEmoji emoji) { emojiCache(emoji.guildIdAsLong(), false).put(emoji.idAsLong(), emoji); } @SuppressWarnings("DuplicateBranchesInSwitch") @Nonnull @Override public Completable updateCache(@Nonnull final String eventType, @Nonnegative final int shardId, @Nonnull final JsonObject payload) { switch(eventType) { // Lifecycle case Raw.READY: { selfUser.set(entityBuilder.createUser(payload.getObject("user"))); break; } // Channels case Raw.CHANNEL_CREATE: case Raw.CHANNEL_UPDATE: { final Channel channel = entityBuilder.createChannel(payload); if(channel.isGuild()) { final GuildChannel gc = (GuildChannel) channel; channelCache(gc.guildIdAsLong(), false).put(gc.idAsLong(), gc); } else if(channel.isUserDM()) { final UserDMChannel dm = (UserDMChannel) channel; dmChannelCache(shardId).put(dm.idAsLong(), dm); } else { catnip.logAdapter().warn("I don't know how to cache channel {}: isCategory={}, isDM={}, isGroupDM={}," + "isGuild={}, isText={}, isUserDM={}, isVoice={}", channel.idAsLong(), channel.isCategory(), channel.isDM(), channel.isGroupDM(), channel.isGuild(), channel.isText(), channel.isUserDM(), channel.isVoice()); } break; } case Raw.CHANNEL_DELETE: { final Channel channel = entityBuilder.createChannel(payload); if(channel.isGuild()) { final GuildChannel gc = (GuildChannel) channel; final MutableNamedCacheView<GuildChannel> channels = channelCache(gc.guildIdAsLong(), true); if(channels != null) { channels.remove(gc.idAsLong()); } } else if(channel.isUserDM()) { final UserDMChannel dm = (UserDMChannel) channel; dmChannelCache(shardId).remove(dm.userIdAsLong()); } else { catnip.logAdapter().warn("I don't know how to delete non-guild channel {}!", channel.idAsLong()); } break; } // Guilds case Raw.GUILD_CREATE: { final Guild guild = entityBuilder.createAndCacheGuild(shardId, payload); guildCache(shardId(guild.idAsLong())).put(guild.idAsLong(), guild); break; } case Raw.GUILD_UPDATE: { final Guild guild = entityBuilder.createGuild(payload); guildCache(shardId(guild.idAsLong())).put(guild.idAsLong(), guild); break; } case Raw.GUILD_DELETE: { final long guildId = Long.parseUnsignedLong(payload.getString("id")); guildCache(shardId(guildId)).remove(guildId); deleteMemberCache(guildId); deleteRoleCache(guildId); deleteChannelCache(guildId); deleteEmojiCache(guildId); deleteVoiceStateCache(guildId); break; } // Roles case Raw.GUILD_ROLE_CREATE: { final String guild = payload.getString("guild_id"); final JsonObject json = payload.getObject("role"); final Role role = entityBuilder.createRole(guild, json); cacheRole(role); break; } case Raw.GUILD_ROLE_UPDATE: { final String guild = payload.getString("guild_id"); final JsonObject json = payload.getObject("role"); final Role role = entityBuilder.createRole(guild, json); cacheRole(role); break; } case Raw.GUILD_ROLE_DELETE: { final String guild = payload.getString("guild_id"); final String role = payload.getString("role_id"); final MutableCacheView<Role> cache = roleCache(Long.parseUnsignedLong(guild), true); if(cache != null) { cache.remove(Long.parseUnsignedLong(role)); } break; } // Members case Raw.GUILD_MEMBER_ADD: { final Member member = entityBuilder.createMember(payload.getString("guild_id"), payload); final User user = entityBuilder.createUser(payload.getObject("user")); userCache(shardId).put(user.idAsLong(), user); cacheMember(member); break; } case Raw.GUILD_MEMBER_UPDATE: { // This doesn't send an object like all the other events, so we build a fake // payload object and create an entity from that final JsonObject user = payload.getObject("user"); final String id = user.getString("id"); final String guild = payload.getString("guild_id"); final Member old = member(guild, id); if(old != null) { @SuppressWarnings("ConstantConditions") final JsonObject data = JsonObject.builder() .value("user", user) .value("roles", payload.getArray("roles")) .value("nick", payload.getString("nick")) .value("deaf", old.deaf()) .value("mute", old.mute()) .value("joined_at", old.joinedAt() // If we have an old member cached, this shouldn't be an issue .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) .done(); final Member member = entityBuilder.createMember(guild, data); cacheMember(member); } else { catnip.logAdapter().warn("Got GUILD_MEMBER_UPDATE for {} in {}, but we don't have them cached?!", id, guild); } break; } case Raw.GUILD_MEMBER_REMOVE: { final String guild = payload.getString("guild_id"); final String user = payload.getObject("user").getString("id"); final MutableCacheView<Member> cache = memberCache(Long.parseUnsignedLong(guild), true); if(cache != null) { cache.remove(Long.parseUnsignedLong(user)); } break; } // Member chunking case Raw.GUILD_MEMBERS_CHUNK: { final String guild = payload.getString("guild_id"); final JsonArray members = payload.getArray("members"); members.stream().map(e -> entityBuilder.createMember(guild, (JsonObject) e)).forEach(this::cacheMember); break; } // Emojis case Raw.GUILD_EMOJIS_UPDATE: { if(!catnip.options().cacheFlags().contains(CacheFlag.DROP_EMOJI)) { final String guild = payload.getString("guild_id"); final JsonArray emojis = payload.getArray("emojis"); emojis.stream().map(e -> entityBuilder.createCustomEmoji(guild, (JsonObject) e)).forEach(this::cacheEmoji); } break; } // Currently-logged-in user case Raw.USER_UPDATE: { // Inner payload is always a user object, according to the // docs, so we can just outright replace it. selfUser.set(entityBuilder.createUser(payload)); break; } // Users case Raw.PRESENCE_UPDATE: { final JsonObject user = payload.getObject("user"); final String id = user.getString("id"); final User old = user(id); if(old == null && !catnip.options().chunkMembers() && catnip.options().logUncachedPresenceWhenNotChunking()) { catnip.logAdapter().warn("Received PRESENCE_UPDATE for uncached user {}!?", id); } else if(old != null) { // This could potentially update: // - username // - discriminator // - avatar // so we check the existing cache for a user, and update as needed final User updated = entityBuilder.createUser(JsonObject.builder() .value("id", id) .value("bot", old.bot()) .value("username", user.getString("username", old.username())) .value("discriminator", user.getString("discriminator", old.discriminator())) .value("avatar", user.getString("avatar", old.avatar())) .done() ); userCache(shardId).put(updated.idAsLong(), updated); if(!catnip.options().cacheFlags().contains(CacheFlag.DROP_GAME_STATUSES)) { final Presence presence = entityBuilder.createPresence(payload); presenceCache(shardId).put(updated.idAsLong(), presence); } } else if(catnip.options().chunkMembers()) { final String guildId = payload.getString("guild_id", "No guild"); catnip.logAdapter().warn("Received PRESENCE_UPDATE for unknown user {} (guild: {})!? (member chunking enabled)", id, guildId); } break; } // Voice case Raw.VOICE_STATE_UPDATE: { if(!catnip.options().cacheFlags().contains(CacheFlag.DROP_VOICE_STATES)) { final VoiceState state = entityBuilder.createVoiceState(payload); cacheVoiceState(state); } break; } } // Default case; most events don't need to have special future cases return RxHelpers.completedCompletable(catnip); } private void cacheVoiceState(final VoiceState state) { final long guild = state.guildIdAsLong(); if(guild == 0) { catnip.logAdapter().warn("Not caching voice state for {} due to null guild", state.userIdAsLong()); return; } voiceStateCache(guild, false).put(state.userIdAsLong(), state); } @Override public void bulkCacheUsers(@Nonnegative final int shardId, @Nonnull final Collection<User> users) { final MutableCacheView<User> cache = userCache(shardId); users.forEach(u -> cache.put(u.idAsLong(), u)); } @Override public void bulkCacheChannels(@Nonnegative final int shardId, @Nonnull final Collection<GuildChannel> channels) { channels.forEach(gc -> channelCache(gc.guildIdAsLong(), false).put(gc.idAsLong(), gc)); } @Override public void bulkCacheRoles(@Nonnegative final int shardId, @Nonnull final Collection<Role> roles) { roles.forEach(this::cacheRole); } @Override public void bulkCacheMembers(@Nonnegative final int shardId, @Nonnull final Collection<Member> members) { members.forEach(this::cacheMember); } @Override public void bulkCacheEmoji(@Nonnegative final int shardId, @Nonnull final Collection<CustomEmoji> emoji) { emoji.forEach(this::cacheEmoji); } @Override public void bulkCachePresences(@Nonnegative final int shardId, @Nonnull final Map<String, Presence> presences) { final MutableCacheView<Presence> cache = presenceCache(shardId); presences.forEach((id, presence) -> cache.put(Long.parseUnsignedLong(id), presence)); } @Override public void bulkCacheVoiceStates(@Nonnegative final int shardId, @Nonnull final Collection<VoiceState> voiceStates) { voiceStates.forEach(this::cacheVoiceState); } @Override public void invalidateShard(final int id) { final int shardCount = catnip().shardManager().shardCount(); final LongPredicate predicate = entityId -> (entityId >> 22) % shardCount == id; removeIf(memberCache, predicate); removeIf(roleCache, predicate); removeIf(guildChannelCache, predicate); removeIf(emojiCache, predicate); removeIf(voiceStateCache, predicate); } @Nullable @Override public Guild guild(final long id) { return guildCache(shardId(id)).getById(id); } @Nonnull @Override public NamedCacheView<Guild> guilds() { return guildCache; } @Nullable @Override public Member member(final long guildId, final long id) { final MutableNamedCacheView<Member> cache = memberCache(guildId, true); return cache == null ? null : cache.getById(id); } @Nonnull @Override public NamedCacheView<Member> members(final long guildId) { final MutableNamedCacheView<Member> cache = memberCache(guildId, true); return cache == null ? CacheView.noop() : cache; } @Nonnull @Override public NamedCacheView<Member> members() { return new CompositeNamedCacheView<>(memberCache.values(), memberNameFunction()); } @Nullable @Override public Role role(final long guildId, final long id) { final MutableNamedCacheView<Role> cache = roleCache(guildId, true); return cache == null ? null : cache.getById(id); } @Nonnull @Override public NamedCacheView<Role> roles(final long guildId) { final MutableNamedCacheView<Role> cache = roleCache(guildId, true); return cache == null ? CacheView.noop() : cache; } @Nonnull @Override public NamedCacheView<Role> roles() { return new CompositeNamedCacheView<>(roleCache.values(), Role::name); } @Nullable @Override public GuildChannel channel(final long guildId, final long id) { final MutableNamedCacheView<GuildChannel> cache = channelCache(guildId, true); return cache == null ? null : cache.getById(id); } @Nonnull @Override public NamedCacheView<GuildChannel> channels(final long guildId) { final MutableNamedCacheView<GuildChannel> cache = channelCache(guildId, true); return cache == null ? CacheView.noop() : cache; } @Nonnull @Override public NamedCacheView<GuildChannel> channels() { return new CompositeNamedCacheView<>(guildChannelCache.values(), GuildChannel::name); } @Nullable @Override public CustomEmoji emoji(final long guildId, final long id) { final MutableNamedCacheView<CustomEmoji> cache = emojiCache(guildId, true); return cache == null ? null : cache.getById(id); } @Nonnull @Override public NamedCacheView<CustomEmoji> emojis(final long guildId) { final MutableNamedCacheView<CustomEmoji> cache = emojiCache(guildId, true); return cache == null ? CacheView.noop() : cache; } @Nonnull @Override public NamedCacheView<CustomEmoji> emojis() { return new CompositeNamedCacheView<>(emojiCache.values(), CustomEmoji::name); } @Nullable @Override public VoiceState voiceState(final long guildId, final long id) { final MutableCacheView<VoiceState> cache = voiceStateCache(guildId, true); return cache == null ? null : cache.getById(id); } @Nonnull @Override public CacheView<VoiceState> voiceStates(final long guildId) { final MutableCacheView<VoiceState> cache = voiceStateCache(guildId, true); return cache == null ? CacheView.noop() : cache; } @Nonnull @Override public CacheView<VoiceState> voiceStates() { return new CompositeCacheView<>(voiceStateCache.values()); } @Nullable @Override public User selfUser() { return selfUser.get(); } @Nonnull @Override public EntityCache catnip(@Nonnull final Catnip catnip) { this.catnip = catnip; entityBuilder = new EntityBuilder(catnip); return this; } }
/* * Copyright 2008-2011 Grant Ingersoll, Thomas Morton and Drew Farris * * 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. * ------------------- * To purchase or learn more about Taming Text, by Grant Ingersoll, Thomas Morton and Drew Farris, visit * http://www.manning.com/ingersoll */ package com.tamingtext.opennlp; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import opennlp.tools.postag.POSModel; import opennlp.tools.postag.POSTaggerME; import opennlp.tools.tokenize.SimpleTokenizer; import org.junit.Test; import com.tamingtext.TamingTextTestJ4; /** * Place the OpenNLP English models (http://opennlp.sourceforge.net/models.html) in a directory and define the System property "models.dir" to point to that directory. * Alternatively, create a directory as a sibling of the Taming Text project named opennlp-tools-1.3.0 and place the models directory in there. */ public class POSTaggerTest extends TamingTextTestJ4 { @Test public void test() throws IOException { //<start id="opennlpPOS"/> File posModelFile = new File( //<co id="opennlpPOS.co.tagger"/> getModelDir(), "en-pos-maxent.bin"); FileInputStream posModelStream = new FileInputStream(posModelFile); POSModel model = new POSModel(posModelStream); POSTaggerME tagger = new POSTaggerME(model); String[] words = SimpleTokenizer.INSTANCE.tokenize( //<co id="opennlpPOS.co.tokenize"/> "The quick, red fox jumped over the lazy, brown dogs."); String[] result = tagger.tag(words);//<co id="opennlpPOS.co.dotag"/> for (int i=0 ; i < words.length; i++) { System.err.print(words[i] + "/" + result[i] + " "); } System.err.println("\n"); /* <calloutlist> <callout arearefs="opennlpPOS.co.tagger"><para>Give the path to the POS Model</para></callout> <callout arearefs="opennlpPOS.co.tokenize"><para>Tokenize the sentence into words</para></callout> <callout arearefs="opennlpPOS.co.dotag"><para>Pass in a tokenized sentence to be tagged.</para></callout> </calloutlist> */ //<end id="opennlpPOS"/> } }
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.kie.dmn.feel.codegen.feel11; import java.math.BigDecimal; import java.math.MathContext; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import ch.obermuhlner.math.big.BigDecimalMath; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.body.FieldDeclaration; import com.github.javaparser.ast.body.Parameter; import com.github.javaparser.ast.body.VariableDeclarator; import com.github.javaparser.ast.expr.BooleanLiteralExpr; import com.github.javaparser.ast.expr.LambdaExpr; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.stmt.BlockStmt; import com.github.javaparser.ast.stmt.ExpressionStmt; import com.github.javaparser.ast.stmt.ReturnStmt; import com.github.javaparser.ast.stmt.Statement; import com.github.javaparser.ast.type.UnknownType; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity; import org.kie.dmn.api.feel.runtime.events.FEELEventListener; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.ast.ForExpressionNode; import org.kie.dmn.feel.lang.ast.ForExpressionNode.ForIteration; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode.QEIteration; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode.Quantifier; import org.kie.dmn.feel.lang.impl.SilentWrappingEvaluationContextImpl; import org.kie.dmn.feel.lang.types.BuiltInType; import org.kie.dmn.feel.runtime.FEELFunction; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.UnaryTest; import org.kie.dmn.feel.runtime.events.ASTEventBase; import org.kie.dmn.feel.runtime.events.InvalidParametersEvent; import org.kie.dmn.feel.runtime.events.SyntaxErrorEvent; import org.kie.dmn.feel.util.EvalHelper; import org.kie.dmn.feel.util.Msg; import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType; import static org.kie.dmn.feel.codegen.feel11.Expressions.compiledFeelSemanticMappingsFQN; public class CompiledFEELSupport { public static ContextBuilder openContext(EvaluationContext ctx) { return new ContextBuilder(ctx); } public static class ContextBuilder { private Map<String, Object> resultContext = new HashMap<>(); private EvaluationContext evaluationContext; public ContextBuilder(EvaluationContext evaluationContext) { this.evaluationContext = evaluationContext; evaluationContext.enterFrame(); } public ContextBuilder setEntry(String key, Object value) { resultContext.put(key, value); evaluationContext.setValue(key, value); return this; } public Map<String, Object> closeContext() { evaluationContext.exitFrame(); return resultContext; } } public static FilterBuilder filter(EvaluationContext ctx, Object value) { return new FilterBuilder(ctx, value); } public static class FilterBuilder { private EvaluationContext ctx; private Object value; public FilterBuilder(EvaluationContext evaluationContext, Object value) { this.ctx = evaluationContext; this.value = value; } public Object with(Function<EvaluationContext, Object> filterExpression) { if (value == null) { return null; } List list = value instanceof List ? (List) value : Arrays.asList(value); Object f = filterExpression.apply( new SilentWrappingEvaluationContextImpl(ctx)); // I need to try evaluate filter first, ignoring errors; only if evaluation fails, or is not a Number, it delegates to try `evaluateExpressionsInContext` if (f instanceof Number) { return withIndex(f); } List results = new ArrayList(); for (Object v : list) { try { ctx.enterFrame(); // handle it as a predicate // Have the "item" variable set first, so to respect the DMN spec: The expression in square brackets can reference a list // element using the name item, unless the list element is a context that contains the key "item". ctx.setValue("item", v); // using Root object logic to avoid having to eagerly inspect all attributes. ctx.setRootObject(v); // Alignment to FilterExpressionNode: // a filter would always return a list with all the elements for which the filter is true. // In case any element fails in there or the filter expression returns null, it will only exclude the element, but will continue to process the list. // In case all elements fail, the result will be an empty list. Object r = filterExpression.apply(new SilentWrappingEvaluationContextImpl(ctx)); if (r instanceof Boolean && r == Boolean.TRUE) { results.add(v); } } catch (Exception e) { ctx.notifyEvt(() -> new ASTEventBase(Severity.ERROR, Msg.createMessage(Msg.ERROR_EXECUTING_LIST_FILTER, filterExpression), null, e)); return null; } finally { ctx.exitFrame(); } } return results; } private Object withIndex(Object filterIndex) { if (value == null) { return null; } List list = value instanceof List ? (List) value : Arrays.asList(value); if (filterIndex instanceof Number) { int i = ((Number) filterIndex).intValue(); if (i > 0 && i <= list.size()) { return list.get(i - 1); } else if (i < 0 && Math.abs(i) <= list.size()) { return list.get(list.size() + i); } else { ctx.notifyEvt(() -> new ASTEventBase(Severity.WARN, Msg.createMessage(Msg.INDEX_OUT_OF_BOUND, list.size(), i), null)); return null; } } else if (filterIndex == null) { return Collections.emptyList(); } else { ctx.notifyEvt(() -> new ASTEventBase(Severity.ERROR, Msg.createMessage(Msg.ERROR_EXECUTING_LIST_FILTER, filterIndex), null)); return null; } } } public static PathBuilder path(EvaluationContext ctx, Object value) { return new PathBuilder(ctx, value); } public static class PathBuilder { private EvaluationContext ctx; private Object o; public PathBuilder(EvaluationContext evaluationContext, Object value) { this.ctx = evaluationContext; this.o = value; } public Object with(final String... names) { if (o instanceof List) { List list = (List) o; // list of contexts/elements as defined in the spec, page 114 List results = new ArrayList(); for (Object element : list) { Object r = fetchValue(element, names); if (r != null) { results.add(r); } } return results; } else { return fetchValue(o, names); } } private Object fetchValue(final Object o, final String... names) { Object result = o; for (String nr : names) { result = EvalHelper.getDefinedValue(result, nr) .getValueResult() .cata(err -> { // no need to report error here, eg: [ {x:1, y:2}, {x:2} ].y results in [2] with no errors. return null; }, Function.identity()); } return result; } } public static ForBuilder ffor(EvaluationContext ctx) { return new ForBuilder(ctx); } public static class ForBuilder { private EvaluationContext ctx; private List<IterationContextCompiled> iterationContexts = new ArrayList<>(); public ForBuilder(EvaluationContext evaluationContext) { this.ctx = evaluationContext; } public ForBuilder with(Function<EvaluationContext, Object> nameExpression, Function<EvaluationContext, Object> iterationExpression) { iterationContexts.add(new IterationContextCompiled(nameExpression, iterationExpression)); return this; } public ForBuilder with(Function<EvaluationContext, Object> nameExpression, Function<EvaluationContext, Object> iterationExpression, Function<EvaluationContext, Object> rangeEndExpression) { iterationContexts.add(new IterationContextCompiled(nameExpression, iterationExpression, rangeEndExpression)); return this; } public Object rreturn(Function<EvaluationContext, Object> expression) { try { ctx.enterFrame(); List results = new ArrayList(); ctx.setValue("partial", results); ForIteration[] ictx = initializeContexts(ctx, iterationContexts); while (ForExpressionNode.nextIteration(ctx, ictx)) { Object result = expression.apply(ctx); results.add(result); } return results; } catch (EndpointOfRangeNotOfNumberException e) { // ast error already reported return null; } finally { ctx.exitFrame(); } } private ForIteration[] initializeContexts(EvaluationContext ctx, List<IterationContextCompiled> iterationContexts) { ForIteration[] ictx = new ForIteration[iterationContexts.size()]; int i = 0; for (IterationContextCompiled icn : iterationContexts) { ictx[i] = createQuantifiedExpressionIterationContext(ctx, icn); if (i < iterationContexts.size() - 1 && ictx[i].hasNextValue()) { ForExpressionNode.setValueIntoContext(ctx, ictx[i]); } i++; } return ictx; } private ForIteration createQuantifiedExpressionIterationContext(EvaluationContext ctx, IterationContextCompiled icn) { ForIteration fi = null; String name = (String) icn.getName().apply(ctx); Object result = icn.getExpression().apply(ctx); Object rangeEnd = icn.getRangeEndExpr().apply(ctx); if (rangeEnd == null) { Iterable values = result instanceof Iterable ? (Iterable) result : Collections.singletonList(result); fi = new ForIteration(name, values); } else { valueMustBeANumber(ctx, result); BigDecimal start = (BigDecimal) result; valueMustBeANumber(ctx, rangeEnd); BigDecimal end = (BigDecimal) rangeEnd; fi = new ForIteration(name, start, end); } return fi; } private void valueMustBeANumber(EvaluationContext ctx, Object value) { if (!(value instanceof BigDecimal)) { ctx.notifyEvt(() -> new ASTEventBase(Severity.ERROR, Msg.createMessage(Msg.VALUE_X_NOT_A_VALID_ENDPOINT_FOR_RANGE_BECAUSE_NOT_A_NUMBER, value), null)); throw new EndpointOfRangeNotOfNumberException(); } } private static class EndpointOfRangeNotOfNumberException extends RuntimeException { private static final long serialVersionUID = 1L; } } public static class IterationContextCompiled { private final Function<EvaluationContext, Object> name; private final Function<EvaluationContext, Object> expression; private final Function<EvaluationContext, Object> rangeEndExpr; public IterationContextCompiled(Function<EvaluationContext, Object> name, Function<EvaluationContext, Object> expression) { this.name = name; this.expression = expression; this.rangeEndExpr = (ctx) -> null; } public IterationContextCompiled(Function<EvaluationContext, Object> name, Function<EvaluationContext, Object> expression, Function<EvaluationContext, Object> rangeEndExpr) { this.name = name; this.expression = expression; this.rangeEndExpr = rangeEndExpr; } public Function<EvaluationContext, Object> getName() { return name; } public Function<EvaluationContext, Object> getExpression() { return expression; } public Function<EvaluationContext, Object> getRangeEndExpr() { return rangeEndExpr; } } public static QuantBuilder quant(Quantifier quantOp, EvaluationContext ctx) { return new QuantBuilder(quantOp, ctx); } public static class QuantBuilder { private Quantifier quantOp; private EvaluationContext ctx; private List<IterationContextCompiled> iterationContexts = new ArrayList<>(); public QuantBuilder(Quantifier quantOp, EvaluationContext evaluationContext) { this.quantOp = quantOp; this.ctx = evaluationContext; } public QuantBuilder with(Function<EvaluationContext, Object> nameExpression, Function<EvaluationContext, Object> iterationExpression) { iterationContexts.add(new IterationContextCompiled(nameExpression, iterationExpression)); return this; } public Object satisfies(Function<EvaluationContext, Object> expression) { if (quantOp == Quantifier.SOME || quantOp == Quantifier.EVERY) { return iterateContexts(ctx, iterationContexts, expression, quantOp); } // can never happen, but anyway: ctx.notifyEvt(() -> new ASTEventBase(Severity.ERROR, Msg.createMessage(Msg.IS_NULL, "Quantifier"), null)); return null; } private Boolean iterateContexts(EvaluationContext ctx, List<IterationContextCompiled> iterationContexts, Function<EvaluationContext, Object> expression, Quantifier quantifier) { try { ctx.enterFrame(); QEIteration[] ictx = initializeContexts(ctx, iterationContexts); while (QuantifiedExpressionNode.nextIteration(ctx, ictx)) { Boolean result = (Boolean) expression.apply(ctx); if (result != null && result.equals(quantifier.positiveTest())) { return quantifier.positiveTest(); } } return quantifier.defaultValue(); } finally { ctx.exitFrame(); } } private QEIteration[] initializeContexts(EvaluationContext ctx, List<IterationContextCompiled> iterationContexts) { QEIteration[] ictx = new QEIteration[iterationContexts.size()]; int i = 0; for (IterationContextCompiled icn : iterationContexts) { ictx[i] = createQuantifiedExpressionIterationContext(ctx, icn); if (i < ictx.length - 1) { // initalize all contexts except the very last one, as it will be initialized in the nextIteration() method QuantifiedExpressionNode.setValueIntoContext(ctx, ictx[i]); } i++; } return ictx; } private QEIteration createQuantifiedExpressionIterationContext(EvaluationContext ctx, IterationContextCompiled icn) { String name = (String) icn.getName().apply(ctx); Object result = icn.getExpression().apply(ctx); Iterable values = result instanceof Iterable ? (Iterable) result : Collections.singletonList(result); QEIteration qei = new QEIteration(name, values); return qei; } } public static Object invoke(EvaluationContext feelExprCtx, Object function, Object params) { if (function == null) { feelExprCtx.notifyEvt(() -> new ASTEventBase(Severity.ERROR, Msg.createMessage(Msg.FUNCTION_NOT_FOUND, function), null)); return null; } if (function instanceof FEELFunction) { Object[] invocationParams = toFunctionParams(params); FEELFunction f = (FEELFunction) function; if (function instanceof CompiledCustomFEELFunction) { CompiledCustomFEELFunction ff = (CompiledCustomFEELFunction) function; if (ff.isProperClosure()) { return ff.invokeReflectively(ff.getEvaluationContext(), invocationParams); } } return f.invokeReflectively(feelExprCtx, invocationParams); } else if (function instanceof UnaryTest) { return ((UnaryTest) function).apply(feelExprCtx, ((List)params).get(0)); } else if (function instanceof Range) { // alignment to FunctionInvocationNode List<?> ps = (List<?>) params; if (ps.size() == 1) { return ((Range) function).includes(ps.get(0)); } else { feelExprCtx.notifyEvt(() -> new ASTEventBase(Severity.ERROR, Msg.createMessage(Msg.CAN_T_INVOKE_AN_UNARY_TEST_WITH_S_PARAMETERS_UNARY_TESTS_REQUIRE_1_SINGLE_PARAMETER, ps.size()), null)); } } return null; } private static Object[] toFunctionParams(Object params) { Object[] invocationParams = null; if (params instanceof List) { invocationParams = ((List) params).toArray(new Object[]{}); } else if (params instanceof Object[]) { invocationParams = (Object[]) params; } else { invocationParams = new Object[]{params}; } return invocationParams; } public static Object notifyCompilationError(EvaluationContext feelExprCtx, String message) { feelExprCtx.notifyEvt(() -> new ASTEventBase(Severity.ERROR, message, null)); return null; } public static Object coerceNumber(Object value) { return EvalHelper.coerceNumber(value); } /** * Generates a compilable class that reports a (compile-time) error at runtime */ public static CompiledFEELExpression compiledError(String expression, String msg) { return new CompilerBytecodeLoader() .makeFromJPExpression( expression, compiledErrorExpression(msg), Collections.emptySet()); } public static DirectCompilerResult compiledErrorUnaryTest(String msg) { LambdaExpr initializer = new LambdaExpr(); initializer.setEnclosingParameters(true); initializer.addParameter(new Parameter(new UnknownType(), "feelExprCtx")); initializer.addParameter(new Parameter(new UnknownType(), "left")); Statement lambdaBody = new BlockStmt(new NodeList<>( new ExpressionStmt(compiledErrorExpression(msg)), new ReturnStmt(new BooleanLiteralExpr(false)) )); initializer.setBody(lambdaBody); String constantName = "UT_EMPTY"; VariableDeclarator vd = new VariableDeclarator(parseClassOrInterfaceType(UnaryTest.class.getCanonicalName()), constantName); vd.setInitializer(initializer); FieldDeclaration fd = new FieldDeclaration(); fd.setModifier(Modifier.publicModifier().getKeyword(), true); fd.setModifier(Modifier.staticModifier().getKeyword(), true); fd.setModifier(Modifier.finalModifier().getKeyword(), true); fd.addVariable(vd); fd.setJavadocComment(" FEEL unary test: - "); MethodCallExpr list = new MethodCallExpr(compiledFeelSemanticMappingsFQN(), "list", new NodeList<>(new NameExpr(constantName))); DirectCompilerResult directCompilerResult = DirectCompilerResult.of(list, BuiltInType.LIST); directCompilerResult.addFieldDeclaration(fd); return directCompilerResult; } public static MethodCallExpr compiledErrorExpression(String msg) { return new MethodCallExpr( new NameExpr("CompiledFEELSupport"), "notifyCompilationError", new NodeList<>( new NameExpr("feelExprCtx"), Expressions.stringLiteral(msg))); } // thread-unsafe, but this is single-threaded so it's ok public static class SyntaxErrorListener implements FEELEventListener { private FEELEvent event = null; @Override public void onEvent(FEELEvent evt) { if (evt instanceof SyntaxErrorEvent || evt instanceof InvalidParametersEvent) { this.event = evt; } } public boolean isError() { return event != null; } public FEELEvent event() { return event; } } public static BigDecimal pow(BigDecimal l, BigDecimal r) { return BigDecimalMath.pow( l, r, MathContext.DECIMAL128 ); } }
package com.mangooa.tools.core.util; import java.util.UUID; /** * 唯一标识生成器工具类,如:UUID、ObjectId(MongoDB)。 * * @author Weimin Gao * @since 1.0.0 **/ @SuppressWarnings("unused") public class IdUtils { /** * 生成随机的通用唯一识别码(Universally Unique Identifier)。 * * @return 唯一识别码。 */ public static String randomUuid() { return UUID.randomUUID().toString(); } /** * 生成随机的通用唯一识别码(Universally Unique Identifier),并去掉了横线。 * * @return 简化的UUID,去掉了横线。 */ public static String simpleUuid() { return UUID.randomUUID().toString().replaceAll("-", ""); } /** * 创建一个唯一标识(MongoDB生成策略实现)。 * * @return 唯一标识。 */ public static String objectId() { return ObjectId.get().toHexString(); } }
package mitzi; /** * The flags for the entries in the Transposition Table (PositionCache). * */ public enum Flag { EXACT, LOWERBOUND, UPPERBOUND }
/******************************************************************************* * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.internal.identitymaps; import java.util.*; import java.io.*; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.exceptions.QueryException; import org.eclipse.persistence.internal.helper.*; import org.eclipse.persistence.internal.sessions.AbstractSession; /** * <p><b>Purpose</b>: Caches objects, and allows their retrieval by their primary key. * <p><b>Responsibilities</b>:<ul> * <li> Store CacheKeys containing objects and possibly writeLockValues. * <li> Insert & retrieve objects from the cache. * <li> Allow retrieval and modification of writeLockValue for a cached object. * </ul> * @see CacheKey * @since TOPLink/Java 1.0 */ public abstract class AbstractIdentityMap implements IdentityMap, Serializable, Cloneable { /** The initial or maximum size of the cache depending upon the concrete implementation. */ protected int maxSize; /** PERF: Store the descriptor to allow lastAccessed cache lookup optimization. */ protected transient ClassDescriptor descriptor; /** Is this identity map within an IsolatedClientSession */ protected boolean isIsolated; /** Session that the map is on */ protected AbstractSession session; public AbstractIdentityMap(){ } /** * Instantiate an new IdentityMap with it's maximum size.<p> * <b>NOTE</b>: Subclasses may provide different behavior for maxSize. * @param size is the maximum size to be allocated for the receiver. */ public AbstractIdentityMap(int size, ClassDescriptor descriptor, AbstractSession session, boolean isolated) { this.maxSize = size; this.descriptor = descriptor; this.isIsolated = isolated; this.session = session; } /** * Acquire a deferred lock on the object. * This is used while reading if the object has relationships without indirection. * This first thread will get an active lock. * Other threads will get deferred locks, all threads will wait until all other threads are complete before releasing their locks. */ @Override public CacheKey acquireDeferredLock(Object primaryKey, boolean isCacheCheckComplete) { CacheKey cacheKey = getCacheKey(primaryKey, false); if (cacheKey == null) { // Create and lock a new cacheKey. CacheKey newCacheKey = createCacheKey(primaryKey, null, null, 0); newCacheKey.acquireDeferredLock(); // PERF: To avoid synchronization, getIfAbsentPut is used. cacheKey = putCacheKeyIfAbsent(newCacheKey); // Return if the newCacheKey was put as it was already locked, otherwise must still lock it. if (cacheKey == null) { return newCacheKey; } else { newCacheKey.releaseDeferredLock(); } } // Acquire a lock on the cache key. cacheKey.acquireDeferredLock(); return cacheKey; } /** * Acquire an active lock on the object. * This is used by reading (when using indirection or no relationships) and by merge. */ @Override public CacheKey acquireLock(Object primaryKey, boolean forMerge, boolean isCacheCheckComplete) { CacheKey cacheKey = getCacheKey(primaryKey, forMerge); if (cacheKey == null) { // Create and lock a new cacheKey. CacheKey newCacheKey = createCacheKey(primaryKey, null, null, 0); newCacheKey.acquire(forMerge); // PERF: To avoid synchronization, getIfAbsentPut is used. cacheKey = putCacheKeyIfAbsent(newCacheKey); // Return if the newCacheKey was put as it was already locked, otherwise must still lock it. if (cacheKey == null) { return newCacheKey; } else { newCacheKey.release(); } } // Acquire a lock on the cache key. cacheKey.acquire(); return cacheKey; } /** * Acquire an active lock on the object, if not already locked. * This is used by merge for missing existing objects. */ @Override public CacheKey acquireLockNoWait(Object primaryKey, boolean forMerge) { CacheKey cacheKey = getCacheKey(primaryKey, forMerge); if (cacheKey == null) { // Create and lock a new cacheKey. CacheKey newCacheKey = createCacheKey(primaryKey, null, null, 0); newCacheKey.acquire(forMerge); // PERF: To avoid synchronization, getIfAbsentPut is used. cacheKey = putCacheKeyIfAbsent(newCacheKey); // Return if the newCacheKey was put as already lock, otherwise must still lock. if (cacheKey == null) { return newCacheKey; } else { newCacheKey.release(); } } // Acquire a lock on the cache key. // Return null if already locked. if (!cacheKey.acquireNoWait(forMerge)) { return null; } return cacheKey; } /** * Acquire an active lock on the object, if not already locked. * This is used by merge for missing existing objects. */ @Override public CacheKey acquireLockWithWait(Object primaryKey, boolean forMerge, int wait) { CacheKey cacheKey = getCacheKey(primaryKey, forMerge); if (cacheKey == null) { // Create and lock a new cacheKey. CacheKey newCacheKey = createCacheKey(primaryKey, null, null, 0); newCacheKey.acquire(forMerge); // PERF: To avoid synchronization, getIfAbsentPut is used. cacheKey = putCacheKeyIfAbsent(newCacheKey); // Return if the newCacheKey was put as already lock, otherwise must still lock. if (cacheKey == null) { return newCacheKey; } else { newCacheKey.release(); } } // Acquire a lock on the cache key. // Return null if already locked. if (!cacheKey.acquireWithWait(forMerge, wait)) { return null; } return cacheKey; } /** * Acquire a read lock on the object. * This is used by UnitOfWork cloning. * This will allow multiple users to read the same object but prevent writes to the object while the read lock is held. */ @Override public CacheKey acquireReadLockOnCacheKey(Object primaryKey) { CacheKey cacheKey = getCacheKey(primaryKey, false); if (cacheKey == null) { CacheKey newCacheKey = createCacheKey(primaryKey, null, null, 0); // Lock new cacheKey. newCacheKey.acquireReadLock(); // Create one but not put it in the cache, as we are only reading // and should not be writing to the identitymap. return newCacheKey; } // Acquire a lock on the cache key. // Return null if already locked. cacheKey.acquireReadLock(); return cacheKey; } /** * Acquire a read lock on the object, if not already locked. * This is used by UnitOfWork cloning. * This will allow multiple users to read the same object but prevent writes to the object while the read lock is held. */ @Override public CacheKey acquireReadLockOnCacheKeyNoWait(Object primaryKey) { CacheKey cacheKey = getCacheKey(primaryKey, false); if (cacheKey == null) { CacheKey newCacheKey = createCacheKey(primaryKey, null, null, 0); // Lock new cacheKey. newCacheKey.acquireReadLock(); // Create one but not put it in the cache, as we are only reading // and should not be writing to the identitymap. return newCacheKey; } // Acquire a lock on the cache key. // Return null if already locked. if (!cacheKey.acquireReadLockNoWait()) { return null; } return cacheKey; } /** * Add all locked CacheKeys to the map grouped by thread. * Used to print all the locks in the identity map. */ @Override public abstract void collectLocks(HashMap threadList); /** * Clone the map and all of the CacheKeys. * This is used by UnitOfWork commitAndResumeOnFailure to avoid corrupting the cache during a failed commit. */ @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException exception) { throw new InternalError(exception.toString()); } } /** * Return true if an CacheKey with the primary key is in the map. * User API. * @param primaryKey is the primary key for the object to search for. */ @Override public boolean containsKey(Object primaryKey) { return getCacheKeyWithReadLock(primaryKey) != null; } /** * Create the correct type of CacheKey for this map. */ public CacheKey createCacheKey(Object primaryKey, Object object, Object writeLockValue, long readTime) { return new CacheKey(primaryKey, object, writeLockValue, readTime, this.isIsolated); } /** * Allow for the cache to be iterated on. */ @Override public abstract Enumeration elements(); /** * Return the object cached in the identity map or null if it could not be found. * User API. */ @Override public Object get(Object primaryKey) { CacheKey cacheKey = getCacheKeyWithReadLock(primaryKey); if (cacheKey == null) { return null; } return cacheKey.getObject(); } /** * ADVANCED: * Using a list of Entity PK this method will attempt to bulk load the entire list from the cache. * In certain circumstances this can have large performance improvements over loading each item individually. * @param pkList List of Entity PKs to extract from the cache * @param ClassDescriptor Descriptor type to be retrieved. * @return Map of Entity PKs associated to the Entities that were retrieved * @throws QueryException */ @Override public Map<Object, Object> getAllFromIdentityMapWithEntityPK(Object[] pkList, ClassDescriptor descriptor, AbstractSession session){ HashMap<Object, Object> map = new HashMap<Object, Object>(); CacheKey cachedObject = null; long currentTime = System.currentTimeMillis(); for (Object pk : pkList){ cachedObject = getCacheKey(pk, false); if ((cachedObject != null && cachedObject.getObject() != null && !descriptor.getCacheInvalidationPolicy().isInvalidated(cachedObject, currentTime))){ map.put(pk, cachedObject.getObject()); } } return map; } /** * ADVANCED: * Using a list of Entity PK this method will attempt to bulk load the entire list from the cache. * In certain circumstances this can have large performance improvements over loading each item individually. * @param pkList List of Entity PKs to extract from the cache * @param ClassDescriptor Descriptor type to be retrieved. * @return Map of Entity PKs associated to the Entities that were retrieved * @throws QueryException */ @Override public Map<Object, CacheKey> getAllCacheKeysFromIdentityMapWithEntityPK(Object[] pkList, ClassDescriptor descriptor, AbstractSession session){ HashMap<Object, CacheKey> map = new HashMap<Object, CacheKey>(); CacheKey cachedObject = null; long currentTime = System.currentTimeMillis(); for (Object pk : pkList){ cachedObject = getCacheKey(pk, false); if ((cachedObject != null && cachedObject.getObject() != null && !descriptor.getCacheInvalidationPolicy().isInvalidated(cachedObject, currentTime))){ map.put(pk, cachedObject); } } return map; } /** * Get the cache key (with object) for the primary key. */ @Override public abstract CacheKey getCacheKey(Object primaryKey, boolean forMerge); /** * Get the cache key (with object) for the primary key. */ @Override public CacheKey getCacheKeyForLock(Object primaryKey) { return getCacheKey(primaryKey, true); } /** * Return the CacheKey (with object) matching the searchKey. * If the CacheKey is missing then put the searchKey in the map. * The searchKey should have already been locked. */ protected abstract CacheKey putCacheKeyIfAbsent(CacheKey cacheKey); /** * Get the cache key (with object) for the primary key with read lock. */ protected CacheKey getCacheKeyWithReadLock(Object primaryKey) { CacheKey key = getCacheKey(primaryKey, false); if (key != null) { key.checkReadLock(); } return key; } /** * Returns the class which should be used as an identity map in a descriptor by default. */ public static Class getDefaultIdentityMapClass() { return ClassConstants.SoftCacheWeakIdentityMap_Class; } /** * @return The maxSize for the IdentityMap (NOTE: some subclasses may use this differently). */ @Override public int getMaxSize() { if (maxSize == -1) { maxSize = 100; } return maxSize; } /** * Return the number of CacheKeys in the IdentityMap. * This may contain weak referenced objects that have been garbage collected. */ @Override public abstract int getSize(); /** * Return the number of actual objects of type myClass in the IdentityMap. * Recurse = true will include subclasses of myClass in the count. */ @Override public abstract int getSize(Class myClass, boolean recurse); /** * Get the wrapper object from the cache key associated with the given primary key, * this is used for EJB2. */ @Override public Object getWrapper(Object primaryKey) { CacheKey cacheKey = getCacheKeyWithReadLock(primaryKey); if (cacheKey == null) { return null; } else { return cacheKey.getWrapper(); } } /** * Get the write lock value from the cache key associated to the primarykey. * User API. */ @Override public Object getWriteLockValue(Object primaryKey) { CacheKey cacheKey = getCacheKeyWithReadLock(primaryKey); if (cacheKey == null) { return null; } else { return cacheKey.getWriteLockValue(); } } /** * Allow for the CacheKeys to be iterated on. */ @Override public abstract Enumeration keys(); /** * Store the object in the cache at its primary key. * This is used by InsertObjectQuery, typically into the UnitOfWork identity map. * Merge and reads do not use put, but acquireLock. * Also an advanced (very) user API. * @param primaryKey is the primary key for the object. * @param object is the domain object to cache. * @param writeLockValue is the current write lock value of object, if null the version is ignored. */ @Override public abstract CacheKey put(Object primaryKey, Object object, Object writeLockValue, long readTime); /** * This method may be called during initialize all identity maps. It allows the identity map * or interceptor the opportunity to release any resources before being thrown away. */ @Override public void release(){ //no-op } /** * Remove the CacheKey with the primaryKey from the map. * This is used by DeleteObjectQuery and merge. * This is also an advanced (very) user API. */ @Override public Object remove(Object primaryKey, Object object) { CacheKey key = getCacheKeyForLock(primaryKey); return remove(key); } /** * Remove the CacheKey from the map. */ @Override public abstract Object remove(CacheKey cacheKey); /** * Set the maximum size for the receiver. * @param size is the new maximum size. */ protected synchronized void setMaxSize(int size) { maxSize = size; } /** * This method will be used to update the max cache size, any objects exceeding the max cache size will * be remove from the cache. Please note that this does not remove the object from the identityMap, except in * the case of the CacheIdentityMap. */ @Override public void updateMaxSize(int maxSize) { setMaxSize(maxSize); } /** * Return the class that this is the map for. */ @Override public ClassDescriptor getDescriptor() { return descriptor; } /** * Return the class that this is the map for. */ @Override public Class getDescriptorClass() { if (descriptor == null) { return null; } return descriptor.getJavaClass(); } /** * Set the descriptor that this is the map for. */ @Override public void setDescriptor(ClassDescriptor descriptor) { this.descriptor = descriptor; } /** * Update the wrapper object in the CacheKey associated with the given primaryKey, * this is used for EJB2. */ @Override public void setWrapper(Object primaryKey, Object wrapper) { CacheKey cacheKey = getCacheKeyForLock(primaryKey); if (cacheKey != null) { cacheKey.setWrapper(wrapper); } } /** * Update the write lock value of the CacheKey associated with the given primaryKey. * This is used by UpdateObjectQuery, and is also an advanced (very) user API. */ @Override public void setWriteLockValue(Object primaryKey, Object writeLockValue) { CacheKey cacheKey = getCacheKeyForLock(primaryKey); if (cacheKey != null) { //lock/release the cache key during the lock value updating cacheKey.acquire(); cacheKey.setWriteLockValue(writeLockValue); cacheKey.release(); } } @Override public String toString() { return Helper.getShortClassName(getClass()) + "[" + getSize() + "]"; } }
package com.example.inout; /* * SalaryCalc.java * * Copyright 2020 Ganesan Koundappan <ganesankoundappan@viruchith.local> * * 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ public class SalaryCalc{ private int WAGE_PER_HOUR = 200; private double InTime,OutTime; private double salary = 0; protected double calculateSalary(){ salary = (OutTime-InTime)*WAGE_PER_HOUR; return Math.round(salary); } protected String validateInterval(float hIn,float mIn,float hOut,float mOut){ InTime = hIn+(mIn/60); OutTime = hOut+(mOut/60); System.out.println("In:"+InTime); System.out.println("Ou:"+OutTime); if(OutTime-InTime>0.5){ return "valid"; }else{ return "Invalid Time Interval chosen ! "; } } }
/* * Copyright (C) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.geom; import gov.nasa.worldwind.globes.Globe; /** * ExtentHolder provides an interface to query an object's enclosing volume in model coordinates. * * @author dcollins * @version $Id: ExtentHolder.java 1171 2013-02-11 21:45:02Z dcollins $ * @see gov.nasa.worldwind.geom.Extent */ public interface ExtentHolder { /** * Returns the objects enclosing volume as an {@link gov.nasa.worldwind.geom.Extent} in model coordinates, given a * specified {@link gov.nasa.worldwind.globes.Globe} and vertical exaggeration (see {@link * gov.nasa.worldwind.SceneController#getVerticalExaggeration()}. * * @param globe the Globe the object is related to. * @param verticalExaggeration the vertical exaggeration of the scene containing this object. * * @return the object's Extent in model coordinates. * * @throws IllegalArgumentException if the Globe is null. */ Extent getExtent(Globe globe, double verticalExaggeration); }
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.controlpanel; import java.io.Serializable; import java.sql.SQLException; import java.util.*; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.aspect.administrative.CurrentActivityAction; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.eperson.EPerson; import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.service.EPersonService; /** * Control panel tab that displays current activity. * Based on the original ControlPanel class by Jay Paz and Scott Phillips * @author LINDAT/CLARIN dev team (http://lindat.cz) * */ public class ControlPanelCurrentActivityTab extends AbstractControlPanelTab { private static final Message T_activity_head = message("xmlui.administrative.ControlPanel.activity_head"); private static final Message T_stop_anonymous = message("xmlui.administrative.ControlPanel.stop_anonymous"); private static final Message T_start_anonymous = message("xmlui.administrative.ControlPanel.start_anonymous"); private static final Message T_stop_bot = message("xmlui.administrative.ControlPanel.stop_bot"); private static final Message T_start_bot = message("xmlui.administrative.ControlPanel.start_bot"); private static final Message T_activity_sort_time = message("xmlui.administrative.ControlPanel.activity_sort_time"); private static final Message T_activity_sort_user = message("xmlui.administrative.ControlPanel.activity_sort_user"); private static final Message T_activity_sort_ip = message("xmlui.administrative.ControlPanel.activity_sort_ip"); private static final Message T_activity_sort_url = message("xmlui.administrative.ControlPanel.activity_sort_url"); private static final Message T_activity_sort_agent = message("xmlui.administrative.ControlPanel.activity_sort_Agent"); private static final Message T_activity_anonymous = message("xmlui.administrative.ControlPanel.activity_anonymous"); private static final Message T_activity_none = message("xmlui.administrative.ControlPanel.activity_none"); private static final Message T_seconds = message("xmlui.administrative.ControlPanel.seconds"); private static final Message T_hours = message("xmlui.administrative.ControlPanel.hours"); private static final Message T_minutes = message("xmlui.administrative.ControlPanel.minutes"); private static final Message T_detail = message("xmlui.administrative.ControlPanel.detail"); private static final Message T_show_hide = message("xmlui.administrative.ControlPanel.show_hide"); private static final Message T_host = message("xmlui.administrative.ControlPanel.host"); private static final Message T_puser = message("xmlui.administrative.ControlPanel.puser"); private static final Message T_headers = message("xmlui.administrative.ControlPanel.headers"); private static final Message T_cookies = message("xmlui.administrative.ControlPanel.cookies"); protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); @Override public void addBody(Map objectModel, Division div) throws WingException, SQLException { // 0) Update recording settings Request request = ObjectModelHelper.getRequest(objectModel); // Toggle anonymous recording String recordAnonymousString = request.getParameter("recordanonymous"); if (recordAnonymousString != null) { if ("ON".equals(recordAnonymousString)) { CurrentActivityAction.setRecordAnonymousEvents(true); } if ("OFF".equals(recordAnonymousString)) { CurrentActivityAction.setRecordAnonymousEvents(false); } } // Toggle bot recording String recordBotString = request.getParameter("recordbots"); if (recordBotString != null) { if ("ON".equals(recordBotString)) { CurrentActivityAction.setRecordBotEvents(true); } if ("OFF".equals(recordBotString)) { CurrentActivityAction.setRecordBotEvents(false); } } // 1) Determine how to sort EventSort sortBy = EventSort.TIME; String sortByString = request.getParameter("sortBy"); if (EventSort.TIME.toString().equals(sortByString)) { sortBy = EventSort.TIME; } if (EventSort.URL.toString().equals(sortByString)) { sortBy = EventSort.URL; } if (EventSort.SESSION.toString().equals(sortByString)) { sortBy = EventSort.SESSION; } if (EventSort.AGENT.toString().equals(sortByString)) { sortBy = EventSort.AGENT; } if (EventSort.IP.toString().equals(sortByString)) { sortBy = EventSort.IP; } // 2) Sort the events by the requested sorting parameter java.util.List<CurrentActivityAction.Event> events = CurrentActivityAction .getEvents(); Collections.sort(events, new ActivitySort<CurrentActivityAction.Event>( sortBy)); Collections.reverse(events); div = div.addDivision("activitydiv", "well well-light"); // 3) Toggle controls for anonymous and bot activity if (CurrentActivityAction.getRecordAnonymousEvents()) { div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordanonymous=OFF").addContent(T_stop_anonymous); } else { div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordanonymous=ON").addContent(T_start_anonymous); } if (CurrentActivityAction.getRecordBotEvents()) { div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordbots=OFF").addContent(T_stop_bot); } else { div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordbots=ON").addContent(T_start_bot); } // 4) Display the results Table // TABLE: activeUsers Table activeUsers = div.addTable("users", 1, 1); activeUsers.setHead(T_activity_head .parameterize(CurrentActivityAction.MAX_EVENTS)); Row row = activeUsers.addRow(null, Row.ROLE_HEADER, "font_smaller"); if (sortBy == EventSort.TIME) { row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time); } else { row.addCell().addXref(web_link + "&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time); } if (sortBy == EventSort.SESSION) { row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user); } else { row.addCell().addXref(web_link + "&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user); } if (sortBy == EventSort.IP) { row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip); } else { row.addCell().addXref(web_link + "&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip); } if (sortBy == EventSort.URL) { row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.URL).addContent(T_activity_sort_url); } else { row.addCell().addXref(web_link + "&sortBy=" + EventSort.URL).addContent(T_activity_sort_url); } if (sortBy == EventSort.AGENT) { row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent); } else { row.addCell().addXref(web_link + "&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent); } // add + row.addCellContent(T_detail); // Keep track of how many individual anonymous users there are, each // unique anonymous // user is assigned an index based upon the servlet session id. HashMap<String, Integer> anonymousHash = new HashMap<String, Integer>(); int anonymousCount = 1; int shown = 0; for (CurrentActivityAction.Event event : events) { if (event == null) { continue; } shown++; Message timeStampMessage = null; long ago = System.currentTimeMillis() - event.getTimeStamp(); if (ago > 2 * 60 * 60 * 1000) { timeStampMessage = T_hours .parameterize((ago / (60 * 60 * 1000))); } else if (ago > 60 * 1000) { timeStampMessage = T_minutes.parameterize((ago / (60 * 1000))); } else { timeStampMessage = T_seconds.parameterize((ago / (1000))); } Row eventRow = activeUsers.addRow(null, Row.ROLE_DATA, "font_smaller"); eventRow.addCellContent(timeStampMessage); UUID eid = event.getEPersonID(); EPerson eperson = ePersonService.find(context, eid); if (eperson != null) { String name = eperson.getFullName(); eventRow.addCellContent(name); } else { // Is this a new anonymous user? if (!anonymousHash.containsKey(event.getSessionID())) { anonymousHash.put(event.getSessionID(), anonymousCount++); } eventRow.addCellContent(T_activity_anonymous .parameterize(anonymousHash.get(event.getSessionID()))); } eventRow.addCellContent(event.getIP()); eventRow.addCell().addXref(contextPath + "/" + event.getURL()) .addContent("/" + event.getURL()); eventRow.addCellContent(event.getDectectedBrowser()); eventRow.addCell(null, null, "toggle-onclick-parent-next4 bold btn-link") .addContent(T_show_hide); final String not_present = "not present"; String host = event.host != null ? (String) (event.host) : not_present; activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) .addContent(T_host.parameterize(host)); String puser = event.puser != null ? event.puser : not_present; activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) .addContent(T_puser.parameterize(puser)); // String headers = ""; for (Map.Entry<String, String> o : event.headers.entrySet()) headers += o.getKey() + ":[" + o.getValue() + "];"; headers = headers != "" ? headers : not_present; activeUsers.addRow(null, null, "hidden").addCell(1, 6) .addContent(T_headers.parameterize(headers)); // String cookies = ""; for (Map.Entry<String, String> o : event.cookieMap.entrySet()) cookies += o.getKey() + ":[" + o.getValue() + "];"; cookies = cookies != "" ? cookies : not_present; activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) .addContent(T_cookies.parameterize(cookies)); } if (shown == 0) { activeUsers.addRow().addCell(1, 5).addContent(T_activity_none); } } /** The possible sorting parameters */ private static enum EventSort { TIME, URL, SESSION, AGENT, IP }; /** * Comparator to sort activity events by their access times. */ public static class ActivitySort<E extends CurrentActivityAction.Event> implements Comparator<E>, Serializable { // Sort parameter private EventSort sortBy; public ActivitySort(EventSort sortBy) { this.sortBy = sortBy; } /** * Compare these two activity events based upon the given sort * parameter. In the case of a tie, allways fallback to sorting based * upon the timestamp. */ @Override public int compare(E a, E b) { // Protect against null events while sorting if (a != null && b == null) { return 1; // A > B } else if (a == null && b != null) { return -1; // B > A } else if (a == null && b == null) { return 0; // A == B } // Sort by the given ordering matrix if (EventSort.URL == sortBy) { String aURL = a.getURL(); String bURL = b.getURL(); int cmp = aURL.compareTo(bURL); if (cmp != 0) { return cmp; } } else if (EventSort.AGENT == sortBy) { String aAgent = a.getDectectedBrowser(); String bAgent = b.getDectectedBrowser(); int cmp = aAgent.compareTo(bAgent); if (cmp != 0) { return cmp; } } else if (EventSort.IP == sortBy) { String aIP = a.getIP(); String bIP = b.getIP(); int cmp = aIP.compareTo(bIP); if (cmp != 0) { return cmp; } } else if (EventSort.SESSION == sortBy) { // Ensure that all sessions with an EPersonID associated are // ordered to the top. Otherwise fall back to comparing session // IDs. Unfortunately we can not compare eperson names because // we do not have access to a context object. if (a.getEPersonID() != null && b.getEPersonID() == null) { return 1; // A > B } else if (a.getEPersonID() == null && b.getEPersonID() != null) { return -1; // B > A } String aSession = a.getSessionID(); String bSession = b.getSessionID(); int cmp = aSession.compareTo(bSession); if (cmp != 0) { return cmp; } } // All ways fall back to sorting by time, when events are equal. if (a.getTimeStamp() > b.getTimeStamp()) { return 1; // A > B } else if (a.getTimeStamp() > b.getTimeStamp()) { return -1; // B > A } return 0; // A == B } } }
/** * Copyright (c) 2016-2019 人人开源 All rights reserved. * 版权所有,侵权必究! */ package com.github.niefy.common.utils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; public class HttpContextUtils { public static HttpServletRequest getHttpServletRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } public static String getDomain() { HttpServletRequest request = getHttpServletRequest(); StringBuffer url = request.getRequestURL(); return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); } public static String getOrigin() { HttpServletRequest request = getHttpServletRequest(); return request.getHeader("Origin"); } }
/* * The MIT License * * Copyright (c) 2010, Kohsuke Kawaguchi * * 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 org.kohsuke.github; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.commons.lang3.StringUtils; import org.kohsuke.github.function.InputStreamFunction; import org.kohsuke.github.internal.EnumUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.io.Reader; import java.net.URL; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.WeakHashMap; import javax.annotation.Nonnull; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import static org.kohsuke.github.internal.Previews.ANTIOPE; import static org.kohsuke.github.internal.Previews.ANT_MAN; import static org.kohsuke.github.internal.Previews.BAPTISTE; import static org.kohsuke.github.internal.Previews.FLASH; import static org.kohsuke.github.internal.Previews.INERTIA; import static org.kohsuke.github.internal.Previews.MERCY; import static org.kohsuke.github.internal.Previews.NEBULA; import static org.kohsuke.github.internal.Previews.SHADOW_CAT; /** * A repository on GitHub. * * @author Kohsuke Kawaguchi */ @SuppressWarnings({ "UnusedDeclaration" }) @SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD" }, justification = "JSON API") public class GHRepository extends GHObject { private String nodeId, description, homepage, name, full_name; private String html_url; // this is the UI /* * The license information makes use of the preview API. * * See: https://developer.github.com/v3/licenses/ */ private GHLicense license; private String git_url, ssh_url, clone_url, svn_url, mirror_url; private GHUser owner; // not fully populated. beware. private boolean has_issues, has_wiki, fork, has_downloads, has_pages, archived, has_projects; private boolean allow_squash_merge; private boolean allow_merge_commit; private boolean allow_rebase_merge; private boolean delete_branch_on_merge; @JsonProperty("private") private boolean _private; private String visibility; private int forks_count, stargazers_count, watchers_count, size, open_issues_count, subscribers_count; private String pushed_at; private Map<Integer, GHMilestone> milestones = new WeakHashMap<Integer, GHMilestone>(); private String default_branch, language; private Map<String, GHCommit> commits = new WeakHashMap<String, GHCommit>(); @SkipFromToString private GHRepoPermission permissions; private GHRepository source, parent; private Boolean isTemplate; private boolean compareUsePaginatedCommits; static GHRepository read(GitHub root, String owner, String name) throws IOException { return root.createRequest().withUrlPath("/repos/" + owner + '/' + name).fetch(GHRepository.class); } /** * Create deployment gh deployment builder. * * @param ref * the ref * @return the gh deployment builder */ public GHDeploymentBuilder createDeployment(String ref) { return new GHDeploymentBuilder(this, ref); } /** * Gets deployment statuses. * * @param id * the id * @return the deployment statuses * @throws IOException * the io exception * @deprecated Use {@code getDeployment(id).listStatuses()} */ @Deprecated public PagedIterable<GHDeploymentStatus> getDeploymentStatuses(final int id) throws IOException { return getDeployment(id).listStatuses(); } /** * List deployments paged iterable. * * @param sha * the sha * @param ref * the ref * @param task * the task * @param environment * the environment * @return the paged iterable */ public PagedIterable<GHDeployment> listDeployments(String sha, String ref, String task, String environment) { return root().createRequest() .with("sha", sha) .with("ref", ref) .with("task", task) .with("environment", environment) .withUrlPath(getApiTailUrl("deployments")) .withPreview(ANT_MAN) .withPreview(FLASH) .toIterable(GHDeployment[].class, item -> item.wrap(this)); } /** * Obtains a single {@link GHDeployment} by its ID. * * @param id * the id * @return the deployment * @throws IOException * the io exception */ public GHDeployment getDeployment(long id) throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("deployments/" + id)) .withPreview(ANT_MAN) .withPreview(FLASH) .fetch(GHDeployment.class) .wrap(this); } /** * Gets deploy status. * * @param deploymentId * the deployment id * @param ghDeploymentState * the gh deployment state * @return the deploy status * @throws IOException * the io exception * @deprecated Use {@code getDeployment(deploymentId).createStatus(ghDeploymentState)} */ @Deprecated public GHDeploymentStatusBuilder createDeployStatus(int deploymentId, GHDeploymentState ghDeploymentState) throws IOException { return getDeployment(deploymentId).createStatus(ghDeploymentState); } private static class GHRepoPermission { boolean pull, push, admin; } /** * Gets node id * * @return the node id */ public String getNodeId() { return nodeId; } /** * Gets description. * * @return the description */ public String getDescription() { return description; } /** * Gets homepage. * * @return the homepage */ public String getHomepage() { return homepage; } /** * Gets the git:// URL to this repository, such as "git://github.com/kohsuke/jenkins.git" This URL is read-only. * * @return the git transport url */ public String getGitTransportUrl() { return git_url; } /** * Gets the HTTPS URL to this repository, such as "https://github.com/kohsuke/jenkins.git" This URL is read-only. * * @return the http transport url */ public String getHttpTransportUrl() { return clone_url; } /** * Git http transport url string. * * @return the string * @deprecated Typo of {@link #getHttpTransportUrl()} */ @Deprecated public String gitHttpTransportUrl() { return clone_url; } /** * Gets the Subversion URL to access this repository: https://github.com/rails/rails * * @return the svn url */ public String getSvnUrl() { return svn_url; } /** * Gets the Mirror URL to access this repository: https://github.com/apache/tomee mirrored from * git://git.apache.org/tomee.git * * @return the mirror url */ public String getMirrorUrl() { return mirror_url; } /** * Gets the SSH URL to access this repository, such as git@github.com:rails/rails.git * * @return the ssh url */ public String getSshUrl() { return ssh_url; } public URL getHtmlUrl() { return GitHubClient.parseURL(html_url); } /** * Short repository name without the owner. For example 'jenkins' in case of http://github.com/jenkinsci/jenkins * * @return the name */ public String getName() { return name; } /** * Full repository name including the owner or organization. For example 'jenkinsci/jenkins' in case of * http://github.com/jenkinsci/jenkins * * @return the full name */ public String getFullName() { return full_name; } /** * Has pull access boolean. * * @return the boolean */ public boolean hasPullAccess() { return permissions != null && permissions.pull; } /** * Has push access boolean. * * @return the boolean */ public boolean hasPushAccess() { return permissions != null && permissions.push; } /** * Has admin access boolean. * * @return the boolean */ public boolean hasAdminAccess() { return permissions != null && permissions.admin; } /** * Gets the primary programming language. * * @return the language */ public String getLanguage() { return language; } /** * Gets owner. * * @return the owner * @throws IOException * the io exception */ @SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior") public GHUser getOwner() throws IOException { return isOffline() ? owner : root().getUser(getOwnerName()); // because 'owner' isn't fully populated } /** * Gets issue. * * @param id * the id * @return the issue * @throws IOException * the io exception */ public GHIssue getIssue(int id) throws IOException { return root().createRequest().withUrlPath(getApiTailUrl("issues/" + id)).fetch(GHIssue.class).wrap(this); } /** * Create issue gh issue builder. * * @param title * the title * @return the gh issue builder */ public GHIssueBuilder createIssue(String title) { return new GHIssueBuilder(this, title); } /** * Gets issues. * * @param state * the state * @return the issues * @throws IOException * the io exception */ public List<GHIssue> getIssues(GHIssueState state) throws IOException { return listIssues(state).toList(); } /** * Gets issues. * * @param state * the state * @param milestone * the milestone * @return the issues * @throws IOException * the io exception */ public List<GHIssue> getIssues(GHIssueState state, GHMilestone milestone) throws IOException { Requester requester = root().createRequest() .with("state", state) .with("milestone", milestone == null ? "none" : "" + milestone.getNumber()); return requester.withUrlPath(getApiTailUrl("issues")) .toIterable(GHIssue[].class, item -> item.wrap(this)) .toList(); } /** * Lists up all the issues in this repository. * * @param state * the state * @return the paged iterable */ public PagedIterable<GHIssue> listIssues(final GHIssueState state) { return root().createRequest() .with("state", state) .withUrlPath(getApiTailUrl("issues")) .toIterable(GHIssue[].class, item -> item.wrap(this)); } /** * Create release gh release builder. * * @param tag * the tag * @return the gh release builder */ public GHReleaseBuilder createRelease(String tag) { return new GHReleaseBuilder(this, tag); } /** * Creates a named ref, such as tag, branch, etc. * * @param name * The name of the fully qualified reference (ie: refs/heads/main). If it doesn't start with 'refs' and * have at least two slashes, it will be rejected. * @param sha * The SHA1 value to set this reference to * @return the gh ref * @throws IOException * the io exception */ public GHRef createRef(String name, String sha) throws IOException { return root().createRequest() .method("POST") .with("ref", name) .with("sha", sha) .withUrlPath(getApiTailUrl("git/refs")) .fetch(GHRef.class); } /** * Gets releases. * * @return the releases * @throws IOException * the io exception * @deprecated use {@link #listReleases()} */ public List<GHRelease> getReleases() throws IOException { return listReleases().toList(); } /** * Gets release. * * @param id * the id * @return the release * @throws IOException * the io exception */ public GHRelease getRelease(long id) throws IOException { try { return root().createRequest() .withUrlPath(getApiTailUrl("releases/" + id)) .fetch(GHRelease.class) .wrap(this); } catch (FileNotFoundException e) { return null; // no release for this id } } /** * Gets release by tag name. * * @param tag * the tag * @return the release by tag name * @throws IOException * the io exception */ public GHRelease getReleaseByTagName(String tag) throws IOException { try { return root().createRequest() .withUrlPath(getApiTailUrl("releases/tags/" + tag)) .fetch(GHRelease.class) .wrap(this); } catch (FileNotFoundException e) { return null; // no release for this tag } } /** * Gets latest release. * * @return the latest release * @throws IOException * the io exception */ public GHRelease getLatestRelease() throws IOException { try { return root().createRequest() .withUrlPath(getApiTailUrl("releases/latest")) .fetch(GHRelease.class) .wrap(this); } catch (FileNotFoundException e) { return null; // no latest release } } /** * List releases paged iterable. * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHRelease> listReleases() throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("releases")) .toIterable(GHRelease[].class, item -> item.wrap(this)); } /** * List tags paged iterable. * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHTag> listTags() throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("tags")) .toIterable(GHTag[].class, item -> item.wrap(this)); } /** * List languages for the specified repository. The value on the right of a language is the number of bytes of code * written in that language. { "C": 78769, "Python": 7769 } * * @return the map * @throws IOException * the io exception */ public Map<String, Long> listLanguages() throws IOException { HashMap<String, Long> result = new HashMap<>(); root().createRequest().withUrlPath(getApiTailUrl("languages")).fetch(HashMap.class).forEach((key, value) -> { Long addValue = -1L; if (value instanceof Integer) { addValue = Long.valueOf((Integer) value); } result.put(key.toString(), addValue); }); return result; } /** * Gets owner name. * * @return the owner name */ public String getOwnerName() { // consistency of the GitHub API is super... some serialized forms of GHRepository populate // a full GHUser while others populate only the owner and email. This later form is super helpful // in putting the login in owner.name not owner.login... thankfully we can easily identify this // second set because owner.login will be null return owner.login != null ? owner.login : owner.name; } /** * Has issues boolean. * * @return the boolean */ public boolean hasIssues() { return has_issues; } /** * Has projects boolean. * * @return the boolean */ public boolean hasProjects() { return has_projects; } /** * Has wiki boolean. * * @return the boolean */ public boolean hasWiki() { return has_wiki; } /** * Is fork boolean. * * @return the boolean */ public boolean isFork() { return fork; } /** * Is archived boolean. * * @return the boolean */ public boolean isArchived() { return archived; } /** * Is allow squash merge boolean. * * @return the boolean */ public boolean isAllowSquashMerge() { return allow_squash_merge; } /** * Is allow merge commit boolean. * * @return the boolean */ public boolean isAllowMergeCommit() { return allow_merge_commit; } /** * Is allow rebase merge boolean. * * @return the boolean */ public boolean isAllowRebaseMerge() { return allow_rebase_merge; } /** * Automatically deleting head branches when pull requests are merged * * @return the boolean */ public boolean isDeleteBranchOnMerge() { return delete_branch_on_merge; } /** * Returns the number of all forks of this repository. This not only counts direct forks, but also forks of forks, * and so on. * * @return the forks * @deprecated use {@link #getForksCount()} instead */ @Deprecated public int getForks() { return getForksCount(); } /** * Returns the number of all forks of this repository. This not only counts direct forks, but also forks of forks, * and so on. * * @return the forks */ public int getForksCount() { return forks_count; } /** * Gets stargazers count. * * @return the stargazers count */ public int getStargazersCount() { return stargazers_count; } /** * Is private boolean. * * @return the boolean */ public boolean isPrivate() { return _private; } /** * Visibility of a repository. */ public enum Visibility { PUBLIC, INTERNAL, PRIVATE, /** * Placeholder for unexpected data values. * * This avoids throwing exceptions during data binding or reading when the list of allowed values returned from * GitHub is expanded. * * Do not pass this value to any methods. If this value is returned during a request, check the log output and * report an issue for the missing value. */ UNKNOWN; public static Visibility from(String value) { return EnumUtils.getNullableEnumOrDefault(Visibility.class, value, Visibility.UNKNOWN); } @Override public String toString() { return name().toLowerCase(Locale.ROOT); } } /** * Gets the visibility of the repository. * * @return the visibility */ @Preview(NEBULA) public Visibility getVisibility() { if (visibility == null) { try { populate(); } catch (final IOException e) { // Convert this to a runtime exception to avoid messy method signature throw new GHException("Could not populate the visibility of the repository", e); } } return Visibility.from(visibility); } /** * Is template boolean. * * @return the boolean */ @Preview(BAPTISTE) public boolean isTemplate() { // isTemplate is still in preview, we do not want to retrieve it unless needed. if (isTemplate == null) { try { populate(); } catch (IOException e) { // Convert this to a runtime exception to avoid messy method signature throw new GHException("Could not populate the template setting of the repository", e); } // if this somehow is not populated, set it to false; isTemplate = Boolean.TRUE.equals(isTemplate); } return isTemplate; } /** * Has downloads boolean. * * @return the boolean */ public boolean hasDownloads() { return has_downloads; } /** * Has pages boolean. * * @return the boolean */ public boolean hasPages() { return has_pages; } /** * Gets watchers. * * @return the watchers * @deprecated use {@link #getWatchersCount()} instead */ @Deprecated public int getWatchers() { return getWatchersCount(); } /** * Gets the count of watchers. * * @return the watchers */ public int getWatchersCount() { return watchers_count; } /** * Gets open issue count. * * @return the open issue count */ public int getOpenIssueCount() { return open_issues_count; } /** * Gets subscribers count. * * @return the subscribers count */ public int getSubscribersCount() { return subscribers_count; } /** * Gets pushed at. * * @return null if the repository was never pushed at. */ public Date getPushedAt() { return GitHubClient.parseDate(pushed_at); } /** * Returns the primary branch you'll configure in the "Admin &gt; Options" config page. * * @return This field is null until the user explicitly configures the default branch. */ public String getDefaultBranch() { return default_branch; } /** * Gets default branch. * * Name is an artifact of when "master" was the most common default. * * @return the default branch * @deprecated Renamed to {@link #getDefaultBranch()} */ @Deprecated public String getMasterBranch() { return default_branch; } /** * Gets size. * * @return the size */ public int getSize() { return size; } /** * Affiliation of a repository collaborator */ public enum CollaboratorAffiliation { ALL, DIRECT, OUTSIDE } /** * Gets the collaborators on this repository. This set always appear to include the owner. * * @return the collaborators * @throws IOException * the io exception */ @WithBridgeMethods(Set.class) public GHPersonSet<GHUser> getCollaborators() throws IOException { return new GHPersonSet<GHUser>(listCollaborators().toList()); } /** * Lists up the collaborators on this repository. * * @return Users paged iterable * @throws IOException * the io exception */ public PagedIterable<GHUser> listCollaborators() throws IOException { return listUsers("collaborators"); } /** * Lists up the collaborators on this repository. * * @param affiliation * Filter users by affiliation * @return Users paged iterable * @throws IOException * the io exception */ public PagedIterable<GHUser> listCollaborators(CollaboratorAffiliation affiliation) throws IOException { return listUsers(root().createRequest().with("affiliation", affiliation), "collaborators"); } /** * Lists all * <a href="https://help.github.com/articles/assigning-issues-and-pull-requests-to-other-github-users/">the * available assignees</a> to which issues may be assigned. * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHUser> listAssignees() throws IOException { return listUsers("assignees"); } /** * Checks if the given user is an assignee for this repository. * * @param u * the u * @return the boolean * @throws IOException * the io exception */ public boolean hasAssignee(GHUser u) throws IOException { return root().createRequest().withUrlPath(getApiTailUrl("assignees/" + u.getLogin())).fetchHttpStatusCode() / 100 == 2; } /** * Gets the names of the collaborators on this repository. This method deviates from the principle of this library * but it works a lot faster than {@link #getCollaborators()}. * * @return the collaborator names * @throws IOException * the io exception */ public Set<String> getCollaboratorNames() throws IOException { Set<String> r = new HashSet<>(); // no initializer - we just want to the logins PagedIterable<GHUser> users = root().createRequest() .withUrlPath(getApiTailUrl("collaborators")) .toIterable(GHUser[].class, null); for (GHUser u : users.toArray()) { r.add(u.login); } return r; } /** * Gets the names of the collaborators on this repository. This method deviates from the principle of this library * but it works a lot faster than {@link #getCollaborators()}. * * @param affiliation * Filter users by affiliation * @return the collaborator names * @throws IOException * the io exception */ public Set<String> getCollaboratorNames(CollaboratorAffiliation affiliation) throws IOException { Set<String> r = new HashSet<>(); // no initializer - we just want to the logins PagedIterable<GHUser> users = root().createRequest() .withUrlPath(getApiTailUrl("collaborators")) .with("affiliation", affiliation) .toIterable(GHUser[].class, null); for (GHUser u : users.toArray()) { r.add(u.login); } return r; } /** * Obtain permission for a given user in this repository. * * @param user * a {@link GHUser#getLogin} * @return the permission * @throws IOException * the io exception */ public GHPermissionType getPermission(String user) throws IOException { GHPermission perm = root().createRequest() .withUrlPath(getApiTailUrl("collaborators/" + user + "/permission")) .fetch(GHPermission.class); return perm.getPermissionType(); } /** * Obtain permission for a given user in this repository. * * @param u * the user * @return the permission * @throws IOException * the io exception */ public GHPermissionType getPermission(GHUser u) throws IOException { return getPermission(u.getLogin()); } /** * If this repository belongs to an organization, return a set of teams. * * @return the teams * @throws IOException * the io exception */ public Set<GHTeam> getTeams() throws IOException { GHOrganization org = root().getOrganization(getOwnerName()); return root().createRequest() .withUrlPath(getApiTailUrl("teams")) .toIterable(GHTeam[].class, item -> item.wrapUp(org)) .toSet(); } /** * Add collaborators. * * @param users * the users * @param permission * the permission level * @throws IOException * the io exception */ public void addCollaborators(GHOrganization.Permission permission, GHUser... users) throws IOException { addCollaborators(asList(users), permission); } /** * Add collaborators. * * @param users * the users * @throws IOException * the io exception */ public void addCollaborators(GHUser... users) throws IOException { addCollaborators(asList(users)); } /** * Add collaborators. * * @param users * the users * @throws IOException * the io exception */ public void addCollaborators(Collection<GHUser> users) throws IOException { modifyCollaborators(users, "PUT", null); } /** * Add collaborators. * * @param users * the users * @param permission * the permission level * @throws IOException * the io exception */ public void addCollaborators(Collection<GHUser> users, GHOrganization.Permission permission) throws IOException { modifyCollaborators(users, "PUT", permission); } /** * Remove collaborators. * * @param users * the users * @throws IOException * the io exception */ public void removeCollaborators(GHUser... users) throws IOException { removeCollaborators(asList(users)); } /** * Remove collaborators. * * @param users * the users * @throws IOException * the io exception */ public void removeCollaborators(Collection<GHUser> users) throws IOException { modifyCollaborators(users, "DELETE", null); } private void modifyCollaborators(@NonNull Collection<GHUser> users, @NonNull String method, @CheckForNull GHOrganization.Permission permission) throws IOException { Requester requester = root().createRequest().method(method); if (permission != null) { requester = requester.with("permission", permission).inBody(); } // Make sure that the users collection doesn't have any duplicates for (GHUser user : new LinkedHashSet<GHUser>(users)) { requester.withUrlPath(getApiTailUrl("collaborators/" + user.getLogin())).send(); } } /** * Sets email service hook. * * @param address * the address * @throws IOException * the io exception */ public void setEmailServiceHook(String address) throws IOException { Map<String, String> config = new HashMap<String, String>(); config.put("address", address); root().createRequest() .method("POST") .with("name", "email") .with("config", config) .with("active", true) .withUrlPath(getApiTailUrl("hooks")) .send(); } /** * Enables or disables the issue tracker for this repository. * * @param v * the v * @throws IOException * the io exception */ public void enableIssueTracker(boolean v) throws IOException { set().issues(v); } /** * Enables or disables projects for this repository. * * @param v * the v * @throws IOException * the io exception */ public void enableProjects(boolean v) throws IOException { set().projects(v); } /** * Enables or disables Wiki for this repository. * * @param v * the v * @throws IOException * the io exception */ public void enableWiki(boolean v) throws IOException { set().wiki(v); } /** * Enable downloads. * * @param v * the v * @throws IOException * the io exception */ public void enableDownloads(boolean v) throws IOException { set().downloads(v); } /** * Rename this repository. * * @param name * the name * @throws IOException * the io exception */ public void renameTo(String name) throws IOException { set().name(name); } /** * Sets description. * * @param value * the value * @throws IOException * the io exception */ public void setDescription(String value) throws IOException { set().description(value); } /** * Sets homepage. * * @param value * the value * @throws IOException * the io exception */ public void setHomepage(String value) throws IOException { set().homepage(value); } /** * Sets default branch. * * @param value * the value * @throws IOException * the io exception */ public void setDefaultBranch(String value) throws IOException { set().defaultBranch(value); } /** * Sets private. * * @param value * the value * @throws IOException * the io exception */ public void setPrivate(boolean value) throws IOException { set().private_(value); } /** * Sets visibility. * * @param value * the value * @throws IOException * the io exception */ @Preview(NEBULA) public void setVisibility(final Visibility value) throws IOException { root().createRequest() .method("PATCH") .withPreview(NEBULA) .with("name", name) .with("visibility", value) .withUrlPath(getApiTailUrl("")) .send(); } /** * Allow squash merge. * * @param value * the value * @throws IOException * the io exception */ public void allowSquashMerge(boolean value) throws IOException { set().allowSquashMerge(value); } /** * Allow merge commit. * * @param value * the value * @throws IOException * the io exception */ public void allowMergeCommit(boolean value) throws IOException { set().allowMergeCommit(value); } /** * Allow rebase merge. * * @param value * the value * @throws IOException * the io exception */ public void allowRebaseMerge(boolean value) throws IOException { set().allowRebaseMerge(value); } /** * After pull requests are merged, you can have head branches deleted automatically. * * @param value * the value * @throws IOException * the io exception */ public void deleteBranchOnMerge(boolean value) throws IOException { set().deleteBranchOnMerge(value); } /** * Deletes this repository. * * @throws IOException * the io exception */ public void delete() throws IOException { try { root().createRequest().method("DELETE").withUrlPath(getApiTailUrl("")).send(); } catch (FileNotFoundException x) { throw (FileNotFoundException) new FileNotFoundException("Failed to delete " + getOwnerName() + "/" + name + "; might not exist, or you might need the delete_repo scope in your token: http://stackoverflow.com/a/19327004/12916") .initCause(x); } } /** * Will archive and this repository as read-only. When a repository is archived, any operation that can change its * state is forbidden. This applies symmetrically if trying to unarchive it. * * <p> * When you try to do any operation that modifies a read-only repository, it returns the response: * * <pre> * org.kohsuke.github.HttpException: { * "message":"Repository was archived so is read-only.", * "documentation_url":"https://developer.github.com/v3/repos/#edit" * } * </pre> * * @throws IOException * In case of any networking error or error from the server. */ public void archive() throws IOException { set().archive(); // Generally would not update this record, // but doing so here since this will result in any other update actions failing archived = true; } /** * Creates a builder that can be used to bulk update repository settings. * * @return the repository updater */ public Updater update() { return new Updater(this); } /** * Creates a builder that can be used to bulk update repository settings. * * @return the repository updater */ public Setter set() { return new Setter(this); } /** * Sort orders for listing forks */ public enum ForkSort { NEWEST, OLDEST, STARGAZERS } /** * Lists all the direct forks of this repository, sorted by github api default, currently {@link ForkSort#NEWEST * ForkSort.NEWEST}*. * * @return the paged iterable */ public PagedIterable<GHRepository> listForks() { return listForks(null); } /** * Lists all the direct forks of this repository, sorted by the given sort order. * * @param sort * the sort order. If null, defaults to github api default, currently {@link ForkSort#NEWEST * ForkSort.NEWEST}. * @return the paged iterable */ public PagedIterable<GHRepository> listForks(final ForkSort sort) { return root().createRequest() .with("sort", sort) .withUrlPath(getApiTailUrl("forks")) .toIterable(GHRepository[].class, null); } /** * Forks this repository as your repository. * * @return Newly forked repository that belong to you. * @throws IOException * the io exception */ public GHRepository fork() throws IOException { root().createRequest().method("POST").withUrlPath(getApiTailUrl("forks")).send(); // this API is asynchronous. we need to wait for a bit for (int i = 0; i < 10; i++) { GHRepository r = root().getMyself().getRepository(name); if (r != null) { return r; } try { Thread.sleep(3000); } catch (InterruptedException e) { throw (IOException) new InterruptedIOException().initCause(e); } } throw new IOException(this + " was forked but can't find the new repository"); } /** * Forks this repository into an organization. * * @param org * the org * @return Newly forked repository that belong to you. * @throws IOException * the io exception */ public GHRepository forkTo(GHOrganization org) throws IOException { root().createRequest() .method("POST") .with("organization", org.getLogin()) .withUrlPath(getApiTailUrl("forks")) .send(); // this API is asynchronous. we need to wait for a bit for (int i = 0; i < 10; i++) { GHRepository r = org.getRepository(name); if (r != null) { return r; } try { Thread.sleep(3000); } catch (InterruptedException e) { throw (IOException) new InterruptedIOException().initCause(e); } } throw new IOException(this + " was forked into " + org.getLogin() + " but can't find the new repository"); } /** * Retrieves a specified pull request. * * @param i * the * @return the pull request * @throws IOException * the io exception */ public GHPullRequest getPullRequest(int i) throws IOException { return root().createRequest() .withPreview(SHADOW_CAT) .withUrlPath(getApiTailUrl("pulls/" + i)) .fetch(GHPullRequest.class) .wrapUp(this); } /** * Retrieves all the pull requests of a particular state. * * @param state * the state * @return the pull requests * @throws IOException * the io exception * @see #listPullRequests(GHIssueState) #listPullRequests(GHIssueState) */ public List<GHPullRequest> getPullRequests(GHIssueState state) throws IOException { return queryPullRequests().state(state).list().toList(); } /** * Retrieves all the pull requests of a particular state. * * @param state * the state * @return the paged iterable * @deprecated Use {@link #queryPullRequests()} */ @Deprecated public PagedIterable<GHPullRequest> listPullRequests(GHIssueState state) { return queryPullRequests().state(state).list(); } /** * Retrieves pull requests. * * @return the gh pull request query builder */ public GHPullRequestQueryBuilder queryPullRequests() { return new GHPullRequestQueryBuilder(this); } /** * Creates a new pull request. * * @param title * Required. The title of the pull request. * @param head * Required. The name of the branch where your changes are implemented. For cross-repository pull * requests in the same network, namespace head with a user like this: username:branch. * @param base * Required. The name of the branch you want your changes pulled into. This should be an existing branch * on the current repository. * @param body * The contents of the pull request. This is the markdown description of a pull request. * @return the gh pull request * @throws IOException * the io exception */ public GHPullRequest createPullRequest(String title, String head, String base, String body) throws IOException { return createPullRequest(title, head, base, body, true); } /** * Creates a new pull request. Maintainer's permissions aware. * * @param title * Required. The title of the pull request. * @param head * Required. The name of the branch where your changes are implemented. For cross-repository pull * requests in the same network, namespace head with a user like this: username:branch. * @param base * Required. The name of the branch you want your changes pulled into. This should be an existing branch * on the current repository. * @param body * The contents of the pull request. This is the markdown description of a pull request. * @param maintainerCanModify * Indicates whether maintainers can modify the pull request. * @return the gh pull request * @throws IOException * the io exception */ public GHPullRequest createPullRequest(String title, String head, String base, String body, boolean maintainerCanModify) throws IOException { return createPullRequest(title, head, base, body, maintainerCanModify, false); } /** * Creates a new pull request. Maintainer's permissions and draft aware. * * @param title * Required. The title of the pull request. * @param head * Required. The name of the branch where your changes are implemented. For cross-repository pull * requests in the same network, namespace head with a user like this: username:branch. * @param base * Required. The name of the branch you want your changes pulled into. This should be an existing branch * on the current repository. * @param body * The contents of the pull request. This is the markdown description of a pull request. * @param maintainerCanModify * Indicates whether maintainers can modify the pull request. * @param draft * Indicates whether to create a draft pull request or not. * @return the gh pull request * @throws IOException * the io exception */ public GHPullRequest createPullRequest(String title, String head, String base, String body, boolean maintainerCanModify, boolean draft) throws IOException { return root().createRequest() .method("POST") .withPreview(SHADOW_CAT) .with("title", title) .with("head", head) .with("base", base) .with("body", body) .with("maintainer_can_modify", maintainerCanModify) .with("draft", draft) .withUrlPath(getApiTailUrl("pulls")) .fetch(GHPullRequest.class) .wrapUp(this); } /** * Retrieves the currently configured hooks. * * @return the hooks * @throws IOException * the io exception */ public List<GHHook> getHooks() throws IOException { return GHHooks.repoContext(this, owner).getHooks(); } /** * Gets hook. * * @param id * the id * @return the hook * @throws IOException * the io exception */ public GHHook getHook(int id) throws IOException { return GHHooks.repoContext(this, owner).getHook(id); } /** * Deletes hook. * * @param id * the id * @throws IOException * the io exception */ public void deleteHook(int id) throws IOException { GHHooks.repoContext(this, owner).deleteHook(id); } /** * Sets {@link #getCompare(String, String)} to return a {@link GHCompare} that uses a paginated commit list instead * of limiting to 250 results. * * By default, {@link GHCompare} returns all commits in the comparison as part of the request, limited to 250 * results. More recently GitHub added the ability to return the commits as a paginated query allowing for more than * 250 results. * * @param value * true if you want commits returned in paginated form. */ public void setCompareUsePaginatedCommits(boolean value) { compareUsePaginatedCommits = value; } /** * Gets a comparison between 2 points in the repository. This would be similar to calling * <code>git log id1...id2</code> against a local repository. * * @param id1 * an identifier for the first point to compare from, this can be a sha1 ID (for a commit, tag etc) or a * direct tag name * @param id2 * an identifier for the second point to compare to. Can be the same as the first point. * @return the comparison output * @throws IOException * on failure communicating with GitHub */ public GHCompare getCompare(String id1, String id2) throws IOException { final Requester requester = root().createRequest() .withUrlPath(getApiTailUrl(String.format("compare/%s...%s", id1, id2))); if (compareUsePaginatedCommits) { requester.with("per_page", 1).with("page", 1); } requester.injectMappingValue("GHCompare_usePaginatedCommits", compareUsePaginatedCommits); GHCompare compare = requester.fetch(GHCompare.class); return compare.lateBind(this); } /** * Gets compare. * * @param id1 * the id 1 * @param id2 * the id 2 * @return the compare * @throws IOException * the io exception */ public GHCompare getCompare(GHCommit id1, GHCommit id2) throws IOException { return getCompare(id1.getSHA1(), id2.getSHA1()); } /** * Gets compare. * * @param id1 * the id 1 * @param id2 * the id 2 * @return the compare * @throws IOException * the io exception */ public GHCompare getCompare(GHBranch id1, GHBranch id2) throws IOException { GHRepository owner1 = id1.getOwner(); GHRepository owner2 = id2.getOwner(); // If the owner of the branches is different, we have a cross-fork compare. if (owner1 != null && owner2 != null) { String ownerName1 = owner1.getOwnerName(); String ownerName2 = owner2.getOwnerName(); if (!StringUtils.equals(ownerName1, ownerName2)) { String qualifiedName1 = String.format("%s:%s", ownerName1, id1.getName()); String qualifiedName2 = String.format("%s:%s", ownerName2, id2.getName()); return getCompare(qualifiedName1, qualifiedName2); } } return getCompare(id1.getName(), id2.getName()); } /** * Retrieves all refs for the github repository. * * @return an array of GHRef elements coresponding with the refs in the remote repository. * @throws IOException * on failure communicating with GitHub */ public GHRef[] getRefs() throws IOException { return listRefs().toArray(); } /** * Retrieves all refs for the github repository. * * @return paged iterable of all refs * @throws IOException * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public PagedIterable<GHRef> listRefs() throws IOException { return listRefs(""); } /** * Retrieves all refs of the given type for the current GitHub repository. * * @param refType * the type of reg to search for e.g. <code>tags</code> or <code>commits</code> * @return an array of all refs matching the request type * @throws IOException * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public GHRef[] getRefs(String refType) throws IOException { return listRefs(refType).toArray(); } /** * Retrieves all refs of the given type for the current GitHub repository. * * @param refType * the type of reg to search for e.g. <code>tags</code> or <code>commits</code> * @return paged iterable of all refs of the specified type * @throws IOException * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public PagedIterable<GHRef> listRefs(String refType) throws IOException { return GHRef.readMatching(this, refType); } /** * Retrive a ref of the given type for the current GitHub repository. * * @param refName * eg: heads/branch * @return refs matching the request type * @throws IOException * on failure communicating with GitHub, potentially due to an invalid ref type being requested */ public GHRef getRef(String refName) throws IOException { return GHRef.read(this, refName); } /** * Returns the <strong>annotated</strong> tag object. Only valid if the {@link GHRef#getObject()} has a * {@link GHRef.GHObject#getType()} of {@code tag}. * * @param sha * the sha of the tag object * @return the annotated tag object * @throws IOException * the io exception */ public GHTagObject getTagObject(String sha) throws IOException { return root().createRequest().withUrlPath(getApiTailUrl("git/tags/" + sha)).fetch(GHTagObject.class).wrap(this); } /** * Retrive a tree of the given type for the current GitHub repository. * * @param sha * sha number or branch name ex: "main" * @return refs matching the request type * @throws IOException * on failure communicating with GitHub, potentially due to an invalid tree type being requested */ public GHTree getTree(String sha) throws IOException { String url = String.format("/repos/%s/%s/git/trees/%s", getOwnerName(), name, sha); return root().createRequest().withUrlPath(url).fetch(GHTree.class).wrap(this); } /** * Create tree gh tree builder. * * @return the gh tree builder */ public GHTreeBuilder createTree() { return new GHTreeBuilder(this); } /** * Retrieves the tree for the current GitHub repository, recursively as described in here: * https://developer.github.com/v3/git/trees/#get-a-tree-recursively * * @param sha * sha number or branch name ex: "main" * @param recursive * use 1 * @return the tree recursive * @throws IOException * on failure communicating with GitHub, potentially due to an invalid tree type being requested */ public GHTree getTreeRecursive(String sha, int recursive) throws IOException { String url = String.format("/repos/%s/%s/git/trees/%s", getOwnerName(), name, sha); return root().createRequest().with("recursive", recursive).withUrlPath(url).fetch(GHTree.class).wrap(this); } /** * Obtains the metadata &amp; the content of a blob. * * <p> * This method retrieves the whole content in memory, so beware when you are dealing with large BLOB. * * @param blobSha * the blob sha * @return the blob * @throws IOException * the io exception * @see <a href="https://developer.github.com/v3/git/blobs/#get-a-blob">Get a blob</a> * @see #readBlob(String) #readBlob(String) */ public GHBlob getBlob(String blobSha) throws IOException { String target = getApiTailUrl("git/blobs/" + blobSha); return root().createRequest().withUrlPath(target).fetch(GHBlob.class); } /** * Create blob gh blob builder. * * @return the gh blob builder */ public GHBlobBuilder createBlob() { return new GHBlobBuilder(this); } /** * Reads the content of a blob as a stream for better efficiency. * * @param blobSha * the blob sha * @return the input stream * @throws IOException * the io exception * @see <a href="https://developer.github.com/v3/git/blobs/#get-a-blob">Get a blob</a> * @see #getBlob(String) #getBlob(String) */ public InputStream readBlob(String blobSha) throws IOException { String target = getApiTailUrl("git/blobs/" + blobSha); // https://developer.github.com/v3/media/ describes this media type return root().createRequest() .withHeader("Accept", "application/vnd.github.v3.raw") .withUrlPath(target) .fetchStream(Requester::copyInputStream); } /** * Gets a commit object in this repository. * * @param sha1 * the sha 1 * @return the commit * @throws IOException * the io exception */ public GHCommit getCommit(String sha1) throws IOException { GHCommit c = commits.get(sha1); if (c == null) { c = root().createRequest() .withUrlPath(String.format("/repos/%s/%s/commits/%s", getOwnerName(), name, sha1)) .fetch(GHCommit.class) .wrapUp(this); commits.put(sha1, c); } return c; } /** * Create commit gh commit builder. * * @return the gh commit builder */ public GHCommitBuilder createCommit() { return new GHCommitBuilder(this); } /** * Lists all the commits. * * @return the paged iterable */ public PagedIterable<GHCommit> listCommits() { return root().createRequest() .withUrlPath(String.format("/repos/%s/%s/commits", getOwnerName(), name)) .toIterable(GHCommit[].class, item -> item.wrapUp(this)); } /** * Search commits by specifying filters through a builder pattern. * * @return the gh commit query builder */ public GHCommitQueryBuilder queryCommits() { return new GHCommitQueryBuilder(this); } /** * Lists up all the commit comments in this repository. * * @return the paged iterable */ public PagedIterable<GHCommitComment> listCommitComments() { return root().createRequest() .withUrlPath(String.format("/repos/%s/%s/comments", getOwnerName(), name)) .toIterable(GHCommitComment[].class, item -> item.wrap(this)); } /** * Lists all comments on a specific commit. * * @param commitSha * the hash of the commit * * @return the paged iterable */ public PagedIterable<GHCommitComment> listCommitComments(String commitSha) { return root().createRequest() .withUrlPath(String.format("/repos/%s/%s/commits/%s/comments", getOwnerName(), name, commitSha)) .toIterable(GHCommitComment[].class, item -> item.wrap(this)); } /** * Gets the basic license details for the repository. * <p> * * @return null if there's no license. * @throws IOException * as usual but also if you don't use the preview connector */ public GHLicense getLicense() throws IOException { GHContentWithLicense lic = getLicenseContent_(); return lic != null ? lic.license : null; } /** * Retrieves the contents of the repository's license file - makes an additional API call * <p> * * @return details regarding the license contents, or null if there's no license. * @throws IOException * as usual but also if you don't use the preview connector */ public GHContent getLicenseContent() throws IOException { return getLicenseContent_(); } private GHContentWithLicense getLicenseContent_() throws IOException { try { return root().createRequest() .withUrlPath(getApiTailUrl("license")) .fetch(GHContentWithLicense.class) .wrap(this); } catch (FileNotFoundException e) { return null; } } /** * /** Lists all the commit statuses attached to the given commit, newer ones first. * * @param sha1 * the sha 1 * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHCommitStatus> listCommitStatuses(final String sha1) throws IOException { return root().createRequest() .withUrlPath(String.format("/repos/%s/%s/statuses/%s", getOwnerName(), name, sha1)) .toIterable(GHCommitStatus[].class, null); } /** * Gets the last status of this commit, which is what gets shown in the UI. * * @param sha1 * the sha 1 * @return the last commit status * @throws IOException * the io exception */ public GHCommitStatus getLastCommitStatus(String sha1) throws IOException { List<GHCommitStatus> v = listCommitStatuses(sha1).toList(); return v.isEmpty() ? null : v.get(0); } /** * Gets check runs for given ref. * * @param ref * ref * @return check runs for given ref * @throws IOException * the io exception * @see <a href="https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref">List check runs * for a specific ref</a> */ @Preview(ANTIOPE) public PagedIterable<GHCheckRun> getCheckRuns(String ref) throws IOException { GitHubRequest request = root().createRequest() .withUrlPath(String.format("/repos/%s/%s/commits/%s/check-runs", getOwnerName(), name, ref)) .withPreview(ANTIOPE) .build(); return new GHCheckRunsIterable(this, request); } /** * Creates a commit status * * @param sha1 * the sha 1 * @param state * the state * @param targetUrl * Optional parameter that points to the URL that has more details. * @param description * Optional short description. * @param context * Optinal commit status context. * @return the gh commit status * @throws IOException * the io exception */ public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description, String context) throws IOException { return root().createRequest() .method("POST") .with("state", state) .with("target_url", targetUrl) .with("description", description) .with("context", context) .withUrlPath(String.format("/repos/%s/%s/statuses/%s", getOwnerName(), this.name, sha1)) .fetch(GHCommitStatus.class); } /** * Create commit status gh commit status. * * @param sha1 * the sha 1 * @param state * the state * @param targetUrl * the target url * @param description * the description * @return the gh commit status * @throws IOException * the io exception * @see #createCommitStatus(String, GHCommitState, String, String, String) #createCommitStatus(String, * GHCommitState,String,String,String) */ public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description) throws IOException { return createCommitStatus(sha1, state, targetUrl, description, null); } /** * Creates a check run for a commit. * * @param name * an identifier for the run * @param headSHA * the commit hash * @return a builder which you should customize, then call {@link GHCheckRunBuilder#create} */ @Preview(ANTIOPE) public @NonNull GHCheckRunBuilder createCheckRun(@NonNull String name, @NonNull String headSHA) { return new GHCheckRunBuilder(this, name, headSHA); } /** * Updates an existing check run. * * @param checkId * the existing checkId * @return a builder which you should customize, then call {@link GHCheckRunBuilder#create} */ @Preview(BAPTISTE) public @NonNull GHCheckRunBuilder updateCheckRun(long checkId) { return new GHCheckRunBuilder(this, checkId); } /** * Lists repository events. * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHEventInfo> listEvents() throws IOException { return root().createRequest() .withUrlPath(String.format("/repos/%s/%s/events", getOwnerName(), name)) .toIterable(GHEventInfo[].class, null); } /** * Lists labels in this repository. * <p> * https://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHLabel> listLabels() throws IOException { return GHLabel.readAll(this); } /** * Gets label. * * @param name * the name * @return the label * @throws IOException * the io exception */ public GHLabel getLabel(String name) throws IOException { return GHLabel.read(this, name); } /** * Create label gh label. * * @param name * the name * @param color * the color * @return the gh label * @throws IOException * the io exception */ public GHLabel createLabel(String name, String color) throws IOException { return GHLabel.create(this).name(name).color(color).description("").done(); } /** * Description is still in preview. * * @param name * the name * @param color * the color * @param description * the description * @return gh label * @throws IOException * the io exception */ public GHLabel createLabel(String name, String color, String description) throws IOException { return GHLabel.create(this).name(name).color(color).description(description).done(); } /** * Lists all the invitations. * * @return the paged iterable */ public PagedIterable<GHInvitation> listInvitations() { return root().createRequest() .withUrlPath(String.format("/repos/%s/%s/invitations", getOwnerName(), name)) .toIterable(GHInvitation[].class, null); } /** * Lists all the subscribers (aka watchers.) * <p> * https://developer.github.com/v3/activity/watching/ * * @return the paged iterable */ public PagedIterable<GHUser> listSubscribers() { return listUsers("subscribers"); } /** * Lists all the users who have starred this repo based on the old version of the API. For additional information, * like date when the repository was starred, see {@link #listStargazers2()} * * @return the paged iterable */ public PagedIterable<GHUser> listStargazers() { return listUsers("stargazers"); } /** * Lists all the users who have starred this repo based on new version of the API, having extended information like * the time when the repository was starred. For compatibility with the old API see {@link #listStargazers()} * * @return the paged iterable */ public PagedIterable<GHStargazer> listStargazers2() { return root().createRequest() .withPreview("application/vnd.github.v3.star+json") .withUrlPath(getApiTailUrl("stargazers")) .toIterable(GHStargazer[].class, item -> item.wrapUp(this)); } private PagedIterable<GHUser> listUsers(final String suffix) { return listUsers(root().createRequest(), suffix); } private PagedIterable<GHUser> listUsers(Requester requester, final String suffix) { return requester.withUrlPath(getApiTailUrl(suffix)).toIterable(GHUser[].class, null); } /** * See https://api.github.com/hooks for possible names and their configuration scheme. TODO: produce type-safe * binding * * @param name * Type of the hook to be created. See https://api.github.com/hooks for possible names. * @param config * The configuration hash. * @param events * Can be null. Types of events to hook into. * @param active * the active * @return the gh hook * @throws IOException * the io exception */ public GHHook createHook(String name, Map<String, String> config, Collection<GHEvent> events, boolean active) throws IOException { return GHHooks.repoContext(this, owner).createHook(name, config, events, active); } /** * Create web hook gh hook. * * @param url * the url * @param events * the events * @return the gh hook * @throws IOException * the io exception */ public GHHook createWebHook(URL url, Collection<GHEvent> events) throws IOException { return createHook("web", Collections.singletonMap("url", url.toExternalForm()), events, true); } /** * Create web hook gh hook. * * @param url * the url * @return the gh hook * @throws IOException * the io exception */ public GHHook createWebHook(URL url) throws IOException { return createWebHook(url, null); } /** * Returns a set that represents the post-commit hook URLs. The returned set is live, and changes made to them are * reflected to GitHub. * * @return the post commit hooks * @deprecated Use {@link #getHooks()} and {@link #createHook(String, Map, Collection, boolean)} */ @SuppressFBWarnings(value = { "DMI_COLLECTION_OF_URLS", "EI_EXPOSE_REP" }, justification = "It causes a performance degradation, but we have already exposed it to the API") @Deprecated public Set<URL> getPostCommitHooks() { synchronized (this) { if (postCommitHooks == null) { postCommitHooks = setupPostCommitHooks(); } return postCommitHooks; } } /** * Live set view of the post-commit hook. */ @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "It causes a performance degradation, but we have already exposed it to the API") @SkipFromToString private /* final */ transient Set<URL> postCommitHooks; @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "It causes a performance degradation, but we have already exposed it to the API") private Set<URL> setupPostCommitHooks() { return new AbstractSet<URL>() { private List<URL> getPostCommitHooks() { try { List<URL> r = new ArrayList<>(); for (GHHook h : getHooks()) { if (h.getName().equals("web")) { r.add(new URL(h.getConfig().get("url"))); } } return r; } catch (IOException e) { throw new GHException("Failed to retrieve post-commit hooks", e); } } @Override public Iterator<URL> iterator() { return getPostCommitHooks().iterator(); } @Override public int size() { return getPostCommitHooks().size(); } @Override public boolean add(URL url) { try { createWebHook(url); return true; } catch (IOException e) { throw new GHException("Failed to update post-commit hooks", e); } } @Override public boolean remove(Object url) { try { String _url = ((URL) url).toExternalForm(); for (GHHook h : getHooks()) { if (h.getName().equals("web") && h.getConfig().get("url").equals(_url)) { h.delete(); return true; } } return false; } catch (IOException e) { throw new GHException("Failed to update post-commit hooks", e); } } }; } /** * Gets branches by {@linkplain GHBranch#getName() their names}. * * @return the branches * @throws IOException * the io exception */ public Map<String, GHBranch> getBranches() throws IOException { Map<String, GHBranch> r = new TreeMap<String, GHBranch>(); for (GHBranch p : root().createRequest() .withUrlPath(getApiTailUrl("branches")) .toIterable(GHBranch[].class, item -> item.wrap(this)) .toArray()) { r.put(p.getName(), p); } return r; } /** * Gets branch. * * @param name * the name * @return the branch * @throws IOException * the io exception */ public GHBranch getBranch(String name) throws IOException { return root().createRequest().withUrlPath(getApiTailUrl("branches/" + name)).fetch(GHBranch.class).wrap(this); } /** * Gets milestones. * * @return the milestones * @throws IOException * the io exception * @deprecated Use {@link #listMilestones(GHIssueState)} */ public Map<Integer, GHMilestone> getMilestones() throws IOException { Map<Integer, GHMilestone> milestones = new TreeMap<Integer, GHMilestone>(); for (GHMilestone m : listMilestones(GHIssueState.OPEN)) { milestones.put(m.getNumber(), m); } return milestones; } /** * Lists up all the milestones in this repository. * * @param state * the state * @return the paged iterable */ public PagedIterable<GHMilestone> listMilestones(final GHIssueState state) { return root().createRequest() .with("state", state) .withUrlPath(getApiTailUrl("milestones")) .toIterable(GHMilestone[].class, item -> item.lateBind(this)); } /** * Gets milestone. * * @param number * the number * @return the milestone * @throws IOException * the io exception */ public GHMilestone getMilestone(int number) throws IOException { GHMilestone m = milestones.get(number); if (m == null) { m = root().createRequest().withUrlPath(getApiTailUrl("milestones/" + number)).fetch(GHMilestone.class); m.owner = this; milestones.put(m.getNumber(), m); } return m; } /** * Gets file content. * * @param path * the path * @return the file content * @throws IOException * the io exception */ public GHContent getFileContent(String path) throws IOException { return getFileContent(path, null); } /** * Gets file content. * * @param path * the path * @param ref * the ref * @return the file content * @throws IOException * the io exception */ public GHContent getFileContent(String path, String ref) throws IOException { Requester requester = root().createRequest(); String target = getApiTailUrl("contents/" + path); return requester.with("ref", ref).withUrlPath(target).fetch(GHContent.class).wrap(this); } /** * Gets directory content. * * @param path * the path * @return the directory content * @throws IOException * the io exception */ public List<GHContent> getDirectoryContent(String path) throws IOException { return getDirectoryContent(path, null); } /** * Gets directory content. * * @param path * the path * @param ref * the ref * @return the directory content * @throws IOException * the io exception */ public List<GHContent> getDirectoryContent(String path, String ref) throws IOException { Requester requester = root().createRequest(); while (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } String target = getApiTailUrl("contents/" + path); return requester.with("ref", ref) .withUrlPath(target) .toIterable(GHContent[].class, item -> item.wrap(this)) .toList(); } /** * https://developer.github.com/v3/repos/contents/#get-the-readme * * @return the readme * @throws IOException * the io exception */ public GHContent getReadme() throws IOException { Requester requester = root().createRequest(); return requester.withUrlPath(getApiTailUrl("readme")).fetch(GHContent.class).wrap(this); } /** * Creates a new content, or update an existing content. * * @return the gh content builder */ public GHContentBuilder createContent() { return new GHContentBuilder(this); } /** * Use {@link #createContent()}. * * @param content * the content * @param commitMessage * the commit message * @param path * the path * @return the gh content update response * @throws IOException * the io exception */ @Deprecated public GHContentUpdateResponse createContent(String content, String commitMessage, String path) throws IOException { return createContent().content(content).message(commitMessage).path(path).commit(); } /** * Use {@link #createContent()}. * * @param content * the content * @param commitMessage * the commit message * @param path * the path * @param branch * the branch * @return the gh content update response * @throws IOException * the io exception */ @Deprecated public GHContentUpdateResponse createContent(String content, String commitMessage, String path, String branch) throws IOException { return createContent().content(content).message(commitMessage).path(path).branch(branch).commit(); } /** * Use {@link #createContent()}. * * @param contentBytes * the content bytes * @param commitMessage * the commit message * @param path * the path * @return the gh content update response * @throws IOException * the io exception */ @Deprecated public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path) throws IOException { return createContent().content(contentBytes).message(commitMessage).path(path).commit(); } /** * Use {@link #createContent()}. * * @param contentBytes * the content bytes * @param commitMessage * the commit message * @param path * the path * @param branch * the branch * @return the gh content update response * @throws IOException * the io exception */ @Deprecated public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path, String branch) throws IOException { return createContent().content(contentBytes).message(commitMessage).path(path).branch(branch).commit(); } /** * Create milestone gh milestone. * * @param title * the title * @param description * the description * @return the gh milestone * @throws IOException * the io exception */ public GHMilestone createMilestone(String title, String description) throws IOException { return root().createRequest() .method("POST") .with("title", title) .with("description", description) .withUrlPath(getApiTailUrl("milestones")) .fetch(GHMilestone.class) .lateBind(this); } /** * Add deploy key gh deploy key. * * @param title * the title * @param key * the key * @return the gh deploy key * @throws IOException * the io exception */ public GHDeployKey addDeployKey(String title, String key) throws IOException { return root().createRequest() .method("POST") .with("title", title) .with("key", key) .withUrlPath(getApiTailUrl("keys")) .fetch(GHDeployKey.class) .lateBind(this); } /** * Gets deploy keys. * * @return the deploy keys * @throws IOException * the io exception */ public List<GHDeployKey> getDeployKeys() throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("keys")) .toIterable(GHDeployKey[].class, item -> item.lateBind(this)) .toList(); } /** * Forked repositories have a 'source' attribute that specifies the ultimate source of the forking chain. * * @return {@link GHRepository} that points to the root repository where this repository is forked (indirectly or * directly) from. Otherwise null. * @throws IOException * the io exception * @see #getParent() #getParent() */ @SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior") public GHRepository getSource() throws IOException { if (fork && source == null) { populate(); } if (source == null) { return null; } return source; } /** * Forked repositories have a 'parent' attribute that specifies the repository this repository is directly forked * from. If we keep traversing {@link #getParent()} until it returns null, that is {@link #getSource()}. * * @return {@link GHRepository} that points to the repository where this repository is forked directly from. * Otherwise null. * @throws IOException * the io exception * @see #getSource() #getSource() */ @SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior") public GHRepository getParent() throws IOException { if (fork && parent == null) { populate(); } if (parent == null) { return null; } return parent; } /** * Subscribes to this repository to get notifications. * * @param subscribed * the subscribed * @param ignored * the ignored * @return the gh subscription * @throws IOException * the io exception */ public GHSubscription subscribe(boolean subscribed, boolean ignored) throws IOException { return root().createRequest() .method("PUT") .with("subscribed", subscribed) .with("ignored", ignored) .withUrlPath(getApiTailUrl("subscription")) .fetch(GHSubscription.class) .wrapUp(this); } /** * Returns the current subscription. * * @return null if no subscription exists. * @throws IOException * the io exception */ public GHSubscription getSubscription() throws IOException { try { return root().createRequest() .withUrlPath(getApiTailUrl("subscription")) .fetch(GHSubscription.class) .wrapUp(this); } catch (FileNotFoundException e) { return null; } } /** * List contributors paged iterable. * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<Contributor> listContributors() throws IOException { return root().createRequest().withUrlPath(getApiTailUrl("contributors")).toIterable(Contributor[].class, null); } /** * The type Contributor. */ public static class Contributor extends GHUser { private int contributions; /** * Gets contributions. * * @return the contributions */ public int getContributions() { return contributions; } @Override public int hashCode() { // We ignore contributions in the calculation return super.hashCode(); } @Override public boolean equals(Object obj) { // We ignore contributions in the calculation return super.equals(obj); } } /** * Returns the statistics for this repository. * * @return the statistics */ public GHRepositoryStatistics getStatistics() { // TODO: Use static object and introduce refresh() method, // instead of returning new object each time. return new GHRepositoryStatistics(this); } /** * Create a project for this repository. * * @param name * the name * @param body * the body * @return the gh project * @throws IOException * the io exception */ public GHProject createProject(String name, String body) throws IOException { return root().createRequest() .method("POST") .withPreview(INERTIA) .with("name", name) .with("body", body) .withUrlPath(getApiTailUrl("projects")) .fetch(GHProject.class) .lateBind(this); } /** * Returns the projects for this repository. * * @param status * The status filter (all, open or closed). * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHProject> listProjects(final GHProject.ProjectStateFilter status) throws IOException { return root().createRequest() .withPreview(INERTIA) .with("state", status) .withUrlPath(getApiTailUrl("projects")) .toIterable(GHProject[].class, item -> item.lateBind(this)); } /** * Returns open projects for this repository. * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHProject> listProjects() throws IOException { return listProjects(GHProject.ProjectStateFilter.OPEN); } /** * Render a Markdown document. * <p> * In {@linkplain MarkdownMode#GFM GFM mode}, issue numbers and user mentions are linked accordingly. * * @param text * the text * @param mode * the mode * @return the reader * @throws IOException * the io exception * @see GitHub#renderMarkdown(String) GitHub#renderMarkdown(String) */ public Reader renderMarkdown(String text, MarkdownMode mode) throws IOException { return new InputStreamReader( root().createRequest() .method("POST") .with("text", text) .with("mode", mode == null ? null : mode.toString()) .with("context", getFullName()) .withUrlPath("/markdown") .fetchStream(Requester::copyInputStream), "UTF-8"); } /** * List all the notifications in a repository for the current user. * * @return the gh notification stream */ public GHNotificationStream listNotifications() { return new GHNotificationStream(root(), getApiTailUrl("/notifications")); } /** * <a href= * "https://developer.github.com/v3/repos/traffic/#views">https://developer.github.com/v3/repos/traffic/#views</a> * * @return the view traffic * @throws IOException * the io exception */ public GHRepositoryViewTraffic getViewTraffic() throws IOException { return root().createRequest().withUrlPath(getApiTailUrl("/traffic/views")).fetch(GHRepositoryViewTraffic.class); } /** * <a href= * "https://developer.github.com/v3/repos/traffic/#clones">https://developer.github.com/v3/repos/traffic/#clones</a> * * @return the clone traffic * @throws IOException * the io exception */ public GHRepositoryCloneTraffic getCloneTraffic() throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("/traffic/clones")) .fetch(GHRepositoryCloneTraffic.class); } @Override public int hashCode() { return ("Repository:" + getOwnerName() + ":" + name).hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof GHRepository) { GHRepository that = (GHRepository) obj; return this.getOwnerName().equals(that.getOwnerName()) && this.name.equals(that.name); } return false; } String getApiTailUrl(String tail) { if (tail.length() > 0 && !tail.startsWith("/")) { tail = '/' + tail; } return "/repos/" + getOwnerName() + "/" + name + tail; } /** * Get all issue events for this repository. See * https://developer.github.com/v3/issues/events/#list-events-for-a-repository * * @return the paged iterable * @throws IOException * the io exception */ public PagedIterable<GHIssueEvent> listIssueEvents() throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("issues/events")) .toIterable(GHIssueEvent[].class, null); } /** * Get a single issue event. See https://developer.github.com/v3/issues/events/#get-a-single-event * * @param id * the id * @return the issue event * @throws IOException * the io exception */ public GHIssueEvent getIssueEvent(long id) throws IOException { return root().createRequest().withUrlPath(getApiTailUrl("issues/events/" + id)).fetch(GHIssueEvent.class); } /** * Lists all the workflows of this repository. * * @return the paged iterable */ public PagedIterable<GHWorkflow> listWorkflows() { return new GHWorkflowsIterable(this); } /** * Gets a workflow by id. * * @param id * the id of the workflow run * @return the workflow run * @throws IOException * the io exception */ public GHWorkflow getWorkflow(long id) throws IOException { return getWorkflow(String.valueOf(id)); } /** * Gets a workflow by name of the file. * * @param nameOrId * either the name of the file (e.g. my-workflow.yml) or the id as a string * @return the workflow run * @throws IOException * the io exception */ public GHWorkflow getWorkflow(String nameOrId) throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("actions/workflows"), nameOrId) .fetch(GHWorkflow.class) .wrapUp(this); } /** * Retrieves workflow runs. * * @return the workflow run query builder */ public GHWorkflowRunQueryBuilder queryWorkflowRuns() { return new GHWorkflowRunQueryBuilder(this); } /** * Gets a workflow run. * * @param id * the id of the workflow run * @return the workflow run * @throws IOException * the io exception */ public GHWorkflowRun getWorkflowRun(long id) throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("actions/runs"), String.valueOf(id)) .fetch(GHWorkflowRun.class) .wrapUp(this); } /** * Lists all the artifacts of this repository. * * @return the paged iterable */ public PagedIterable<GHArtifact> listArtifacts() { return new GHArtifactsIterable(this, root().createRequest().withUrlPath(getApiTailUrl("actions/artifacts"))); } /** * Gets an artifact by id. * * @param id * the id of the artifact * @return the artifact * @throws IOException * the io exception */ public GHArtifact getArtifact(long id) throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("actions/artifacts"), String.valueOf(id)) .fetch(GHArtifact.class) .wrapUp(this); } /** * Gets a job from a workflow run by id. * * @param id * the id of the job * @return the job * @throws IOException * the io exception */ public GHWorkflowJob getWorkflowJob(long id) throws IOException { return root().createRequest() .withUrlPath(getApiTailUrl("/actions/jobs"), String.valueOf(id)) .fetch(GHWorkflowJob.class) .wrapUp(this); } // Only used within listTopics(). private static class Topics { public List<String> names; } /** * Return the topics for this repository. See * https://developer.github.com/v3/repos/#list-all-topics-for-a-repository * * @return the list * @throws IOException * the io exception */ public List<String> listTopics() throws IOException { Topics topics = root().createRequest() .withPreview(MERCY) .withUrlPath(getApiTailUrl("topics")) .fetch(Topics.class); return topics.names; } /** * Set the topics for this repository. See * https://developer.github.com/v3/repos/#replace-all-topics-for-a-repository * * @param topics * the topics * @throws IOException * the io exception */ public void setTopics(List<String> topics) throws IOException { root().createRequest() .method("PUT") .with("names", topics) .withPreview(MERCY) .withUrlPath(getApiTailUrl("topics")) .send(); } /** * Create a tag. See https://developer.github.com/v3/git/tags/#create-a-tag-object * * @param tag * The tag's name. * @param message * The tag message. * @param object * The SHA of the git object this is tagging. * @param type * The type of the object we're tagging: "commit", "tree" or "blob". * @return The newly created tag. * @throws java.io.IOException * The IO exception. */ public GHTagObject createTag(String tag, String message, String object, String type) throws IOException { return root().createRequest() .method("POST") .with("tag", tag) .with("message", message) .with("object", object) .with("type", type) .withUrlPath(getApiTailUrl("git/tags")) .fetch(GHTagObject.class) .wrap(this); } /** * Streams a zip archive of the repository, optionally at a given <code>ref</code>. * * @param <T> * the type of result * @param streamFunction * The {@link InputStreamFunction} that will process the stream * @param ref * if <code>null</code> the repository's default branch, usually <code>main</code>, * @throws IOException * The IO exception. * @return the result of reading the stream. */ public <T> T readZip(InputStreamFunction<T> streamFunction, String ref) throws IOException { return downloadArchive("zip", ref, streamFunction); } /** * Streams a tar archive of the repository, optionally at a given <code>ref</code>. * * @param <T> * the type of result * @param streamFunction * The {@link InputStreamFunction} that will process the stream * @param ref * if <code>null</code> the repository's default branch, usually <code>main</code>, * @throws IOException * The IO exception. * @return the result of reading the stream. */ public <T> T readTar(InputStreamFunction<T> streamFunction, String ref) throws IOException { return downloadArchive("tar", ref, streamFunction); } private <T> T downloadArchive(@Nonnull String type, @CheckForNull String ref, @Nonnull InputStreamFunction<T> streamFunction) throws IOException { requireNonNull(streamFunction, "Sink must not be null"); String tailUrl = getApiTailUrl(type + "ball"); if (ref != null) { tailUrl += "/" + ref; } final Requester builder = root().createRequest().method("GET").withUrlPath(tailUrl); return builder.fetchStream(streamFunction); } /** * Populate this object. * * @throws java.io.IOException * The IO exception */ void populate() throws IOException { if (isOffline()) { return; // can't populate if the root is offline } final URL url = requireNonNull(getUrl(), "Missing instance URL!"); try { // IMPORTANT: the url for repository records does not reliably point to the API url. // There is bug in Push event payloads that returns the wrong url. // All other occurrences of "url" take the form "https://api.github.com/...". // For Push event repository records, they take the form "https://github.com/{fullName}". root().createRequest() .withPreview(BAPTISTE) .withPreview(NEBULA) .setRawUrlPath(url.toString()) .fetchInto(this); } catch (HttpException e) { if (e.getCause() instanceof JsonParseException) { root().createRequest() .withPreview(BAPTISTE) .withPreview(NEBULA) .withUrlPath("/repos/" + full_name) .fetchInto(this); } else { throw e; } } } /** * A {@link GHRepositoryBuilder} that allows multiple properties to be updated per request. * * Consumer must call {@link #done()} to commit changes. */ @BetaApi public static class Updater extends GHRepositoryBuilder<Updater> { protected Updater(@Nonnull GHRepository repository) { super(Updater.class, repository.root(), null); // even when we don't change the name, we need to send it in // this requirement may be out-of-date, but we do not want to break it requester.with("name", repository.name); requester.method("PATCH").withUrlPath(repository.getApiTailUrl("")); } } /** * A {@link GHRepositoryBuilder} that allows multiple properties to be updated per request. * * Consumer must call {@link #done()} to commit changes. */ @BetaApi public static class Setter extends GHRepositoryBuilder<GHRepository> { protected Setter(@Nonnull GHRepository repository) { super(GHRepository.class, repository.root(), null); // even when we don't change the name, we need to send it in // this requirement may be out-of-date, but we do not want to break it requester.with("name", repository.name); requester.method("PATCH").withUrlPath(repository.getApiTailUrl("")); } } }
package com.github.megatronking.svg.sample; import com.github.megatronking.svg.sample.animation.AnimationSampleActivity; import com.github.megatronking.svg.sample.extend.ExtendSampleActivity; import com.github.megatronking.svg.sample.graphics.GraphicsSampleActivity; import com.github.megatronking.svg.sample.matrix.MatrixSampleActivity; import java.util.ArrayList; import java.util.List; public class MainActivity extends ListSampleActivity { @Override protected List<SampleData> sampleData() { final List<SampleData> sampleData = new ArrayList<>(); sampleData.add(new SampleData("Icon Samples", IconSampleActivity.class.getName())); sampleData.add(new SampleData("Graphics Samples", GraphicsSampleActivity.class.getName())); sampleData.add(new SampleData("Matrix Samples", MatrixSampleActivity.class.getName())); sampleData.add(new SampleData("Animation Samples", AnimationSampleActivity.class.getName())); sampleData.add(new SampleData("Extend Samples", ExtendSampleActivity.class.getName())); return sampleData; } }
/* * 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.benchmark.search.geo; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.SizeValue; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.geoDistanceQuery; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; /** */ public class GeoDistanceSearchBenchmark { public static void main(String[] args) throws Exception { Node node = NodeBuilder.nodeBuilder().clusterName(GeoDistanceSearchBenchmark.class.getSimpleName()).node(); Client client = node.client(); ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); if (clusterHealthResponse.isTimedOut()) { System.err.println("Failed to wait for green status, bailing"); System.exit(1); } final long NUM_DOCS = SizeValue.parseSizeValue("1m").singles(); final long NUM_WARM = 50; final long NUM_RUNS = 100; if (client.admin().indices().prepareExists("test").execute().actionGet().isExists()) { System.out.println("Found an index, count: " + client.prepareSearch("test").setSize(0).setQuery(QueryBuilders.matchAllQuery()).execute().actionGet().getHits().totalHits()); } else { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") .startObject("properties").startObject("location").field("type", "geo_point").field("lat_lon", true).endObject().endObject() .endObject().endObject().string(); client.admin().indices().prepareCreate("test") .setSettings(Settings.settingsBuilder().put("index.number_of_shards", 1).put("index.number_of_replicas", 0)) .addMapping("type1", mapping) .execute().actionGet(); System.err.println("--> Indexing [" + NUM_DOCS + "]"); for (long i = 0; i < NUM_DOCS; ) { client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "New York") .startObject("location").field("lat", 40.7143528).field("lon", -74.0059731).endObject() .endObject()).execute().actionGet(); // to NY: 5.286 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Times Square") .startObject("location").field("lat", 40.759011).field("lon", -73.9844722).endObject() .endObject()).execute().actionGet(); // to NY: 0.4621 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Tribeca") .startObject("location").field("lat", 40.718266).field("lon", -74.007819).endObject() .endObject()).execute().actionGet(); // to NY: 1.258 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Soho") .startObject("location").field("lat", 40.7247222).field("lon", -74).endObject() .endObject()).execute().actionGet(); // to NY: 8.572 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Brooklyn") .startObject("location").field("lat", 40.65).field("lon", -73.95).endObject() .endObject()).execute().actionGet(); if ((i % 10000) == 0) { System.err.println("--> indexed " + i); } } System.err.println("Done indexed"); client.admin().indices().prepareFlush("test").execute().actionGet(); client.admin().indices().prepareRefresh().execute().actionGet(); } System.err.println("--> Warming up (ARC) - optimize_bbox"); long start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.ARC, "memory"); } long totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (ARC) - optimize_bbox (memory) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (ARC) - optimize_bbox (memory)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.ARC, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (ARC) - optimize_bbox " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (ARC) - optimize_bbox (indexed)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.ARC, "indexed"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (ARC) - optimize_bbox (indexed) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (ARC) - optimize_bbox (indexed)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.ARC, "indexed"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (ARC) - optimize_bbox (indexed) " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (ARC) - no optimize_bbox"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.ARC, "none"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (ARC) - no optimize_bbox " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (ARC) - no optimize_bbox"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.ARC, "none"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (ARC) - no optimize_bbox " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (SLOPPY_ARC)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.SLOPPY_ARC, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (SLOPPY_ARC) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (SLOPPY_ARC)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.SLOPPY_ARC, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (SLOPPY_ARC) " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (PLANE)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.PLANE, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (PLANE) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (PLANE)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.PLANE, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (PLANE) " + (totalTime / NUM_RUNS) + "ms"); node.close(); } public static void run(Client client, GeoDistance geoDistance, String optimizeBbox) { client.prepareSearch() // from NY .setSize(0) .setQuery(boolQuery().must(matchAllQuery()).filter(geoDistanceQuery("location") .distance("2km") .optimizeBbox(optimizeBbox) .geoDistance(geoDistance) .point(40.7143528, -74.0059731))) .execute().actionGet(); } }
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Wed 12 Jul 2017 at 16:10:00 PST by ian morris nieves // modified on Sat 23 February 2008 at 10:15:47 PST by lamport // modified on Fri Aug 10 15:09:07 PDT 2001 by yuanyu package tlc2.value.impl; import java.io.EOFException; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Set; import tla2sany.semantic.OpDeclNode; import tla2sany.semantic.SymbolNode; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.FingerprintException; import tlc2.tool.StateVec; import tlc2.tool.TLCState; import tlc2.tool.coverage.CostModel; import tlc2.util.FP64; import tlc2.value.IMVPerm; import tlc2.value.IValue; import tlc2.value.IValueInputStream; import tlc2.value.IValueOutputStream; import tlc2.value.ValueInputStream; import tlc2.value.Values; import util.Assert; import util.TLAConstants; import util.UniqueString; public class RecordValue extends Value implements Applicable { public final UniqueString[] names; // the field names public final Value[] values; // the field values private boolean isNorm; public static final RecordValue EmptyRcd = new RecordValue(new UniqueString[0], new Value[0], true); /* Constructor */ public RecordValue(UniqueString[] names, Value[] values, boolean isNorm) { this.names = names; this.values = values; this.isNorm = isNorm; } public RecordValue(UniqueString[] names, Value[] values, boolean isNorm, CostModel cm) { this(names, values, isNorm); this.cm = cm; } public RecordValue(UniqueString name, Value v, boolean isNorm) { this(new UniqueString[] {name}, new Value[] {v}, isNorm); } public RecordValue(UniqueString name, Value v) { this(new UniqueString[] {name}, new Value[] {v}, false); } public RecordValue(final TLCState state) { final OpDeclNode[] vars = state.getVars(); this.names = new UniqueString[vars.length]; this.values = new Value[vars.length]; for (int i = 0; i < vars.length; i++) { this.names[i] = vars[i].getName(); this.values[i] = (Value) state.lookup(this.names[i]); } this.isNorm = false; } @Override public final byte getKind() { return RECORDVALUE; } @Override public final int compareTo(Object obj) { try { RecordValue rcd = obj instanceof Value ? (RecordValue) ((Value)obj).toRcd() : null; if (rcd == null) { if (obj instanceof ModelValue) return 1; Assert.fail("Attempted to compare record:\n" + Values.ppr(this.toString()) + "\nwith non-record\n" + Values.ppr(obj.toString())); } this.normalize(); rcd.normalize(); int len = this.names.length; int cmp = len - rcd.names.length; if (cmp == 0) { for (int i = 0; i < len; i++) { cmp = this.names[i].compareTo(rcd.names[i]); if (cmp != 0) break; cmp = this.values[i].compareTo(rcd.values[i]); if (cmp != 0) break; } } return cmp; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public final boolean equals(Object obj) { try { RecordValue rcd = obj instanceof Value ? (RecordValue) ((Value)obj).toRcd() : null; if (rcd == null) { if (obj instanceof ModelValue) return ((ModelValue) obj).modelValueEquals(this) ; Assert.fail("Attempted to check equality of record:\n" + Values.ppr(this.toString()) + "\nwith non-record\n" + Values.ppr(obj.toString())); } this.normalize(); rcd.normalize(); int len = this.names.length; if (len != rcd.names.length) return false; for (int i = 0; i < len; i++) { if ((!(this.names[i].equals(rcd.names[i]))) || (!(this.values[i].equals(rcd.values[i])))) return false; } return true; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean member(Value elem) { try { Assert.fail("Attempted to check if element:\n" + Values.ppr(elem.toString()) + "\nis in the record:\n" + Values.ppr(this.toString())); return false; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean isFinite() { return true; } @Override public final Value takeExcept(ValueExcept ex) { try { if (ex.idx < ex.path.length) { int rlen = this.names.length; Value[] newValues = new Value[rlen]; Value arcVal = ex.path[ex.idx]; if (arcVal instanceof StringValue) { UniqueString arc = ((StringValue)arcVal).val; for (int i = 0; i < rlen; i++) { if (this.names[i].equals(arc)) { ex.idx++; newValues[i] = this.values[i].takeExcept(ex); } else { newValues[i] = this.values[i]; } } UniqueString[] newNames = this.names; if (!this.isNorm) { newNames = new UniqueString[rlen]; for (int i = 0; i < rlen; i++) { newNames[i] = this.names[i]; } } return new RecordValue(newNames, newValues, this.isNorm); } else { MP.printWarning(EC.TLC_WRONG_RECORD_FIELD_NAME, new String[]{Values.ppr(arcVal.toString())}); } } return ex.value; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value takeExcept(ValueExcept[] exs) { try { Value res = this; for (int i = 0; i < exs.length; i++) { res = res.takeExcept(exs[i]); } return res; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value toRcd() { return this; } @Override public final Value toTuple() { return size() == 0 ? TupleValue.EmptyTuple : super.toTuple(); } @Override public final Value toFcnRcd() { this.normalize(); Value[] dom = new Value[this.names.length]; for (int i = 0; i < this.names.length; i++) { dom[i] = new StringValue(this.names[i], cm); } if (coverage) {cm.incSecondary(dom.length);} return new FcnRcdValue(dom, this.values, this.isNormalized(), cm); } @Override public final int size() { try { return this.names.length; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value apply(Value arg, int control) { try { if (!(arg instanceof StringValue)) { Assert.fail("Attempted to access record by a non-string argument: " + Values.ppr(arg.toString())); } UniqueString name = ((StringValue)arg).getVal(); int rlen = this.names.length; for (int i = 0; i < rlen; i++) { if (name.equals(this.names[i])) { return this.values[i]; } } Assert.fail("Attempted to access nonexistent field '" + name + "' of record\n" + Values.ppr(this.toString())); return null; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value apply(Value[] args, int control) { try { if (args.length != 1) { Assert.fail("Attempted to apply record to more than one arguments."); } return this.apply(args[0], control); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } /* This method returns the named component of the record. */ @Override public final Value select(Value arg) { try { if (!(arg instanceof StringValue)) { Assert.fail("Attempted to access record by a non-string argument: " + Values.ppr(arg.toString())); } UniqueString name = ((StringValue)arg).getVal(); int rlen = this.names.length; for (int i = 0; i < rlen; i++) { if (name.equals(this.names[i])) { return this.values[i]; } } return null; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value getDomain() { try { Value[] dElems = new Value[this.names.length]; for (int i = 0; i < this.names.length; i++) { dElems[i] = new StringValue(this.names[i]); } return new SetEnumValue(dElems, this.isNormalized()); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public final boolean assign(UniqueString name, Value val) { try { for (int i = 0; i < this.names.length; i++) { if (name.equals(this.names[i])) { if (this.values[i] == UndefValue.ValUndef || this.values[i].equals(val)) { this.values[i] = val; return true; } return false; } } Assert.fail("Attempted to assign to nonexistent record field " + name + "."); return false; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean isNormalized() { return this.isNorm; } @Override public final Value normalize() { try { if (!this.isNorm) { int len = this.names.length; for (int i = 1; i < len; i++) { int cmp = this.names[0].compareTo(this.names[i]); if (cmp == 0) { Assert.fail("Field name " + this.names[i] + " occurs multiple times in record."); } else if (cmp > 0) { UniqueString ts = this.names[0]; this.names[0] = this.names[i]; this.names[i] = ts; Value tv = this.values[0]; this.values[0] = this.values[i]; this.values[i] = tv; } } for (int i = 2; i < len; i++) { int j = i; UniqueString st = this.names[i]; Value val = this.values[i]; int cmp; while ((cmp = st.compareTo(this.names[j-1])) < 0) { this.names[j] = this.names[j-1]; this.values[j] = this.values[j-1]; j--; } if (cmp == 0) { Assert.fail("Field name " + this.names[i] + " occurs multiple times in record."); } this.names[j] = st; this.values[j] = val; } this.isNorm = true; } return this; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final void deepNormalize() { try { for (int i = 0; i < values.length; i++) { values[i].deepNormalize(); } normalize(); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean isDefined() { try { boolean defined = true; for (int i = 0; i < this.values.length; i++) { defined = defined && this.values[i].isDefined(); } return defined; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final IValue deepCopy() { try { Value[] vals = new Value[this.values.length]; for (int i = 0; i < this.values.length; i++) { vals[i] = (Value) this.values[i].deepCopy(); } // Following code modified 16 June 2015 by adding Arrays.copyOf to fix // the following bug that seems to have manifested itself only in TLC.Print and // TLC.PrintT: Calling normalize on the original modifies the // order of the names array in the deepCopy (and vice-versa) without doing the // corresponding modification on the values array. Thus, the names are // copied too to prevent any modification/normalization done to the // original to appear in the deepCopy. return new RecordValue(Arrays.copyOf(this.names, this.names.length), vals, this.isNorm); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean assignable(Value val) { try { boolean canAssign = ((val instanceof RecordValue) && this.names.length == ((RecordValue)val).names.length); if (!canAssign) return false; for (int i = 0; i < this.values.length; i++) { canAssign = (canAssign && this.names[i].equals(((RecordValue)val).names[i]) && this.values[i].assignable(((RecordValue)val).values[i])); } return canAssign; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final void write(final IValueOutputStream vos) throws IOException { final int index = vos.put(this); if (index == -1) { vos.writeByte(RECORDVALUE); final int len = names.length; vos.writeInt((isNormalized()) ? len : -len); for (int i = 0; i < len; i++) { final int index1 = vos.put(names[i]); if (index1 == -1) { vos.writeByte(STRINGVALUE); names[i].write(vos.getOutputStream()); } else { vos.writeByte(DUMMYVALUE); vos.writeNat(index1); } values[i].write(vos); } } else { vos.writeByte(DUMMYVALUE); vos.writeNat(index); } } /* The fingerprint methods. */ @Override public final long fingerPrint(long fp) { try { this.normalize(); int rlen = this.names.length; fp = FP64.Extend(fp, FCNRCDVALUE); fp = FP64.Extend(fp, rlen); for (int i = 0; i < rlen; i++) { String str = this.names[i].toString(); fp = FP64.Extend(fp, STRINGVALUE); fp = FP64.Extend(fp, str.length()); fp = FP64.Extend(fp, str); fp = this.values[i].fingerPrint(fp); } return fp; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final IValue permute(IMVPerm perm) { try { this.normalize(); int rlen = this.names.length; Value[] vals = new Value[rlen]; boolean changed = false; for (int i = 0; i < rlen; i++) { vals[i] = (Value) this.values[i].permute(perm); changed = changed || (vals[i] != this.values[i]); } if (changed) { return new RecordValue(this.names, vals, true); } return this; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } /* The string representation */ @Override public final StringBuffer toString(StringBuffer sb, int offset, boolean swallow) { try { int len = this.names.length; sb.append("["); if (len > 0) { sb.append(this.names[0] + TLAConstants.RECORD_ARROW); sb = this.values[0].toString(sb, offset, swallow); } for (int i = 1; i < len; i++) { sb.append(", "); sb.append(this.names[i] + TLAConstants.RECORD_ARROW); sb = this.values[i].toString(sb, offset, swallow); } return sb.append("]"); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public static IValue createFrom(final IValueInputStream vos) throws EOFException, IOException { final int index = vos.getIndex(); boolean isNorm = true; int len = vos.readInt(); if (len < 0) { len = -len; isNorm = false; } final UniqueString[] names = new UniqueString[len]; final Value[] vals = new Value[len]; for (int i = 0; i < len; i++) { final byte kind1 = vos.readByte(); if (kind1 == DUMMYVALUE) { final int index1 = vos.readNat(); names[i] = vos.getValue(index1); } else { final int index1 = vos.getIndex(); names[i] = UniqueString.read(vos.getInputStream()); vos.assign(names[i], index1); } vals[i] = (Value) vos.read(); } final Value res = new RecordValue(names, vals, isNorm); vos.assign(res, index); return res; } public static IValue createFrom(final ValueInputStream vos, final Map<String, UniqueString> tbl) throws EOFException, IOException { final int index = vos.getIndex(); boolean isNorm = true; int len = vos.readInt(); if (len < 0) { len = -len; isNorm = false; } final UniqueString[] names = new UniqueString[len]; final Value[] vals = new Value[len]; for (int i = 0; i < len; i++) { final byte kind1 = vos.readByte(); if (kind1 == DUMMYVALUE) { final int index1 = vos.readNat(); names[i] = vos.getValue(index1); } else { final int index1 = vos.getIndex(); names[i] = UniqueString.read(vos.getInputStream(), tbl); vos.assign(names[i], index1); } vals[i] = (Value) vos.read(tbl); } final Value res = new RecordValue(names, vals, isNorm); vos.assign(res, index); return res; } public TLCState toState() { final TLCState state = TLCState.Empty.createEmpty(); final OpDeclNode[] vars = state.getVars(); for (int i = 0; i < vars.length; i++) { final UniqueString name = vars[i].getName(); int rlen = this.names.length; for (int j = 0; j < rlen; j++) { if (name.equals(this.names[j])) { state.bind(name, this.values[j]); } } } return new PrintTLCState(this, state); } private static final class PrintTLCState extends TLCState { private final RecordValue rcd; private final TLCState state; public PrintTLCState(RecordValue recordValue, final TLCState state) { this.rcd = recordValue; this.state = state; } @Override public String toString() { final StringBuffer result = new StringBuffer(); int vlen = rcd.names.length; if (vlen == 1) { result.append(rcd.names[0].toString()); result.append(" = "); result.append(Values.ppr(rcd.values[0])); result.append("\n"); } else { for (int i = 0; i < vlen; i++) { UniqueString key = rcd.names[i]; result.append("/\\ "); result.append(key.toString()); result.append(" = "); result.append(Values.ppr(rcd.values[i])); result.append("\n"); } } return result.toString(); } @Override public int hashCode() { return this.state.hashCode(); } @Override public boolean equals(Object obj) { return this.state.equals(obj); } @Override public long fingerPrint() { return this.state.fingerPrint(); } @Override public boolean allAssigned() { return this.state.allAssigned(); } @Override public String toString(TLCState lastState) { return this.state.toString(lastState); } @Override public TLCState bind(UniqueString name, IValue value) { return this.state.bind(name, value); } @Override public TLCState bind(SymbolNode id, IValue value) { return this.state.bind(id, value); } @Override public TLCState unbind(UniqueString name) { return this.state.unbind(name); } @Override public IValue lookup(UniqueString var) { return this.state.lookup(var); } @Override public boolean containsKey(UniqueString var) { return this.state.containsKey(var); } @Override public TLCState copy() { return this.state.copy(); } @Override public TLCState deepCopy() { return this.state.deepCopy(); } @Override public StateVec addToVec(StateVec states) { return this.state.addToVec(states); } @Override public void deepNormalize() { this.state.deepNormalize(); } @Override public Set<OpDeclNode> getUnassigned() { return this.state.getUnassigned(); } @Override public TLCState createEmpty() { return this.state.createEmpty(); } } }
package ta.jurais.amopen; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import ta.jurais.amopen.util.Config; import ta.jurais.amopen.util.Request; public class InputKompenActivity extends AppCompatActivity { EditText edtDesk, edtRuang, edtQuota; Button btnSubmit; private ProgressDialog pDialog; private static String url = Config.HOST+"input_kompen.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_input_kompen); getSupportActionBar().setTitle("Input Data Kompen"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); final String id_staff_kampus = getIntent().getStringExtra("key_id_staff_kampus"); edtDesk = (EditText) findViewById(R.id.edt_desk); edtRuang = (EditText) findViewById(R.id.edt_ruang); edtQuota = (EditText) findViewById(R.id.edt_quota); btnSubmit = (Button) findViewById(R.id.btn_submit); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String desk = edtDesk.getText().toString(); String ruangan = edtRuang.getText().toString(); String quota = edtQuota.getText().toString(); new postData(id_staff_kampus, desk, ruangan, quota).execute(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id_menu = item.getItemId(); if(id_menu == android.R.id.home){ finish(); } return super.onOptionsItemSelected(item); } private class postData extends AsyncTask<Void,Void,String> { //variabel untuk tangkap data private int scs = 0; private String psn; private String id_staff_kampus, desk_job, ruangan, quota; public postData(String id_staff_kampus, String desk_job, String ruangan, String quota){ this.id_staff_kampus = id_staff_kampus; this.desk_job = desk_job; this.ruangan = ruangan; this.quota = quota; } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(InputKompenActivity.this); pDialog.setMessage("Posting data..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } protected String doInBackground(Void... params) { try{ //susun parameter HashMap<String,String> detail = new HashMap<>(); detail.put("id_staff_kampus", id_staff_kampus); detail.put("desk_job", desk_job); detail.put("ruangan", ruangan); detail.put("quota", quota); try { //convert this HashMap to encodedUrl to send to php file String dataToSend = hashMapToUrl(detail); //make a Http request and send data to php file String response = Request.post(url,dataToSend); //dapatkan respon Log.e("Respon", response); JSONObject ob = new JSONObject(response); scs = ob.getInt("success"); if (scs == 1) { psn = ob.getString("message"); } else { // no data found psn = ob.getString("message"); } } catch (JSONException e){ e.printStackTrace(); } } catch (Exception e){ e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { pDialog.dismiss(); if (scs == 1) { finish(); Toast.makeText(InputKompenActivity.this, psn, Toast.LENGTH_SHORT).show(); } else { // no data found Toast.makeText(InputKompenActivity.this, psn, Toast.LENGTH_SHORT).show(); } } } private String hashMapToUrl(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } }
package org.rizki.mufrizal.spring.social.service; import org.rizki.mufrizal.spring.social.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.social.security.SocialUserDetails; import org.springframework.social.security.SocialUserDetailsService; import org.springframework.stereotype.Service; import java.util.Collections; /** * @Author Rizki Mufrizal <mufrizalrizki@gmail.com> * @Web <https://RizkiMufrizal.github.io> * @Since 01 April 2018 * @Time 6:01 PM * @Project Spring-Social * @Package org.rizki.mufrizal.spring.social.service * @File UserLoginDetailsService */ @Service public class UserLoginDetailsService implements UserDetailsService, SocialUserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { org.rizki.mufrizal.spring.social.domain.User user = userRepository.findOne(username); if (user == null) { throw new UsernameNotFoundException("username not found " + username); } return new User(user.getUsername(), user.getPassword(), true, true, true, true, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); } @Override public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException { org.rizki.mufrizal.spring.social.domain.User user = userRepository.findOne(userId); if (user == null) { throw new UsernameNotFoundException("username not found " + userId); } return new SocialUserLoginDetails(user); } }
/* * 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.hyracks.algebricks.core.algebra.prettyprint; import java.io.IOException; import org.apache.commons.io.output.StringBuilderWriter; import org.apache.hyracks.util.annotations.NotThreadSafe; /** * String writer based on string builder to provide un-synchronized writer. It overrides append methods to allow * chaining to the same string-builder-based writer to avoid throwing {@link IOException} */ @NotThreadSafe public class AlgebricksStringBuilderWriter extends StringBuilderWriter { private static final long serialVersionUID = 61841252848797632L; public AlgebricksStringBuilderWriter() { super(); } public AlgebricksStringBuilderWriter(final int capacity) { super(capacity); } @Override public AlgebricksStringBuilderWriter append(final char value) { super.append(value); return this; } @Override public AlgebricksStringBuilderWriter append(final CharSequence value) { super.append(value); return this; } @Override public AlgebricksStringBuilderWriter append(final CharSequence value, final int start, final int end) { super.append(value, start, end); return this; } }
/* * Copyright 2014, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc.stub; import com.google.common.collect.Maps; import io.grpc.Channel; import io.grpc.ClientInterceptor; import io.grpc.ClientInterceptors; import io.grpc.MethodDescriptor; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Common base type for stub implementations. * * <p>This is the base class of the stub classes from the generated code. It allows for * reconfiguration, e.g., attaching interceptors to the stub. * * @param <S> the concrete type of this stub. * @param <C> the service descriptor type */ public abstract class AbstractStub<S extends AbstractStub<?, ?>, C extends AbstractServiceDescriptor<C>> { protected final Channel channel; protected final C config; /** * Constructor for use by subclasses. * * @param channel the channel that this stub will use to do communications * @param config defines the RPC methods of the stub */ protected AbstractStub(Channel channel, C config) { this.channel = channel; this.config = config; } protected C getServiceDescriptor() { return config; } /** * Creates a builder for reconfiguring the stub. */ public StubConfigBuilder configureNewStub() { return new StubConfigBuilder(); } /** * The underlying channel of the stub. */ public Channel getChannel() { return channel; } /** * Returns a new stub with the given channel for the provided method configurations. * * @param channel the channel that this stub will use to do communications * @param config defines the RPC methods of the stub */ protected abstract S build(Channel channel, C config); /** * Utility class for (re) configuring the operations in a stub. */ public class StubConfigBuilder { private final Map<String, MethodDescriptor<?, ?>> methodMap; private final List<ClientInterceptor> interceptors = new ArrayList<ClientInterceptor>(); private Channel stubChannel; private StubConfigBuilder() { this.stubChannel = AbstractStub.this.channel; methodMap = Maps.newHashMapWithExpectedSize(config.methods().size()); for (MethodDescriptor<?, ?> method : AbstractStub.this.config.methods()) { methodMap.put(method.getName(), method); } } /** * Sets a timeout for all methods in the stub. */ public StubConfigBuilder setTimeout(long timeout, TimeUnit unit) { for (Map.Entry<String, MethodDescriptor<?, ?>> entry : methodMap.entrySet()) { entry.setValue(entry.getValue().withTimeout(timeout, unit)); } return this; } /** * Set the channel to be used by the stub. */ public StubConfigBuilder setChannel(Channel channel) { this.stubChannel = channel; return this; } /** * Adds a client interceptor to be attached to the channel of the reconfigured stub. */ public StubConfigBuilder addInterceptor(ClientInterceptor interceptor) { interceptors.add(interceptor); return this; } /** * Create a new stub with the configurations made on this builder. */ public S build() { return AbstractStub.this.build(ClientInterceptors.intercept(stubChannel, interceptors), config.build(methodMap)); } } }
package org.d3ifcool.finpro.koor.fragments; import android.app.ProgressDialog; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.d3ifcool.finpro.R; /** * A simple {@link Fragment} subclass. */ public class KoorKuotaDosenFragment extends Fragment { private ProgressDialog progressDialog; private RecyclerView recyclerView ; private View empty_view; public KoorKuotaDosenFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_koor_kuota_dosen, container, false); progressDialog = new ProgressDialog(getContext()); progressDialog.setMessage(getString(R.string.text_progress_dialog)); empty_view = rootView.findViewById(R.id.view_emptyview); return rootView; } }
package sagan.search; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.springframework.security.crypto.codec.Base64; public class SearchEntry { private String path; private String summary; private String rawContent; private String title; private String subTitle; private List<String> facetPaths = new ArrayList<>(); private boolean current = true; // TODO: maybe we don't need this in the index? private Date publishAt = new Date(); private String type = "site"; private String version; private String projectId; public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubTitle() { return subTitle; } public void setSubTitle(String subTitle) { this.subTitle = subTitle; } public Date getPublishAt() { return publishAt; } public void setPublishAt(Date publishAt) { this.publishAt = publishAt; } public String getRawContent() { return rawContent; } public void setRawContent(String rawContent) { this.rawContent = rawContent; } public String getId() { byte[] encodedId = Base64.encode(path.toLowerCase().getBytes()); return new String(encodedId); } public boolean isCurrent() { return current; } public void setCurrent(boolean current) { this.current = current; } public List<String> getFacetPaths() { return facetPaths; } public void setFacetPaths(List<String> facetPaths) { this.facetPaths = facetPaths; } public void addFacetPaths(String... paths) { facetPaths.addAll(Arrays.asList(paths)); } public String getType() { return type; } public void setType(String type) { this.type = type; } public void setVersion(String version) { this.version = version; } public String getVersion() { return version; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getProjectId() { return projectId; } }
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ab.network.toolbox; import java.io.File; import com.ab.util.AbAppUtil; import com.ab.util.AbFileUtil; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.http.AndroidHttpClient; import android.os.Build; public class Volley { /** Default on-disk cache directory. */ private static final String DEFAULT_CACHE_DIR = "andbase"; /** * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. * * @param context A {@link Context} to use for creating the cache dir. * @param stack An {@link HttpStack} to use for the network, or null for default. * @return A started {@link RequestQueue} instance. */ public static RequestQueue newRequestQueue(Context context, HttpStack stack) { File cacheDir = null; if(!AbFileUtil.isCanUseSD()){ cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); }else{ cacheDir = new File(AbFileUtil.getCacheDownloadDir(context)); } String userAgent = "andbase/0"; PackageInfo info = AbAppUtil.getPackageInfo(context); userAgent = info.packageName + "/" + info.versionCode; if (stack == null) { if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; } /** * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. * * @param context A {@link Context} to use for creating the cache dir. * @return A started {@link RequestQueue} instance. */ public static RequestQueue newRequestQueue(Context context) { return newRequestQueue(context, null); } }
/* * Copyright (c) 2020, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.disparity.block; import boofcv.alg.descriptor.DescriptorDistance; import boofcv.struct.image.GrayS32; import boofcv.struct.image.GrayS64; import boofcv.struct.image.GrayU8; import boofcv.struct.image.ImageType; import boofcv.testing.BoofStandardJUnit; import org.junit.jupiter.api.Nested; /** * @author Peter Abeles */ class TestBlockRowScoreCensus extends BoofStandardJUnit { @Nested class U8 extends ChecksBlockRowScore.ArrayIntI<GrayU8, byte[]> { U8() {super(255, ImageType.single(GrayU8.class));} @Override public BlockRowScore<GrayU8, int[], byte[]> createAlg( int radiusWidth, int radiusHeight ) { return new BlockRowScoreCensus.U8(-1); } @Override protected int computeError( int a, int b ) { return DescriptorDistance.hamming(a ^ b); } } @Nested class S32 extends ChecksBlockRowScore.ArrayIntI<GrayS32, int[]> { S32() {super(Integer.MAX_VALUE - 1000, ImageType.single(GrayS32.class));} @Override public BlockRowScore<GrayS32, int[], int[]> createAlg( int radiusWidth, int radiusHeight ) { return new BlockRowScoreCensus.S32(-1); } @Override protected int computeError( int a, int b ) { return DescriptorDistance.hamming(a ^ b); } } @Nested class S64 extends ChecksBlockRowScore.ArrayIntL { S64() {super(Integer.MAX_VALUE - 1000);} @Override public BlockRowScore<GrayS64, int[], long[]> createAlg( int radiusWidth, int radiusHeight ) { return new BlockRowScoreCensus.S64(-1); } @Override protected int computeError( long a, long b ) { return DescriptorDistance.hamming(a ^ b); } } }
/* * 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 co.edu.sena.ciclos.hagamientras; /** * * @author Enrique */ public class Ejemplo01 { /** * @param args the command line arguments */ public static void main(String[] args) { int i=0; do { System.out.println(i); i++; } while (i<10); } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.block.meta; import alluxio.util.io.PathUtils; import alluxio.worker.block.TieredBlockStoreTestUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link DefaultTempBlockMeta}. */ public class DefaultTempBlockMetaTest { private static final long TEST_SESSION_ID = 2; private static final long TEST_BLOCK_ID = 9; private static final long TEST_BLOCK_SIZE = 100; private static final int TEST_TIER_ORDINAL = 0; private static final String TEST_TIER_ALIAS = "MEM"; private static final long[] TEST_TIER_CAPACITY_BYTES = {100}; private static final String[] TEST_TIER_MEDIUM_TYPES = {"MEM"}; private static final String TEST_WORKER_DATA_FOLDER = "workertest"; private String mTestDirPath; private String mTestBlockDirPath; private TempBlockMeta mTempBlockMeta; /** Rule to create a new temporary folder during each test. */ @Rule public TemporaryFolder mFolder = new TemporaryFolder(); /** * Sets up all dependencies before a test runs. */ @Before public void before() throws Exception { mTestDirPath = mFolder.newFolder().getAbsolutePath(); // Sets up tier with one storage dir under mTestDirPath with 100 bytes capacity. TieredBlockStoreTestUtils.setupConfWithSingleTier(null, TEST_TIER_ORDINAL, TEST_TIER_ALIAS, new String[] {mTestDirPath}, TEST_TIER_CAPACITY_BYTES, TEST_TIER_MEDIUM_TYPES, TEST_WORKER_DATA_FOLDER); StorageTier tier = DefaultStorageTier.newStorageTier(TEST_TIER_ALIAS, false); StorageDir dir = tier.getDir(0); // Append the worker data folder to the expected path. mTestBlockDirPath = PathUtils.concatPath(mTestDirPath, TEST_WORKER_DATA_FOLDER); mTempBlockMeta = new DefaultTempBlockMeta(TEST_SESSION_ID, TEST_BLOCK_ID, TEST_BLOCK_SIZE, dir); } /** * Tests the {@link TempBlockMeta#getPath()} method. */ @Test public void getPath() { Assert.assertEquals(PathUtils.concatPath(mTestBlockDirPath, ".tmp_blocks", TEST_SESSION_ID % 1024, String.format("%x-%x", TEST_SESSION_ID, TEST_BLOCK_ID)), mTempBlockMeta.getPath()); } /** * Tests the {@link TempBlockMeta#getCommitPath()} method. */ @Test public void getCommitPath() { Assert.assertEquals(PathUtils.concatPath(mTestBlockDirPath, TEST_BLOCK_ID), mTempBlockMeta.getCommitPath()); } /** * Tests the {@link TempBlockMeta#getSessionId()} method. */ @Test public void getSessionId() { Assert.assertEquals(TEST_SESSION_ID, mTempBlockMeta.getSessionId()); } /** * Tests the {@link TempBlockMeta#setBlockSize(long)} method. */ @Test public void setBlockSize() { Assert.assertEquals(TEST_BLOCK_SIZE, mTempBlockMeta.getBlockSize()); mTempBlockMeta.setBlockSize(1); Assert.assertEquals(1, mTempBlockMeta.getBlockSize()); mTempBlockMeta.setBlockSize(100); Assert.assertEquals(100, mTempBlockMeta.getBlockSize()); } }
/* * Copyright (C) 2021 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.hilt.processor.internal.root; import dagger.hilt.android.testing.HiltAndroidTest; /** Defines a {@link HiltAndroidTest} for {@link MyTestPreviousCompilationTest}. */ public final class MyTestPreviousCompilation { @HiltAndroidTest public static final class MyTest {} private MyTestPreviousCompilation() {} }
package top.kairuiyang.base.validator.group; /** * GetOne Group 用于get方法查询时 * * @author: 陌溪 * @date: 2019年12月4日22:49:01 */ public interface GetOne { }
/** * Java Modular Image Synthesis Toolkit (JMIST) * Copyright (C) 2018 Bradley W. Kimmel * * 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 ca.eandb.jmist.framework.color; import ca.eandb.jmist.framework.Raster; /** * Default implementations for <code>Raster</code>. * @author Brad Kimmel */ public abstract class AbstractRaster implements Raster { /** Serialization version ID. */ private static final long serialVersionUID = -3717804516623958287L; @Override public void addPixel(int x, int y, Color pixel) { setPixel(x, y, getPixel(x, y).plus(pixel)); } }
/******************************************************************************* * Copyright 2018 General Electric Company * * 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. * * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ package org.eclipse.keti.acs.service.policy.evaluation; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.eclipse.keti.acs.attribute.readers.SubjectAttributeReader; import org.eclipse.keti.acs.model.Attribute; public class SubjectAttributeResolver { private final Map<String, Set<Attribute>> subjectAttributeMap = new HashMap<>(); private final SubjectAttributeReader subjectAttributeReader; private final String subjectIdentifier; private final Set<Attribute> supplementalSubjectAttributes; public SubjectAttributeResolver(final SubjectAttributeReader subjectAttributeReader, final String subjectIdentifier, final Set<Attribute> supplementalSubjectAttributes) { this.subjectAttributeReader = subjectAttributeReader; this.subjectIdentifier = subjectIdentifier; if (null == supplementalSubjectAttributes) { this.supplementalSubjectAttributes = Collections.emptySet(); } else { this.supplementalSubjectAttributes = supplementalSubjectAttributes; } } public Set<Attribute> getResult(final Set<Attribute> scopes) { Set<Attribute> subjectAttributes = this.subjectAttributeMap.get(this.subjectIdentifier); if (null == subjectAttributes) { subjectAttributes = new HashSet<>( this.subjectAttributeReader.getAttributesByScope(this.subjectIdentifier, scopes)); subjectAttributes.addAll(this.supplementalSubjectAttributes); this.subjectAttributeMap.put(this.subjectIdentifier, subjectAttributes); } return subjectAttributes; } }
package com.mall.order.dao; import com.mall.order.entity.OmsOrderItemEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 订单项信息 * * @author mark * @email Wyl@gmail.com * @date 2020-07-19 15:31:41 */ @Mapper public interface OmsOrderItemDao extends BaseMapper<OmsOrderItemEntity> { }
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glitchtechscience.utility.billing; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a block of information about in-app items. * An Inventory is returned by such methods as {@link IabHelper#queryInventory}. */ public class Inventory { Map<String, SkuDetails> mSkuMap = new HashMap<String, SkuDetails>(); Map<String, Purchase> mPurchaseMap = new HashMap<String, Purchase>(); Inventory() { } /** Returns the listing details for an in-app product. */ public SkuDetails getSkuDetails( String sku ) { return mSkuMap.get( sku ); } /** Returns purchase information for a given product, or null if there is no purchase. */ public Purchase getPurchase( String sku ) { return mPurchaseMap.get( sku ); } /** Returns whether or not there exists a purchase of the given product. */ public boolean hasPurchase( String sku ) { return mPurchaseMap.containsKey( sku ); } /** Return whether or not details about the given product are available. */ public boolean hasDetails( String sku ) { return mSkuMap.containsKey( sku ); } /** * Erase a purchase (locally) from the inventory, given its product ID. This just * modifies the Inventory object locally and has no effect on the server! This is * useful when you have an existing Inventory object which you know to be up to date, * and you have just consumed an item successfully, which means that erasing its * purchase data from the Inventory you already have is quicker than querying for * a new Inventory. */ public void erasePurchase( String sku ) { if( mPurchaseMap.containsKey( sku ) ) mPurchaseMap.remove( sku ); } /** Returns a list of all owned product IDs. */ List<String> getAllOwnedSkus() { return new ArrayList<String>( mPurchaseMap.keySet() ); } /** Returns a list of all owned product IDs of a given type */ List<String> getAllOwnedSkus( String itemType ) { List<String> result = new ArrayList<String>(); for( Purchase p : mPurchaseMap.values() ) { if( p.getItemType().equals( itemType ) ) result.add( p.getSku() ); } return result; } /** Returns a list of all purchases. */ List<Purchase> getAllPurchases() { return new ArrayList<Purchase>( mPurchaseMap.values() ); } void addSkuDetails( SkuDetails d ) { mSkuMap.put( d.getSku(), d ); } void addPurchase( Purchase p ) { mPurchaseMap.put( p.getSku(), p ); } }
package io.kickflip.sdk.av; import android.annotation.TargetApi; import android.media.MediaCodec; import android.media.MediaFormat; import android.os.Build; import android.os.Bundle; import android.util.Log; import java.nio.ByteBuffer; import static io.kickflip.sdk.Kickflip.isKitKat; /** * @hide */ public abstract class AndroidEncoder { private final static String TAG = "AndroidEncoder"; private final static boolean VERBOSE = false; protected Muxer mMuxer; protected MediaCodec mEncoder; protected MediaCodec.BufferInfo mBufferInfo; protected int mTrackIndex; public void release(){ if(mMuxer != null) mMuxer.onEncoderReleased(mTrackIndex); if (mEncoder != null) { mEncoder.stop(); mEncoder.release(); mEncoder = null; if (VERBOSE) Log.i(TAG, "Released encoder"); } } @TargetApi(Build.VERSION_CODES.KITKAT) public void adjustBitrate(int targetBitrate){ if(isKitKat() && mEncoder != null){ Bundle bitrate = new Bundle(); bitrate.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, targetBitrate); mEncoder.setParameters(bitrate); }else if (!isKitKat()) { Log.w(TAG, "Ignoring adjustVideoBitrate call. This functionality is only available on Android API 19+"); } } public void drainEncoder(boolean endOfStream) { synchronized (mMuxer){ final int TIMEOUT_USEC = 1000; if (VERBOSE) Log.d(TAG, "drainEncoder(" + endOfStream + ") track: " + mTrackIndex); if (endOfStream) { if (VERBOSE) Log.d(TAG, "sending EOS to encoder for track " + mTrackIndex); if(isSurfaceInputEncoder()){ if (VERBOSE) Log.i(TAG, "signalEndOfInputStream for track " + mTrackIndex); mEncoder.signalEndOfInputStream(); } } ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers(); while (true) { int encoderStatus = mEncoder.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { // no output available yet if (!endOfStream) { break; // out of while } else { if (VERBOSE) Log.d(TAG, "no output available, spinning to await EOS"); } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { // not expected for an encoder encoderOutputBuffers = mEncoder.getOutputBuffers(); } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // should happen before receiving buffers, and should only happen once MediaFormat newFormat = mEncoder.getOutputFormat(); if (VERBOSE) Log.d(TAG, "encoder output format changed: " + newFormat); // now that we have the Magic Goodies, start the muxer mTrackIndex = mMuxer.addTrack(newFormat); // Muxer is responsible for starting/stopping itself // based on knowledge of expected # tracks } else if (encoderStatus < 0) { Log.w(TAG, "unexpected result from encoder.dequeueOutputBuffer: " + encoderStatus); // let's ignore it } else { ByteBuffer encodedData = encoderOutputBuffers[encoderStatus]; if (encodedData == null) { throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null"); } if (mBufferInfo.size >= 0) { // Allow zero length buffer for purpose of sending 0 size video EOS Flag // adjust the ByteBuffer values to match BufferInfo (not needed?) encodedData.position(mBufferInfo.offset); encodedData.limit(mBufferInfo.offset + mBufferInfo.size); // It is the muxer's responsibility to release encodedData mMuxer.writeSampleData(mEncoder, mTrackIndex, encoderStatus, encodedData, mBufferInfo); if (VERBOSE) { Log.d(TAG, "sent " + mBufferInfo.size + " bytes to muxer, ts=" + mBufferInfo.presentationTimeUs + "track " + mTrackIndex); } } if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { if (!endOfStream) { Log.w(TAG, "reached end of stream unexpectedly"); } else { if (VERBOSE) Log.d(TAG, "end of stream reached for track " + mTrackIndex); } break; // out of while } } } } } protected abstract boolean isSurfaceInputEncoder(); }
package finergit.ast.token; public class LEFTMETHODPAREN extends LEFTPAREN { }
// Generated source. // Generator: org.chromium.sdk.internal.wip.tools.protocolgenerator.Generator // Origin: http://src.chromium.org/blink/trunk/Source/devtools/protocol.json@150309 with change #14672031 package org.chromium.sdk.internal.wip.protocol.input.dom; /** Requests that the node is sent to the caller given its backend node id. */ @org.chromium.sdk.internal.protocolparser.JsonType public interface PushNodeByBackendIdToFrontendData { /** The pushed node's id. */ long/*See org.chromium.sdk.internal.wip.protocol.common.dom.NodeIdTypedef*/ nodeId(); }
package javax0.geci.jamal_test; import java.util.Map; @SuppressWarnings("FieldCanBeLocal") public class PreprocessedFile { public int a; private Map myMap; public String mimosa(Integer a, Map myMap) { return null; } /*!jamal {%@define z=13%}int i = {%z%}; {%@import res:javax0/geci/jamal_test/setters.jim%}\ // {%#for ($modifiers,$type,$name,$arg) in ({%#methods (class=javax0.geci.jamal_test.PreprocessedFile selector=true argsep=: exsep=: format=$modifiers|$type|$name|$args)%})= // $modifiers $type $name $arg {%@comment // //%} %} {%@define $class=javax0.geci.jamal_test.PreprocessedFile%} {%setters%} */ int i = 13; // // protected Object clone // protected void finalize // public String mimosa java.lang.Integer:Map // public String toString // public boolean equals java.lang.Object // public final Class getClass // public final void notify // public final void notifyAll // public final void wait // public final void wait long // public final void wait long:int // public int hashCode // public void dummy // public void setA int // public void setI int // public void setMyMap Map public void setA(int a){ this.a = a; } public void setI(int i){ this.i = i; } public void setMyMap(Map myMap){ this.myMap = myMap; } //__END__ public void dummy() { /*!jamal {%beginCode the generatedCode%} var j = {%z%}; {%endCode%} */ //<editor-fold desc="the generatedCode"> var j = 13; //</editor-fold> //__END__ /*!jamal {%beginCode the generatedCode%} {%@import variables.jam%}var k = {%s%}; {%endCode%} */ //<editor-fold desc="the generatedCode"> var k = 666; //</editor-fold> //__END__ } }
package com.teamalpha.aichef; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
/** * IO package. * @since 1.0 * @author Anton Viktorov */ package com.antviktorov.io;
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.cognitosync.model; import com.amazonaws.AmazonServiceException; /** * Thrown if the request is throttled. */ public class TooManyRequestsException extends AmazonServiceException { private static final long serialVersionUID = 1L; /** * Constructs a new TooManyRequestsException with the specified error * message. * * @param message * Describes the error encountered. */ public TooManyRequestsException(String message) { super(message); } }
/* * ============LICENSE_START==================================== * DCAEGEN2-SERVICES-SDK * ========================================================= * Copyright (C) 2019 Nokia. 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. * ============LICENSE_END===================================== */ package org.onap.dcaegen2.services.sdk.rest.services.cbs.client.impl.streams.gson.dmaap.dr; import static org.assertj.core.api.Assertions.assertThat; import com.google.gson.JsonObject; import io.vavr.control.Either; import java.io.IOException; import org.junit.jupiter.api.Test; import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.exceptions.StreamParserError; import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParser; import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParsers; import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.impl.streams.gson.DataStreamUtils; import org.onap.dcaegen2.services.sdk.model.streams.DataStreamDirection; import org.onap.dcaegen2.services.sdk.model.streams.ImmutableRawDataStream; import org.onap.dcaegen2.services.sdk.model.streams.RawDataStream; import org.onap.dcaegen2.services.sdk.model.streams.StreamType; import org.onap.dcaegen2.services.sdk.model.streams.dmaap.DataRouterSource; import org.onap.dcaegen2.services.sdk.model.streams.dmaap.ImmutableDataRouterSource; public class DataRouterSourceParserTest { private static final String SAMPLE_LOCATION = "mtc00"; private static final String SAMPLE_DELIVERY_URL = "https://my-subscriber-app.dcae:8080/target-path"; private static final String SAMPLE_USER = "some-user"; private static final String SAMPLE_PASSWORD = "some-password"; private static final String SAMPLE_SUBSCRIBER_ID = "789012"; private final StreamFromGsonParser<DataRouterSource> streamParser = StreamFromGsonParsers.dataRouterSourceParser(); @Test void fullConfiguration_shouldGenerateDataRouterSinkObject() throws IOException { // given RawDataStream<JsonObject> input = DataStreamUtils.readSourceFromResource("/streams/data_router_source_full.json"); // when DataRouterSource result = streamParser.unsafeParse(input); // then final DataRouterSource fullConfigurationStream = ImmutableDataRouterSource.builder() .name(input.name()) .location(SAMPLE_LOCATION) .deliveryUrl(SAMPLE_DELIVERY_URL) .username(SAMPLE_USER) .password(SAMPLE_PASSWORD) .subscriberId(SAMPLE_SUBSCRIBER_ID) .build(); assertThat(result).isEqualTo(fullConfigurationStream); } @Test void minimalConfiguration_shouldGenerateDataRouterSinkObject() throws IOException { // given RawDataStream<JsonObject> input = DataStreamUtils .readSourceFromResource("/streams/data_router_source_minimal.json"); // when DataRouterSource result = streamParser.unsafeParse(input); // then final DataRouterSource minimalConfigurationStream = ImmutableDataRouterSource.builder() .name(input.name()) .build(); assertThat(result).isEqualTo(minimalConfigurationStream); } @Test void incorrectConfiguration_shouldParseToStreamParserError() throws IOException { // given RawDataStream<JsonObject> input = DataStreamUtils.readSourceFromResource("/streams/message_router_full.json"); // when Either<StreamParserError, DataRouterSource> result = streamParser.parse(input); // then assertThat(result.getLeft()).isInstanceOf(StreamParserError.class); result.peekLeft(error -> { assertThat(error.message()).contains("Invalid stream type"); assertThat(error.message()).contains("Expected '" + StreamType.DATA_ROUTER + "', but was '" + StreamType.MESSAGE_ROUTER + "'"); } ); } @Test void emptyConfiguration_shouldBeParsedToStreamParserError() { // given JsonObject json = new JsonObject(); final ImmutableRawDataStream<JsonObject> input = ImmutableRawDataStream.<JsonObject>builder() .name("empty") .type(StreamType.DATA_ROUTER) .descriptor(json) .direction(DataStreamDirection.SOURCE) .build(); // when Either<StreamParserError, DataRouterSource> result = streamParser.parse(input); // then assertThat(result.getLeft()).isInstanceOf(StreamParserError.class); } }
package com.agekt.ideastore.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.agekt.ideastore.ApplicationStarter; import com.agekt.ideastore.dao.UserDAO; import com.agekt.ideastore.entity.User; @RunWith(SpringRunner.class) @SpringBootTest(classes = ApplicationStarter.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @EnableAutoConfiguration public class UserDAOTest { @Autowired private UserDAO userDAO; @Autowired private User user; public void save() { user.setId(1L); user.setUsername("Alice"); user.setNickname("Ashon"); user.setEmail("alice@gmail.com"); user.setPhone("+8618076589124"); user.setPassword("q4frc8hg4sy"); userDAO.save(user); } public void findById() { user = userDAO.findById(user, 1L); System.out.println(user); } @Test public void test() { save(); findById(); } }
package cn.enilu.flash.bean.entity.system; import lombok.Data; import org.hibernate.annotations.Table; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.Date; /** * <p> * User: Yao * Date: 2017-06-22 11:12:48 */ @Table(appliesTo = "t_sys_task_log", comment = "定时任务日志") @Entity(name = "t_sys_task_log") @Data public class TaskLog { public static final int EXE_FAILURE_RESULT = 0; public static final int EXE_SUCCESS_RESULT = 1; @Id @GeneratedValue private Long id; @Column(columnDefinition = "BIGINT COMMENT '对应任务id'") private Long idTask; @Column(columnDefinition = "VARCHAR(50) COMMENT '任务名'") private String name; @Column(columnDefinition = "DATETime COMMENT '执行时间'") private Date execAt; @Column(columnDefinition = "INTEGER COMMENT '执行结果(成功:1、失败:0)'") private int execSuccess; @Column(columnDefinition = "VARCHAR(500) COMMENT '抛出异常'") private String jobException; }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2018_04_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.network.v2018_04_01.implementation.VirtualNetworkUsageInner; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.network.v2018_04_01.implementation.NetworkManager; /** * Type representing VirtualNetworkUsage. */ public interface VirtualNetworkUsage extends HasInner<VirtualNetworkUsageInner>, HasManager<NetworkManager> { /** * @return the currentValue value. */ Double currentValue(); /** * @return the id value. */ String id(); /** * @return the limit value. */ Double limit(); /** * @return the name value. */ VirtualNetworkUsageName name(); /** * @return the unit value. */ String unit(); }
//@@author nattanyz package dream.fcard.logic.stats; import java.time.LocalDateTime; import java.util.ArrayList; import org.junit.jupiter.api.Test; public class UserStatsTest { @Test public void createUserStatsFromSessionList_verifyNoStackOverflow() { ArrayList<Session> arrayListOfSessions = new ArrayList<>(); for (int i = 1; i <= 5; i++) { LocalDateTime start = LocalDateTime.of(2019, 10, 30, 18, 59); LocalDateTime end = LocalDateTime.of(2019, 10, 30, 23, 59); // expected output: new Session with specified start and end times, duration of 5 hours Session session = new Session(start, end); arrayListOfSessions.add(session); } UserStats userStats = new UserStats(); SessionList sessionList = new SessionList(arrayListOfSessions); userStats.setSessionList(sessionList); } }
/* * Copyright 2006-2021 Prowide * * 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.prowidesoftware.swift.model.mt.mt0xx; import com.prowidesoftware.Generated; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.prowidesoftware.swift.model.*; import com.prowidesoftware.swift.model.field.*; import com.prowidesoftware.swift.model.mt.AbstractMT; import com.prowidesoftware.swift.utils.Lib; import java.io.File; import java.io.InputStream; import java.io.IOException; /** * <strong>MT 073 - Message Sample Request</strong> * * <p> * SWIFT MT073 (ISO 15022) message structure: * <br> <div class="scheme"><ul> <li class="sequence"> Sequence _A - Message identifier (O)<ul><li class="field">Field 120 (M) (repetitive)</li> </ul></li> <li class="sequence"> Sequence _B - Message list (O)<ul><li class="field">Field 123 (M)</li> <li class="field">Field 126 (M)</li> <li class="field">Field 122 (M)</li> </ul></li> <li class="sequence"> Sequence _C - Message type (O)<ul><li class="field">Field 124 (M) (repetitive)</li> <li class="field">Field 126 (M)</li> <li class="field">Field 122 (M)</li> </ul></li> <li class="sequence"> Sequence _D - Message category (O)<ul><li class="field">Field 125 (M) (repetitive)</li> <li class="field">Field 126 (M)</li> <li class="field">Field 122 (M)</li> </ul></li> </ul></div> * * <p> * This source code is specific to release <strong>SRU 2021</strong> * <p> * For additional resources check <a href="https://www.prowidesoftware.com/resources">https://www.prowidesoftware.com/resources</a> */ @Generated public class MT073 extends AbstractMT implements Serializable { /** * Constant identifying the SRU to which this class belongs to. */ public static final int SRU = 2021; private static final long serialVersionUID = 1L; private static final transient java.util.logging.Logger log = java.util.logging.Logger.getLogger(MT073.class.getName()); /** * Constant for MT name, this is part of the classname, after <code>MT</code> */ public static final String NAME = "073"; /** * Creates an MT073 initialized with the parameter SwiftMessage * @param m swift message with the MT073 content */ public MT073(SwiftMessage m) { super(m); sanityCheck(m); } /** * Creates an MT073 initialized with the parameter MtSwiftMessage. * @param m swift message with the MT073 content, the parameter can not be null * @see #MT073(String) */ public MT073(MtSwiftMessage m) { this(m.message()); } /** * Creates an MT073 initialized with the parameter MtSwiftMessage. * * @param m swift message with the MT073 content * @return the created object or null if the parameter is null * @see #MT073(String) * @since 7.7 */ public static MT073 parse(MtSwiftMessage m) { if (m == null) { return null; } return new MT073(m); } /** * Creates and initializes a new MT073 input message setting TEST BICS as sender and receiver.<br> * All mandatory header attributes are completed with default values. * * @since 7.6 */ public MT073() { this(BIC.TEST8, BIC.TEST8); } /** * Creates and initializes a new MT073 input message from sender to receiver.<br> * All mandatory header attributes are completed with default values. * In particular the sender and receiver addresses will be filled with proper default LT identifier * and branch codes if not provided, * * @param sender the sender address as a bic8, bic11 or full logical terminal consisting of 12 characters * @param receiver the receiver address as a bic8, bic11 or full logical terminal consisting of 12 characters * @since 7.7 */ public MT073(final String sender, final String receiver) { super(73, sender, receiver); } /** * Creates a new MT073 by parsing a String with the message content in its swift FIN format.<br> * If the fin parameter is null or the message cannot be parsed, the internal message object * will be initialized (blocks will be created) but empty.<br> * If the string contains multiple messages, only the first one will be parsed. * * @param fin a string with the MT message in its FIN swift format * @since 7.7 */ public MT073(final String fin) { super(); if (fin != null) { final SwiftMessage parsed = read(fin); if (parsed != null) { super.m = parsed; sanityCheck(parsed); } } } private void sanityCheck(final SwiftMessage param) { if (param.isServiceMessage()) { log.warning("Creating an MT073 object from FIN content with a Service Message. Check if the MT073 you are intended to read is prepended with and ACK."); } else if (!StringUtils.equals(param.getType(), getMessageType())) { log.warning("Creating an MT073 object from FIN content with message type "+param.getType()); } } /** * Creates a new MT073 by parsing a String with the message content in its swift FIN format.<br> * If the fin parameter cannot be parsed, the returned MT073 will have its internal message object * initialized (blocks will be created) but empty.<br> * If the string contains multiple messages, only the first one will be parsed. * * @param fin a string with the MT message in its FIN swift format. <em>fin may be null in which case this method returns null</em> * @return a new instance of MT073 or null if fin is null * @since 7.7 */ public static MT073 parse(final String fin) { if (fin == null) { return null; } return new MT073(fin); } /** * Creates a new MT073 by parsing a input stream with the message content in its swift FIN format, using "UTF-8" as encoding.<br> * If the message content is null or cannot be parsed, the internal message object * will be initialized (blocks will be created) but empty.<br> * If the stream contains multiple messages, only the first one will be parsed. * * @param stream an input stream in UTF-8 encoding with the MT message in its FIN swift format. * @throws IOException if the stream data cannot be read * @since 7.7 */ public MT073(final InputStream stream) throws IOException { this(Lib.readStream(stream)); } /** * Creates a new MT073 by parsing a input stream with the message content in its swift FIN format, using "UTF-8" as encoding.<br> * If the stream contains multiple messages, only the first one will be parsed. * * @param stream an input stream in UTF-8 encoding with the MT message in its FIN swift format. * @return a new instance of MT073 or null if stream is null or the message cannot be parsed * @throws IOException if the stream data cannot be read * @since 7.7 */ public static MT073 parse(final InputStream stream) throws IOException { if (stream == null) { return null; } return new MT073(stream); } /** * Creates a new MT073 by parsing a file with the message content in its swift FIN format.<br> * If the file content is null or cannot be parsed as a message, the internal message object * will be initialized (blocks will be created) but empty.<br> * If the file contains multiple messages, only the first one will be parsed. * * @param file a file with the MT message in its FIN swift format. * @throws IOException if the file content cannot be read * @since 7.7 */ public MT073(final File file) throws IOException { this(Lib.readFile(file)); } /** * Creates a new MT073 by parsing a file with the message content in its swift FIN format.<br> * If the file contains multiple messages, only the first one will be parsed. * * @param file a file with the MT message in its FIN swift format. * @return a new instance of MT073 or null if; file is null, does not exist, can't be read, is not a file or the message cannot be parsed * @throws IOException if the file content cannot be read * @since 7.7 */ public static MT073 parse(final File file) throws IOException { if (file == null) { return null; } return new MT073(file); } /** * Returns this MT number * @return the message type number of this MT * @since 6.4 */ @Override public String getMessageType() { return "073"; } /** * Add all tags from block to the end of the block4. * * @param block to append * @return this object to allow method chaining * @since 7.6 */ @Override public MT073 append(final SwiftTagListBlock block) { super.append(block); return this; } /** * Add all tags to the end of the block4. * * @param tags to append * @return this object to allow method chaining * @since 7.6 */ @Override public MT073 append(final Tag ... tags) { super.append(tags); return this; } /** * Add all the fields to the end of the block4. * * @param fields to append * @return this object to allow method chaining * @since 7.6 */ @Override public MT073 append(final Field ... fields) { super.append(fields); return this; } /** * Creates an MT073 messages from its JSON representation. * <p> * For generic conversion of JSON into the corresopnding MT instance * see {@link AbstractMT#fromJson(String)} * * @param json a JSON representation of an MT073 message * @return a new instance of MT073 * @since 7.10.3 */ public static MT073 fromJson(String json) { return (MT073) AbstractMT.fromJson(json); } /** * Iterates through block4 fields and return the first one whose name matches 123, * or null if none is found.<br> * The first occurrence of field 123 at MT073 is expected to be the only one. * * @return a Field123 object or null if the field is not found * @see SwiftTagListBlock#getTagByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public Field123 getField123() { final Tag t = tag("123"); if (t != null) { return new Field123(t.getValue()); } else { return null; } } /** * Iterates through block4 fields and return all occurrences of fields whose names matches 120, * or <code>Collections.emptyList()</code> if none is found.<br> * Multiple occurrences of field 120 at MT073 are expected at one sequence or across several sequences. * * @return a List of Field120 objects or <code>Collections.emptyList()</code> if none is not found * @see SwiftTagListBlock#getTagsByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public List<Field120> getField120() { final List<Field120> result = new ArrayList<>(); final Tag[] tags = tags("120"); if (tags != null && tags.length > 0) { for (Tag tag : tags) { result.add(new Field120(tag.getValue())); } } return result; } /** * Iterates through block4 fields and return all occurrences of fields whose names matches 124, * or <code>Collections.emptyList()</code> if none is found.<br> * Multiple occurrences of field 124 at MT073 are expected at one sequence or across several sequences. * * @return a List of Field124 objects or <code>Collections.emptyList()</code> if none is not found * @see SwiftTagListBlock#getTagsByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public List<Field124> getField124() { final List<Field124> result = new ArrayList<>(); final Tag[] tags = tags("124"); if (tags != null && tags.length > 0) { for (Tag tag : tags) { result.add(new Field124(tag.getValue())); } } return result; } /** * Iterates through block4 fields and return all occurrences of fields whose names matches 126, * or <code>Collections.emptyList()</code> if none is found.<br> * Multiple occurrences of field 126 at MT073 are expected at one sequence or across several sequences. * * @return a List of Field126 objects or <code>Collections.emptyList()</code> if none is not found * @see SwiftTagListBlock#getTagsByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public List<Field126> getField126() { final List<Field126> result = new ArrayList<>(); final Tag[] tags = tags("126"); if (tags != null && tags.length > 0) { for (Tag tag : tags) { result.add(new Field126(tag.getValue())); } } return result; } /** * Iterates through block4 fields and return all occurrences of fields whose names matches 122, * or <code>Collections.emptyList()</code> if none is found.<br> * Multiple occurrences of field 122 at MT073 are expected at one sequence or across several sequences. * * @return a List of Field122 objects or <code>Collections.emptyList()</code> if none is not found * @see SwiftTagListBlock#getTagsByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public List<Field122> getField122() { final List<Field122> result = new ArrayList<>(); final Tag[] tags = tags("122"); if (tags != null && tags.length > 0) { for (Tag tag : tags) { result.add(new Field122(tag.getValue())); } } return result; } /** * Iterates through block4 fields and return all occurrences of fields whose names matches 125, * or <code>Collections.emptyList()</code> if none is found.<br> * Multiple occurrences of field 125 at MT073 are expected at one sequence or across several sequences. * * @return a List of Field125 objects or <code>Collections.emptyList()</code> if none is not found * @see SwiftTagListBlock#getTagsByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public List<Field125> getField125() { final List<Field125> result = new ArrayList<>(); final Tag[] tags = tags("125"); if (tags != null && tags.length > 0) { for (Tag tag : tags) { result.add(new Field125(tag.getValue())); } } return result; } }
/* * Copyright 2016-2019 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package zipkin2.storage.mysql.v1; import java.io.IOException; import java.util.List; import java.util.Set; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.RegisterExtension; import zipkin2.Span; import zipkin2.dependencies.mysql.MySQLDependenciesJob; import zipkin2.storage.ITDependencies; import zipkin2.storage.StorageComponent; import static org.testcontainers.containers.MySQLContainer.MYSQL_PORT; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ITMySQLDependencies extends ITDependencies<MySQLStorage> { @RegisterExtension MySQLStorageExtension backend = new MySQLStorageExtension( "openzipkin/zipkin-mysql:2.16.0"); @Override protected StorageComponent.Builder newStorageBuilder(TestInfo testInfo) { return backend.computeStorageBuilder(); } @Override public void clear() { storage.clear(); } /** This processes the job as if it were a batch. For each day we had traces, run the job again. */ @Override public void processDependencies(List<Span> spans) throws IOException { storage.spanConsumer().accept(spans).execute(); // aggregate links in memory to determine which days they are in Set<Long> days = aggregateLinks(spans).keySet(); // process the job for each day of links. for (long day : days) { MySQLDependenciesJob.builder() .user(backend.container.getUsername()) .password(backend.container.getPassword()) .port(backend.container.getMappedPort(MYSQL_PORT)) .db(backend.container.getDatabaseName()) .day(day).build().run(); } } }
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2014 the original author or authors. */ package org.assertj.guava.api; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.guava.api.Assertions.assertThat; import org.junit.Test; import com.google.common.collect.Range; /** * @author Marcin Kwaczyński */ public class RangeAssert_doesNotContain_Test extends BaseTest { @Test public void should_fail_if_actual_is_null() { // given Range<Integer> actual = null; // expect expectException(AssertionError.class, actualIsNull()); // when assertThat(actual).doesNotContain(1); } @Test public void should_fail_when_range_contains_unexpected_value() { // given final Range<Integer> actual = Range.closed(1, 10); // expect expectException(AssertionError.class, "\nExpecting\n <[1‥10]>\nnot to contain\n <[9, 10, 11]>\nbut found\n <[9, 10]>\n"); // when assertThat(actual).doesNotContain(9, 10, 11); } @Test public void should_pass_if_range_does_not_contain_values() throws Exception { // given final Range<Integer> actual = Range.closedOpen(1, 10); // when assertThat(actual).doesNotContain(10); // then // pass } }
package us.codecraft.webmagic.scheduler; import us.codecraft.webmagic.Request; import us.codecraft.webmagic.Task; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Basic Scheduler implementation.<br> * Store urls to fetch in LinkedBlockingQueue and remove duplicate urls by HashMap. * * @author code4crafter@gmail.com <br> * @since 0.1.0 */ public class QueueScheduler extends DuplicateRemovedScheduler implements MonitorableScheduler { private BlockingQueue<Request> queue = new LinkedBlockingQueue<Request>(); @Override public void pushWhenNoDuplicate(Request request, Task task) { queue.add(request); } @Override public Request poll(Task task) { return queue.poll(); } @Override public void clearQueue() { queue.clear(); logger.debug("queue size: {}", queue.size()); } @Override public void clearDuplicateSet() { super.getDuplicateRemover().clear(); } @Override public int getLeftRequestsCount(Task task) { return queue.size(); } @Override public int getTotalRequestsCount(Task task) { return getDuplicateRemover().getTotalRequestsCount(task); } }
package com.adobe.acs.epic; import static com.adobe.acs.epic.DataUtils.compareDates; import com.adobe.acs.epic.controller.AppController; import com.adobe.acs.epic.controller.AuthHandler; import com.adobe.acs.epic.model.CrxPackage; import com.adobe.acs.epic.model.PackageContents; import com.adobe.acs.model.pkglist.PackageType; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javafx.application.Platform; import javafx.beans.property.DoubleProperty; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIUtils; import org.apache.http.impl.client.CloseableHttpClient; /** * Package-specific utility functions */ public class PackageOps { static final private ApplicationState app = ApplicationState.getInstance(); private PackageOps() { // Utility class has no constructor } public static boolean isInstalled(PackageType p) { return p.getLastUnpacked() != null && !p.getLastUnpacked().isEmpty(); } public static boolean isProduct(PackageType p) { String group = p.getGroup().trim().toLowerCase(); return group.startsWith("adobe/cq") || group.startsWith("adobe/aem6") || group.startsWith("com/adobe/cq") || group.startsWith("day/cq") || group.startsWith("cq/hotfix") || group.contains("featurepack") || group.startsWith("adobe/granite") || group.startsWith("com.adobe.cq") || group.startsWith("com.adobe.granite"); } public static int orderPackagesByUnpacked(PackageType p1, PackageType p2) { int val = compareDates(p1.getLastUnpacked(), p2.getLastUnpacked()); if (val != 0) { return val; } else { val = compareDates(p1.getCreated(), p2.getCreated()); if (val != 0) { return val; } else { return getCompareName(p1).compareTo(getCompareName(p2)); } } } public static String getCompareName(PackageType pkg) { return pkg.getGroup() + "~~~" + pkg.getName() + "~~~" + pkg.getVersion(); } public static boolean hasPackageContents(PackageType pkg) { return app.getPackageContents(pkg) != null; } private static final Map<String, File> packageFiles = new HashMap<>(); public static String getDownloadLink(PackageType pkg) { AuthHandler authHandler = ApplicationState.getInstance().getAuthHandler(); return authHandler.getUrlBase() + "/etc/packages/" + urlPathEscape(pkg.getGroup()) + "/" + urlPathEscape(pkg.getDownloadName()); } private static String urlPathEscape(String str) { try { return URLEncoder.encode(str, "UTF-8") .replaceAll(Pattern.quote("+"), "%20") .replaceAll(Pattern.quote("%21"), "!") .replaceAll(Pattern.quote("%27"), "'") .replaceAll(Pattern.quote("%28"), "(") .replaceAll(Pattern.quote("%29"), ")") .replaceAll(Pattern.quote("%7E"), "~"); } catch (UnsupportedEncodingException ex) { return str; } } private static File getPackageFile(PackageType pkg, DoubleProperty progress) { String filename = pkg.getGroup().replaceAll("[^A-Za-z]", "_") + "-" + pkg.getDownloadName() + "-" + pkg.getVersion() + "-" + pkg.getSize(); if (!packageFiles.containsKey(filename)) { AuthHandler authHandler = ApplicationState.getInstance().getAuthHandler(); try (CloseableHttpClient client = authHandler.getAuthenticatedClient()) { File targetFile = File.createTempFile(filename, ".zip"); targetFile.deleteOnExit(); String url = getDownloadLink(pkg); HttpGet request = new HttpGet(url); try (CloseableHttpResponse response = client.execute(request)) { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); try (OutputStream outputStream = new FileOutputStream(targetFile)) { long fileSize = entity.getContentLength(); long downloaded = 0; BufferedInputStream in = new BufferedInputStream(inputStream); BufferedOutputStream out = new BufferedOutputStream(outputStream); byte[] buffer = new byte[1024]; int size; int updateCounter = 0; while ((size = in.read(buffer)) > 0) { downloaded += size; out.write(buffer, 0, size); if (progress != null && (++updateCounter % 16) == 0) { final double newProgress = (double) downloaded / (double) fileSize; Platform.runLater(()-> progress.set(newProgress) ); } } out.flush(); outputStream.flush(); outputStream.close(); inputStream.close(); response.close(); packageFiles.put(filename, targetFile); } } } } catch (IOException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } } if (progress != null) { progress.set(1.0); } return packageFiles.get(filename); } public static PackageContents getPackageContents(PackageType pkg, DoubleProperty progress) throws IOException { if (app.getPackageContents(pkg) == null) { File targetFile = getPackageFile(pkg, progress); Logger.getLogger(AppController.class.getName()).log(Level.INFO, "Package downloaded to {0}", targetFile.getPath()); app.putPackageContents(pkg, new PackageContents(targetFile, pkg)); } return app.getPackageContents(pkg); } public static String getInformativeVersion(PackageType pkg) { String ver = pkg.getVersion(); if (pkg instanceof CrxPackage) { int others = ((CrxPackage) pkg).getAllVersions().size() - 1; if (others > 1) { ver += " +" + others + " others"; } else if (others == 1) { ver += " +1 other"; } } return ver; } }
package ch.frostnova.spring.boot.platform.service.impl; import ch.frostnova.spring.boot.platform.model.UserInfo; import ch.frostnova.spring.boot.platform.service.JWTVerificationService; import ch.frostnova.spring.boot.platform.service.TokenAuthenticator; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @Component @ConditionalOnProperty(value = "ch.frostnova.platform.security.auth", havingValue = "jwt") public class JWTTokenAuthenticator implements TokenAuthenticator { private final static Set<String> RESERVED_CLAIMS = Set.of("sub", "tenant", "scope"); @Autowired private Logger logger; @Autowired private JWTVerificationService jwtVerificationService; @Override public UserInfo authenticate(String token) throws SecurityException { logger.debug("Token: {}", token); Jws<Claims> claims = jwtVerificationService.verify(token); Claims body = claims.getBody(); logger.debug("Authenticated as: {}", body); List<?> scopes = body.get("scope", List.class); Map<String, String> additionalClaims = new HashMap<>(); body.forEach((key, value) -> { if (!RESERVED_CLAIMS.contains(key)) { additionalClaims.put(key, toString(value)); } }); return UserInfo.aUserInfo() .tenant(body.get("tenant", String.class)) .login(body.getSubject()) .roles(scopes.stream().map(String::valueOf).collect(Collectors.toSet())) .additionalClaims(additionalClaims) .build(); } private String toString(Object obj) { if (obj == null) { return null; } if (obj instanceof Iterable<?>) { Iterable<?> iterable = (Iterable<?>) obj; return StreamSupport.stream(iterable.spliterator(), false) .map(this::toString) .collect(Collectors.joining(",")); } return String.valueOf(obj); } }
package com.jocher.javapattern.decorator; /** * Created by wubin on 2017/3/20. */ public class TrollDecorator implements Troll { private Troll decorated; public TrollDecorator(Troll decorated) { this.decorated = decorated; } @Override public void attack() { decorated.attack(); } @Override public int getAttackPower() { return decorated.getAttackPower(); } @Override public void fleeBattle() { decorated.fleeBattle(); } }
/* * * * * * Copyright 2020 First People's Cultural Council * * * * 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 ca.firstvoices.enrichers; import static org.nuxeo.ecm.core.io.registry.reflect.Instantiations.SINGLETON; import static org.nuxeo.ecm.core.io.registry.reflect.Priorities.REFERENCE; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.CoreInstance; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.core.api.security.SecurityConstants; import org.nuxeo.ecm.core.io.marshallers.json.enrichers.AbstractJsonEnricher; import org.nuxeo.ecm.core.io.registry.reflect.Setup; @Setup(mode = SINGLETON, priority = REFERENCE) public class AncestryEnricher extends AbstractJsonEnricher<DocumentModel> { public static final String NAME = "ancestry"; private static final Log log = LogFactory.getLog(AncestryEnricher.class); public AncestryEnricher() { super(NAME); } // Method that will be called when the enricher is asked for @Override public void write(JsonGenerator jg, DocumentModel doc) throws IOException { // We use the Jackson library to generate Json ObjectNode wordJsonObject = constructAncestryJSON(doc); jg.writeFieldName(NAME); jg.writeObject(wordJsonObject); } protected ObjectNode constructAncestryJSON(DocumentModel doc) { ObjectMapper mapper = new ObjectMapper(); return CoreInstance.doPrivileged(doc.getCoreSession(), session -> { // JSON object to be returned ObjectNode jsonObj = mapper.createObjectNode(); /* * Process fvancestry values */ // Process Language Family log.debug("Constructing ancestry for doc: " + doc.getId()); DocumentModel resolvedDoc = doc; String languageFamilyId = (String) doc.getProperty("fvancestry", "family"); if (StringUtils.isNotEmpty(languageFamilyId)) { resolvedDoc = resolveTargetDoc(languageFamilyId, doc.isProxy(), session); ObjectNode languageFamilyObj = mapper.createObjectNode(); if (resolvedDoc != null) { languageFamilyObj.put("uid", languageFamilyId); languageFamilyObj.put("dc:title", resolvedDoc.getTitle()); } jsonObj.set("family", languageFamilyObj); } // Process Language String languageId = (String) doc.getProperty("fvancestry", "language"); if (StringUtils.isNotEmpty(languageId)) { resolvedDoc = resolveTargetDoc(languageId, doc.isProxy(), session); ObjectNode languageObj = mapper.createObjectNode(); if (resolvedDoc != null) { languageObj.put("uid", languageId); languageObj.put("dc:title", resolvedDoc.getTitle()); } jsonObj.set("language", languageObj); } // Process Dialect String dialectId = (String) doc.getProperty("fvancestry", "dialect"); if (StringUtils.isNotEmpty(dialectId)) { resolvedDoc = resolveTargetDoc(dialectId, doc.isProxy(), session); ObjectNode dialectDoc = mapper.createObjectNode(); if (resolvedDoc != null) { dialectDoc.put("uid", dialectId); dialectDoc.put("dc:title", resolvedDoc.getTitle()); dialectDoc.put("path", resolvedDoc.getPathAsString()); dialectDoc.put("fvdialect:country", (String) resolvedDoc.getPropertyValue("fvdialect:country")); dialectDoc.put("fvdialect:region", (String) resolvedDoc.getPropertyValue("fvdialect:region")); } jsonObj.set("dialect", dialectDoc); } return jsonObj; }); } protected DocumentModel resolveTargetDoc(String docIdRef, boolean isProxy, CoreSession session) { if (!session.hasPermission(new IdRef(docIdRef), SecurityConstants.READ)) { return null; } DocumentModel resolvedDoc = session.getDocument(new IdRef(docIdRef)); if (isProxy) { DocumentModelList proxies = session.getProxies(new IdRef(docIdRef), null); if (!proxies.isEmpty()) { resolvedDoc = proxies.get(0); } } return resolvedDoc; } }
package edu.kit.ss17.chatsys.team1.shared.StreamProcessor.Serialization; import edu.kit.ss17.chatsys.team1.shared.StreamData.StanzaInterface; import edu.kit.ss17.chatsys.team1.shared.StreamProcessor.Constants; import org.dom4j.Element; import java.time.Instant; /** * This abstract class provides the functionality to serialize the metadata of stanza objects. */ public abstract class AbstractStanzaSerializer implements StanzaSerializerInterface { /** * This method translates the metadata of a stanza to its XML representation. * @param element the {@link Element} to put the serialization in. * @param stanza the {@link StanzaInterface} to be serialized. * @return the given {@link Element} with the serialized values in it. */ static Element serializeMetadata(Element element, StanzaInterface stanza) { element.addAttribute("from", stanza.getSender()) .addAttribute("id", stanza.getID()).addAttribute("to", stanza.getReceiver()) .addAttribute(Constants.CLIENT_SEND_DATE, instantToString(stanza.getClientSendDate())) .addAttribute(Constants.SERVER_RECEIVE_DATE, instantToString(stanza.getServerReceiveDate())) .addAttribute(Constants.CLIENT_RECEIVE_DATE, instantToString(stanza.getClientReceiveDate())) .addAttribute("type", stanza.getType()); return element; } private static String instantToString(Instant instant) { String instantString = ""; if (instant != null) { instantString = String.valueOf(instant.getEpochSecond()).concat(".").concat(String.valueOf(instant.getNano())); } return instantString; } }
package gov.gtas.parser.pentaho.util.test; import static org.junit.Assert.*; import org.junit.Test; import gov.gtas.parser.pentaho.util.ParseDataSegment; public class ParseDataSegmentTest { private static final String DATA_ELEMENT_SEPARATOR = "+"; private static final String COMP_DATA_ELEMENT_SEPARATOR = ":"; private static final String LOCATION_SEGMENT_1 = "LOC+178+MEX"; private static final String DOCUMENT_SEGMENT_1 = "DOC+P+340210565"; private static final String DOCUMENT_SEGMENT_2 = "DOC+V+96690777"; private static final String DATE_SEGMENT_1 = "DTM+36:230212"; private static final String DATE_SEGMENT_2 = "DTM+36:020212"; private static final String FLIGHT_DATE_SEGMENT_1 = "DTM+189:1802191015:201"; private static final String FLIGHT_DATE_SEGMENT_2 = "DTM+189:1805230927:201"; private static final String CONTACT_SEGMENT_1 = "COM+044 222 222222:TE"; private static final String CONTACT_SEGMENT_2 = "COM+202 628 9292:TE+202 628 4998:FX+davidsonr.at.iata.org:EM"; @Test public void extractFieldDataTest() { assertEquals("MEX", ParseDataSegment.extractFieldData(LOCATION_SEGMENT_1, DATA_ELEMENT_SEPARATOR)); assertEquals("340210565", ParseDataSegment.extractFieldData(DOCUMENT_SEGMENT_1, DATA_ELEMENT_SEPARATOR)); // Not Equals test assertNotEquals("USA", ParseDataSegment.extractFieldData(LOCATION_SEGMENT_1, DATA_ELEMENT_SEPARATOR)); assertNotEquals("123456", ParseDataSegment.extractFieldData(DOCUMENT_SEGMENT_1, DATA_ELEMENT_SEPARATOR)); } @Test public void extractDateFieldDataTest() { try { assertEquals("2023-02-12", ParseDataSegment.extractDateFieldData(DATE_SEGMENT_1, COMP_DATA_ELEMENT_SEPARATOR, "yyMMdd", "yyyy-MM-dd")); assertEquals("2002-02-12", ParseDataSegment.extractDateFieldData(DATE_SEGMENT_2, COMP_DATA_ELEMENT_SEPARATOR, "yyMMdd", "yyyy-MM-dd")); assertNotEquals("2023-01-12", ParseDataSegment.extractDateFieldData(DATE_SEGMENT_1, COMP_DATA_ELEMENT_SEPARATOR, "yyMMdd", "yyyy-MM-dd")); assertNotEquals("2022-02-12", ParseDataSegment.extractDateFieldData(DATE_SEGMENT_2, COMP_DATA_ELEMENT_SEPARATOR, "yyMMdd", "yyyy-MM-dd")); assertNull( ParseDataSegment.extractDateFieldData(null, COMP_DATA_ELEMENT_SEPARATOR, "yyMMdd", "yyyy-MM-dd")); } catch (Exception e) { e.printStackTrace(); } } @Test public void extractFlightDateFieldTest() { try { assertEquals("2018-02-19", ParseDataSegment.extractFlightDateField(FLIGHT_DATE_SEGMENT_1, COMP_DATA_ELEMENT_SEPARATOR)); assertEquals("2018-05-23", ParseDataSegment.extractFlightDateField(FLIGHT_DATE_SEGMENT_2, COMP_DATA_ELEMENT_SEPARATOR)); assertNotEquals("2018-01-19", ParseDataSegment.extractFlightDateField(FLIGHT_DATE_SEGMENT_1, COMP_DATA_ELEMENT_SEPARATOR)); assertNotEquals("2018-05-22", ParseDataSegment.extractFlightDateField(FLIGHT_DATE_SEGMENT_2, COMP_DATA_ELEMENT_SEPARATOR)); assertNull(ParseDataSegment.extractFlightDateField(null, COMP_DATA_ELEMENT_SEPARATOR)); } catch (Exception e) { e.printStackTrace(); } } @Test public void extractFlightDateTimeFieldTest() { try { assertEquals("2018-02-19 10:15:00", ParseDataSegment.extractFlightDateTimeField(FLIGHT_DATE_SEGMENT_1, COMP_DATA_ELEMENT_SEPARATOR)); assertEquals("2018-05-23 09:27:00", ParseDataSegment.extractFlightDateTimeField(FLIGHT_DATE_SEGMENT_2, COMP_DATA_ELEMENT_SEPARATOR)); assertNotEquals("2018-03-19 10:15:00", ParseDataSegment.extractFlightDateTimeField(FLIGHT_DATE_SEGMENT_1, COMP_DATA_ELEMENT_SEPARATOR)); assertNotEquals("2018-05-23 09:25:00", ParseDataSegment.extractFlightDateTimeField(FLIGHT_DATE_SEGMENT_2, COMP_DATA_ELEMENT_SEPARATOR)); assertNull(ParseDataSegment.extractFlightDateTimeField(null, COMP_DATA_ELEMENT_SEPARATOR)); } catch (Exception e) { e.printStackTrace(); } } @Test public void extractMiddleFieldTest() { try { assertEquals("P", ParseDataSegment.extractMiddleField(DOCUMENT_SEGMENT_1, DATA_ELEMENT_SEPARATOR)); assertEquals("V", ParseDataSegment.extractMiddleField(DOCUMENT_SEGMENT_2, DATA_ELEMENT_SEPARATOR)); assertNotEquals("V", ParseDataSegment.extractMiddleField(DOCUMENT_SEGMENT_1, DATA_ELEMENT_SEPARATOR)); assertNotEquals("P", ParseDataSegment.extractMiddleField(DOCUMENT_SEGMENT_2, DATA_ELEMENT_SEPARATOR)); assertNull(ParseDataSegment.extractMiddleField(null, DATA_ELEMENT_SEPARATOR)); assertNull(ParseDataSegment.extractMiddleField(DOCUMENT_SEGMENT_1, COMP_DATA_ELEMENT_SEPARATOR)); } catch (Exception e) { e.printStackTrace(); } } @Test public void getContactInfoTest() { try { // Equals String[] result1 = ParseDataSegment.getContactInfo(CONTACT_SEGMENT_1, DATA_ELEMENT_SEPARATOR, COMP_DATA_ELEMENT_SEPARATOR); String[] result2 = ParseDataSegment.getContactInfo(CONTACT_SEGMENT_2, DATA_ELEMENT_SEPARATOR, COMP_DATA_ELEMENT_SEPARATOR); assertEquals("044 222 222222", result1[0]); assertNull(result1[1]); assertNull(result1[2]); assertEquals("202 628 9292", result2[0]); assertEquals("202 628 4998", result2[1]); assertEquals("davidsonr.at.iata.org", result2[2]); // null String[] result3 = ParseDataSegment.getContactInfo(null, DATA_ELEMENT_SEPARATOR, COMP_DATA_ELEMENT_SEPARATOR); assertNotNull(result3); } catch (Exception e) { e.printStackTrace(); } } }
package hu.rbr.sfinapp.account.command; import hu.rbr.sfinapp.account.AccountCommandService; import hu.rbr.sfinapp.core.command.Handler; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class UpdateAccountCommandHandler implements Handler<UpdateAccountCommand> { private final AccountCommandService accountCommandService; @Inject public UpdateAccountCommandHandler(AccountCommandService accountCommandService) { this.accountCommandService = accountCommandService; } @Override public void handle(UpdateAccountCommand command) { accountCommandService.update(command); } @Override public Class<UpdateAccountCommand> commandClass() { return UpdateAccountCommand.class; } }
/* Copyright [2020] [https://www.xiaonuo.vip] 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. Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: 1.请不要删除和修改根目录下的LICENSE文件。 2.请不要删除和修改Snowy源码头部的版权声明。 3.请保留源码和相关描述文件的项目出处,作者声明等。 4.分发源码时候,请注明软件出处 https://gitee.com/xiaonuobase/snowy 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/xiaonuobase/snowy 6.若您的项目无法满足以上几点,可申请商业授权,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip */ package com.mofish.sober.sys.core.cache; import cn.hutool.core.collection.CollectionUtil; import java.util.Set; /** * 项目资源的缓存,存储了项目所有的访问url * <p> * 一般用在过滤器检测请求是否是项目没有的url * * @author yubaoshan * @date 2020/7/9 11:03 */ public class ResourceCache { private final Set<String> resourceCaches = CollectionUtil.newHashSet(); /** * 获取所有缓存资源 * * @author yubaoshan * @date 2020/7/9 13:52 */ public Set<String> getAllResources() { return resourceCaches; } /** * 直接缓存所有资源 * * @author yubaoshan * @date 2020/7/9 13:52 */ public void putAllResources(Set<String> resources) { resourceCaches.addAll(resources); } }