text
stringlengths
7
1.01M
package com.ceiba.usuario.modelo.dto; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public class DtoUsuarioEnvio { private Long id; private String nombre; private boolean premium; }
package com.z0ltan.compilers.microenglish.parser; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import static org.junit.Assert.assertEquals; import com.z0ltan.compilers.microenglish.scanner.Token; import com.z0ltan.compilers.microenglish.scanner.TokenType; public class ParserTest extends TestCase { public ParserTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(ParserTest.class); } public void test1() { String source = "I see the cat."; Parser parser = new Parser(source); parser.parse(); } public void test2() { String source = "I like me."; Parser parser = new Parser(source); parser.parse(); } public void test3() { String source = "I sees the mat."; Parser parser = new Parser(source); parser.parse(); } }
package com.google.ads.googleads.v10.services; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * <pre> * Service to manage labels on campaigns. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/ads/googleads/v10/services/campaign_label_service.proto") @io.grpc.stub.annotations.GrpcGenerated public final class CampaignLabelServiceGrpc { private CampaignLabelServiceGrpc() {} public static final String SERVICE_NAME = "google.ads.googleads.v10.services.CampaignLabelService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest, com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse> getMutateCampaignLabelsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "MutateCampaignLabels", requestType = com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest.class, responseType = com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest, com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse> getMutateCampaignLabelsMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest, com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse> getMutateCampaignLabelsMethod; if ((getMutateCampaignLabelsMethod = CampaignLabelServiceGrpc.getMutateCampaignLabelsMethod) == null) { synchronized (CampaignLabelServiceGrpc.class) { if ((getMutateCampaignLabelsMethod = CampaignLabelServiceGrpc.getMutateCampaignLabelsMethod) == null) { CampaignLabelServiceGrpc.getMutateCampaignLabelsMethod = getMutateCampaignLabelsMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest, com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "MutateCampaignLabels")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse.getDefaultInstance())) .setSchemaDescriptor(new CampaignLabelServiceMethodDescriptorSupplier("MutateCampaignLabels")) .build(); } } } return getMutateCampaignLabelsMethod; } /** * Creates a new async stub that supports all call types for the service */ public static CampaignLabelServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CampaignLabelServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CampaignLabelServiceStub>() { @java.lang.Override public CampaignLabelServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignLabelServiceStub(channel, callOptions); } }; return CampaignLabelServiceStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static CampaignLabelServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CampaignLabelServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CampaignLabelServiceBlockingStub>() { @java.lang.Override public CampaignLabelServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignLabelServiceBlockingStub(channel, callOptions); } }; return CampaignLabelServiceBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static CampaignLabelServiceFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CampaignLabelServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CampaignLabelServiceFutureStub>() { @java.lang.Override public CampaignLabelServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignLabelServiceFutureStub(channel, callOptions); } }; return CampaignLabelServiceFutureStub.newStub(factory, channel); } /** * <pre> * Service to manage labels on campaigns. * </pre> */ public static abstract class CampaignLabelServiceImplBase implements io.grpc.BindableService { /** * <pre> * Creates and removes campaign-label relationships. * Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [LabelError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * </pre> */ public void mutateCampaignLabels(com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getMutateCampaignLabelsMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getMutateCampaignLabelsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest, com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse>( this, METHODID_MUTATE_CAMPAIGN_LABELS))) .build(); } } /** * <pre> * Service to manage labels on campaigns. * </pre> */ public static final class CampaignLabelServiceStub extends io.grpc.stub.AbstractAsyncStub<CampaignLabelServiceStub> { private CampaignLabelServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CampaignLabelServiceStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignLabelServiceStub(channel, callOptions); } /** * <pre> * Creates and removes campaign-label relationships. * Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [LabelError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * </pre> */ public void mutateCampaignLabels(com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getMutateCampaignLabelsMethod(), getCallOptions()), request, responseObserver); } } /** * <pre> * Service to manage labels on campaigns. * </pre> */ public static final class CampaignLabelServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<CampaignLabelServiceBlockingStub> { private CampaignLabelServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CampaignLabelServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignLabelServiceBlockingStub(channel, callOptions); } /** * <pre> * Creates and removes campaign-label relationships. * Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [LabelError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse mutateCampaignLabels(com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getMutateCampaignLabelsMethod(), getCallOptions(), request); } } /** * <pre> * Service to manage labels on campaigns. * </pre> */ public static final class CampaignLabelServiceFutureStub extends io.grpc.stub.AbstractFutureStub<CampaignLabelServiceFutureStub> { private CampaignLabelServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CampaignLabelServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignLabelServiceFutureStub(channel, callOptions); } /** * <pre> * Creates and removes campaign-label relationships. * Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [LabelError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse> mutateCampaignLabels( com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getMutateCampaignLabelsMethod(), getCallOptions()), request); } } private static final int METHODID_MUTATE_CAMPAIGN_LABELS = 0; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final CampaignLabelServiceImplBase serviceImpl; private final int methodId; MethodHandlers(CampaignLabelServiceImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_MUTATE_CAMPAIGN_LABELS: serviceImpl.mutateCampaignLabels((com.google.ads.googleads.v10.services.MutateCampaignLabelsRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v10.services.MutateCampaignLabelsResponse>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static abstract class CampaignLabelServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { CampaignLabelServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.ads.googleads.v10.services.CampaignLabelServiceProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("CampaignLabelService"); } } private static final class CampaignLabelServiceFileDescriptorSupplier extends CampaignLabelServiceBaseDescriptorSupplier { CampaignLabelServiceFileDescriptorSupplier() {} } private static final class CampaignLabelServiceMethodDescriptorSupplier extends CampaignLabelServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; CampaignLabelServiceMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (CampaignLabelServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new CampaignLabelServiceFileDescriptorSupplier()) .addMethod(getMutateCampaignLabelsMethod()) .build(); } } } return result; } }
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.uimanager; import static android.view.View.MeasureSpec.AT_MOST; import static android.view.View.MeasureSpec.EXACTLY; import static android.view.View.MeasureSpec.UNSPECIFIED; import android.os.SystemClock; import android.view.View.MeasureSpec; import com.facebook.common.logging.FLog; import expolib_v1.com.facebook.infer.annotation.Assertions; import com.facebook.react.animation.Animation; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableArray; import com.facebook.react.common.ReactConstants; import com.facebook.react.modules.i18nmanager.I18nUtil; import com.facebook.react.uimanager.common.MeasureSpecProvider; import com.facebook.react.uimanager.common.SizeMonitoringFrameLayout; import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.systrace.Systrace; import com.facebook.systrace.SystraceMessage; import com.facebook.yoga.YogaDirection; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * An class that is used to receive React commands from JS and translate them into a * shadow node hierarchy that is then mapped to a native view hierarchy. */ public class UIImplementation { protected final EventDispatcher mEventDispatcher; protected final ReactApplicationContext mReactContext; protected final ShadowNodeRegistry mShadowNodeRegistry = new ShadowNodeRegistry(); private final Set<Integer> mMeasuredRootNodes = new HashSet<>(); private final ViewManagerRegistry mViewManagers; private final UIViewOperationQueue mOperationsQueue; private final NativeViewHierarchyOptimizer mNativeViewHierarchyOptimizer; private final int[] mMeasureBuffer = new int[4]; private long mLastCalculateLayoutTime = 0; protected @Nullable LayoutUpdateListener mLayoutUpdateListener; /** Interface definition for a callback to be invoked when the layout has been updated */ public interface LayoutUpdateListener { /** Called when the layout has been updated */ void onLayoutUpdated(ReactShadowNode root); } public UIImplementation( ReactApplicationContext reactContext, UIManagerModule.ViewManagerResolver viewManagerResolver, EventDispatcher eventDispatcher, int minTimeLeftInFrameForNonBatchedOperationMs) { this( reactContext, new ViewManagerRegistry(viewManagerResolver), eventDispatcher, minTimeLeftInFrameForNonBatchedOperationMs); } public UIImplementation( ReactApplicationContext reactContext, List<ViewManager> viewManagers, EventDispatcher eventDispatcher, int minTimeLeftInFrameForNonBatchedOperationMs) { this( reactContext, new ViewManagerRegistry(viewManagers), eventDispatcher, minTimeLeftInFrameForNonBatchedOperationMs); } private UIImplementation( ReactApplicationContext reactContext, ViewManagerRegistry viewManagers, EventDispatcher eventDispatcher, int minTimeLeftInFrameForNonBatchedOperationMs) { this( reactContext, viewManagers, new UIViewOperationQueue( reactContext, new NativeViewHierarchyManager(viewManagers), minTimeLeftInFrameForNonBatchedOperationMs), eventDispatcher); } protected UIImplementation( ReactApplicationContext reactContext, ViewManagerRegistry viewManagers, UIViewOperationQueue operationsQueue, EventDispatcher eventDispatcher) { mReactContext = reactContext; mViewManagers = viewManagers; mOperationsQueue = operationsQueue; mNativeViewHierarchyOptimizer = new NativeViewHierarchyOptimizer( mOperationsQueue, mShadowNodeRegistry); mEventDispatcher = eventDispatcher; } protected ReactShadowNode createRootShadowNode() { ReactShadowNode rootCSSNode = new ReactShadowNodeImpl(); I18nUtil sharedI18nUtilInstance = I18nUtil.getInstance(); if (sharedI18nUtilInstance.isRTL(mReactContext)) { rootCSSNode.setLayoutDirection(YogaDirection.RTL); } rootCSSNode.setViewClassName("Root"); return rootCSSNode; } protected ReactShadowNode createShadowNode(String className) { ViewManager viewManager = mViewManagers.get(className); return viewManager.createShadowNodeInstance(mReactContext); } public final ReactShadowNode resolveShadowNode(int reactTag) { return mShadowNodeRegistry.getNode(reactTag); } protected final ViewManager resolveViewManager(String className) { return mViewManagers.get(className); } /*package*/ UIViewOperationQueue getUIViewOperationQueue() { return mOperationsQueue; } /** * Updates the styles of the {@link ReactShadowNode} based on the Measure specs received by * parameters. */ public void updateRootView(int tag, int widthMeasureSpec, int heightMeasureSpec) { ReactShadowNode rootCSSNode = mShadowNodeRegistry.getNode(tag); if (rootCSSNode == null) { FLog.w(ReactConstants.TAG, "Tried to update non-existent root tag: " + tag); return; } updateRootView(rootCSSNode, widthMeasureSpec, heightMeasureSpec); } /** * Updates the styles of the {@link ReactShadowNode} based on the Measure specs received by * parameters. */ public void updateRootView( ReactShadowNode rootCSSNode, int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); switch (widthMode) { case EXACTLY: rootCSSNode.setStyleWidth(widthSize); break; case AT_MOST: rootCSSNode.setStyleMaxWidth(widthSize); break; case UNSPECIFIED: rootCSSNode.setStyleWidthAuto(); break; } int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (heightMode) { case EXACTLY: rootCSSNode.setStyleHeight(heightSize); break; case AT_MOST: rootCSSNode.setStyleMaxHeight(heightSize); break; case UNSPECIFIED: rootCSSNode.setStyleHeightAuto(); break; } } /** * Registers a root node with a given tag, size and ThemedReactContext and adds it to a node * registry. */ public <T extends SizeMonitoringFrameLayout & MeasureSpecProvider> void registerRootView( T rootView, int tag, ThemedReactContext context) { final ReactShadowNode rootCSSNode = createRootShadowNode(); rootCSSNode.setReactTag(tag); rootCSSNode.setThemedContext(context); int widthMeasureSpec = rootView.getWidthMeasureSpec(); int heightMeasureSpec = rootView.getHeightMeasureSpec(); updateRootView(rootCSSNode, widthMeasureSpec, heightMeasureSpec); context.runOnNativeModulesQueueThread(new Runnable() { @Override public void run() { mShadowNodeRegistry.addRootNode(rootCSSNode); } }); // register it within NativeViewHierarchyManager mOperationsQueue.addRootView(tag, rootView, context); } /** * Unregisters a root node with a given tag. */ public void removeRootView(int rootViewTag) { removeRootShadowNode(rootViewTag); mOperationsQueue.enqueueRemoveRootView(rootViewTag); } /** * Unregisters a root node with a given tag from the shadow node registry */ public void removeRootShadowNode(int rootViewTag) { mShadowNodeRegistry.removeRootNode(rootViewTag); } /** * Invoked when native view that corresponds to a root node, or acts as a root view (ie. Modals) * has its size changed. */ public void updateNodeSize( int nodeViewTag, int newWidth, int newHeight) { ReactShadowNode cssNode = mShadowNodeRegistry.getNode(nodeViewTag); if (cssNode == null) { FLog.w( ReactConstants.TAG, "Tried to update size of non-existent tag: " + nodeViewTag); return; } cssNode.setStyleWidth(newWidth); cssNode.setStyleHeight(newHeight); dispatchViewUpdatesIfNeeded(); } public void setViewLocalData(int tag, Object data) { ReactShadowNode shadowNode = mShadowNodeRegistry.getNode(tag); if (shadowNode == null) { FLog.w( ReactConstants.TAG, "Attempt to set local data for view with unknown tag: " + tag); return; } shadowNode.setLocalData(data); dispatchViewUpdatesIfNeeded(); } public void profileNextBatch() { mOperationsQueue.profileNextBatch(); } public Map<String, Long> getProfiledBatchPerfCounters() { return mOperationsQueue.getProfiledBatchPerfCounters(); } /** * Invoked by React to create a new node with a given tag, class name and properties. */ public void createView(int tag, String className, int rootViewTag, ReadableMap props) { ReactShadowNode cssNode = createShadowNode(className); ReactShadowNode rootNode = mShadowNodeRegistry.getNode(rootViewTag); Assertions.assertNotNull(rootNode, "Root node with tag " + rootViewTag + " doesn't exist"); cssNode.setReactTag(tag); cssNode.setViewClassName(className); cssNode.setRootTag(rootNode.getReactTag()); cssNode.setThemedContext(rootNode.getThemedContext()); mShadowNodeRegistry.addNode(cssNode); ReactStylesDiffMap styles = null; if (props != null) { styles = new ReactStylesDiffMap(props); cssNode.updateProperties(styles); } handleCreateView(cssNode, rootViewTag, styles); } protected void handleCreateView( ReactShadowNode cssNode, int rootViewTag, @Nullable ReactStylesDiffMap styles) { if (!cssNode.isVirtual()) { mNativeViewHierarchyOptimizer.handleCreateView(cssNode, cssNode.getThemedContext(), styles); } } /** * Invoked by React to create a new node with a given tag has its properties changed. */ public void updateView(int tag, String className, ReadableMap props) { ViewManager viewManager = mViewManagers.get(className); if (viewManager == null) { throw new IllegalViewOperationException("Got unknown view type: " + className); } ReactShadowNode cssNode = mShadowNodeRegistry.getNode(tag); if (cssNode == null) { throw new IllegalViewOperationException("Trying to update non-existent view with tag " + tag); } if (props != null) { ReactStylesDiffMap styles = new ReactStylesDiffMap(props); cssNode.updateProperties(styles); handleUpdateView(cssNode, className, styles); } } /** * Used by native animated module to bypass the process of updating the values through the shadow * view hierarchy. This method will directly update native views, which means that updates for * layout-related propertied won't be handled properly. * Make sure you know what you're doing before calling this method :) */ public void synchronouslyUpdateViewOnUIThread(int tag, ReactStylesDiffMap props) { UiThreadUtil.assertOnUiThread(); mOperationsQueue.getNativeViewHierarchyManager().updateProperties(tag, props); } protected void handleUpdateView( ReactShadowNode cssNode, String className, ReactStylesDiffMap styles) { if (!cssNode.isVirtual()) { mNativeViewHierarchyOptimizer.handleUpdateView(cssNode, className, styles); } } /** * Invoked when there is a mutation in a node tree. * * @param tag react tag of the node we want to manage * @param indicesToRemove ordered (asc) list of indicies at which view should be removed * @param viewsToAdd ordered (asc based on mIndex property) list of tag-index pairs that represent * a view which should be added at the specified index * @param tagsToDelete list of tags corresponding to views that should be removed */ public void manageChildren( int viewTag, @Nullable ReadableArray moveFrom, @Nullable ReadableArray moveTo, @Nullable ReadableArray addChildTags, @Nullable ReadableArray addAtIndices, @Nullable ReadableArray removeFrom) { ReactShadowNode cssNodeToManage = mShadowNodeRegistry.getNode(viewTag); int numToMove = moveFrom == null ? 0 : moveFrom.size(); int numToAdd = addChildTags == null ? 0 : addChildTags.size(); int numToRemove = removeFrom == null ? 0 : removeFrom.size(); if (numToMove != 0 && (moveTo == null || numToMove != moveTo.size())) { throw new IllegalViewOperationException("Size of moveFrom != size of moveTo!"); } if (numToAdd != 0 && (addAtIndices == null || numToAdd != addAtIndices.size())) { throw new IllegalViewOperationException("Size of addChildTags != size of addAtIndices!"); } // We treat moves as an add and a delete ViewAtIndex[] viewsToAdd = new ViewAtIndex[numToMove + numToAdd]; int[] indicesToRemove = new int[numToMove + numToRemove]; int[] tagsToRemove = new int[indicesToRemove.length]; int[] tagsToDelete = new int[numToRemove]; if (numToMove > 0) { Assertions.assertNotNull(moveFrom); Assertions.assertNotNull(moveTo); for (int i = 0; i < numToMove; i++) { int moveFromIndex = moveFrom.getInt(i); int tagToMove = cssNodeToManage.getChildAt(moveFromIndex).getReactTag(); viewsToAdd[i] = new ViewAtIndex( tagToMove, moveTo.getInt(i)); indicesToRemove[i] = moveFromIndex; tagsToRemove[i] = tagToMove; } } if (numToAdd > 0) { Assertions.assertNotNull(addChildTags); Assertions.assertNotNull(addAtIndices); for (int i = 0; i < numToAdd; i++) { int viewTagToAdd = addChildTags.getInt(i); int indexToAddAt = addAtIndices.getInt(i); viewsToAdd[numToMove + i] = new ViewAtIndex(viewTagToAdd, indexToAddAt); } } if (numToRemove > 0) { Assertions.assertNotNull(removeFrom); for (int i = 0; i < numToRemove; i++) { int indexToRemove = removeFrom.getInt(i); int tagToRemove = cssNodeToManage.getChildAt(indexToRemove).getReactTag(); indicesToRemove[numToMove + i] = indexToRemove; tagsToRemove[numToMove + i] = tagToRemove; tagsToDelete[i] = tagToRemove; } } // NB: moveFrom and removeFrom are both relative to the starting state of the View's children. // moveTo and addAt are both relative to the final state of the View's children. // // 1) Sort the views to add and indices to remove by index // 2) Iterate the indices being removed from high to low and remove them. Going high to low // makes sure we remove the correct index when there are multiple to remove. // 3) Iterate the views being added by index low to high and add them. Like the view removal, // iteration direction is important to preserve the correct index. Arrays.sort(viewsToAdd, ViewAtIndex.COMPARATOR); Arrays.sort(indicesToRemove); // Apply changes to CSSNodeDEPRECATED hierarchy int lastIndexRemoved = -1; for (int i = indicesToRemove.length - 1; i >= 0; i--) { int indexToRemove = indicesToRemove[i]; if (indexToRemove == lastIndexRemoved) { throw new IllegalViewOperationException("Repeated indices in Removal list for view tag: " + viewTag); } cssNodeToManage.removeChildAt(indicesToRemove[i]); lastIndexRemoved = indicesToRemove[i]; } for (int i = 0; i < viewsToAdd.length; i++) { ViewAtIndex viewAtIndex = viewsToAdd[i]; ReactShadowNode cssNodeToAdd = mShadowNodeRegistry.getNode(viewAtIndex.mTag); if (cssNodeToAdd == null) { throw new IllegalViewOperationException("Trying to add unknown view tag: " + viewAtIndex.mTag); } cssNodeToManage.addChildAt(cssNodeToAdd, viewAtIndex.mIndex); } if (!cssNodeToManage.isVirtual() && !cssNodeToManage.isVirtualAnchor()) { mNativeViewHierarchyOptimizer.handleManageChildren( cssNodeToManage, indicesToRemove, tagsToRemove, viewsToAdd, tagsToDelete); } for (int i = 0; i < tagsToDelete.length; i++) { removeShadowNode(mShadowNodeRegistry.getNode(tagsToDelete[i])); } } /** * An optimized version of manageChildren that is used for initial setting of child views. * The children are assumed to be in index order * * @param viewTag tag of the parent * @param childrenTags tags of the children */ public void setChildren( int viewTag, ReadableArray childrenTags) { ReactShadowNode cssNodeToManage = mShadowNodeRegistry.getNode(viewTag); for (int i = 0; i < childrenTags.size(); i++) { ReactShadowNode cssNodeToAdd = mShadowNodeRegistry.getNode(childrenTags.getInt(i)); if (cssNodeToAdd == null) { throw new IllegalViewOperationException("Trying to add unknown view tag: " + childrenTags.getInt(i)); } cssNodeToManage.addChildAt(cssNodeToAdd, i); } if (!cssNodeToManage.isVirtual() && !cssNodeToManage.isVirtualAnchor()) { mNativeViewHierarchyOptimizer.handleSetChildren( cssNodeToManage, childrenTags); } } /** * Replaces the View specified by oldTag with the View specified by newTag within oldTag's parent. */ public void replaceExistingNonRootView(int oldTag, int newTag) { if (mShadowNodeRegistry.isRootNode(oldTag) || mShadowNodeRegistry.isRootNode(newTag)) { throw new IllegalViewOperationException("Trying to add or replace a root tag!"); } ReactShadowNode oldNode = mShadowNodeRegistry.getNode(oldTag); if (oldNode == null) { throw new IllegalViewOperationException("Trying to replace unknown view tag: " + oldTag); } ReactShadowNode parent = oldNode.getParent(); if (parent == null) { throw new IllegalViewOperationException("Node is not attached to a parent: " + oldTag); } int oldIndex = parent.indexOf(oldNode); if (oldIndex < 0) { throw new IllegalStateException("Didn't find child tag in parent"); } WritableArray tagsToAdd = Arguments.createArray(); tagsToAdd.pushInt(newTag); WritableArray addAtIndices = Arguments.createArray(); addAtIndices.pushInt(oldIndex); WritableArray indicesToRemove = Arguments.createArray(); indicesToRemove.pushInt(oldIndex); manageChildren(parent.getReactTag(), null, null, tagsToAdd, addAtIndices, indicesToRemove); } /** * Method which takes a container tag and then releases all subviews for that container upon * receipt. * TODO: The method name is incorrect and will be renamed, #6033872 * @param containerTag the tag of the container for which the subviews must be removed */ public void removeSubviewsFromContainerWithID(int containerTag) { ReactShadowNode containerNode = mShadowNodeRegistry.getNode(containerTag); if (containerNode == null) { throw new IllegalViewOperationException( "Trying to remove subviews of an unknown view tag: " + containerTag); } WritableArray indicesToRemove = Arguments.createArray(); for (int childIndex = 0; childIndex < containerNode.getChildCount(); childIndex++) { indicesToRemove.pushInt(childIndex); } manageChildren(containerTag, null, null, null, null, indicesToRemove); } /** * Find the touch target child native view in the supplied root view hierarchy, given a react * target location. * * This method is currently used only by Element Inspector DevTool. * * @param reactTag the tag of the root view to traverse * @param targetX target X location * @param targetY target Y location * @param callback will be called if with the identified child view react ID, and measurement * info. If no view was found, callback will be invoked with no data. */ public void findSubviewIn(int reactTag, float targetX, float targetY, Callback callback) { mOperationsQueue.enqueueFindTargetForTouch(reactTag, targetX, targetY, callback); } /** * Check if the first shadow node is the descendant of the second shadow node */ public void viewIsDescendantOf( final int reactTag, final int ancestorReactTag, final Callback callback) { ReactShadowNode node = mShadowNodeRegistry.getNode(reactTag); ReactShadowNode ancestorNode = mShadowNodeRegistry.getNode(ancestorReactTag); if (node == null || ancestorNode == null) { callback.invoke(false); return; } callback.invoke(node.isDescendantOf(ancestorNode)); } /** * Determines the location on screen, width, and height of the given view relative to the root * view and returns the values via an async callback. */ public void measure(int reactTag, Callback callback) { // This method is called by the implementation of JS touchable interface (see Touchable.js for // more details) at the moment of touch activation. That is after user starts the gesture from // a touchable view with a given reactTag, or when user drag finger back into the press // activation area of a touchable view that have been activated before. mOperationsQueue.enqueueMeasure(reactTag, callback); } /** * Determines the location on screen, width, and height of the given view relative to the device * screen and returns the values via an async callback. This is the absolute position including * things like the status bar */ public void measureInWindow(int reactTag, Callback callback) { mOperationsQueue.enqueueMeasureInWindow(reactTag, callback); } /** * Measures the view specified by tag relative to the given ancestorTag. This means that the * returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the * given outputBuffer. We allow ancestor view and measured view to be the same, in which case * the position always will be (0, 0) and method will only measure the view dimensions. */ public void measureLayout( int tag, int ancestorTag, Callback errorCallback, Callback successCallback) { try { measureLayout(tag, ancestorTag, mMeasureBuffer); float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]); float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]); float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]); successCallback.invoke(relativeX, relativeY, width, height); } catch (IllegalViewOperationException e) { errorCallback.invoke(e.getMessage()); } } /** * Like {@link #measure} and {@link #measureLayout} but measures relative to the immediate parent. */ public void measureLayoutRelativeToParent( int tag, Callback errorCallback, Callback successCallback) { try { measureLayoutRelativeToParent(tag, mMeasureBuffer); float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]); float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]); float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]); successCallback.invoke(relativeX, relativeY, width, height); } catch (IllegalViewOperationException e) { errorCallback.invoke(e.getMessage()); } } /** * Invoked at the end of the transaction to commit any updates to the node hierarchy. */ public void dispatchViewUpdates(int batchId) { SystraceMessage.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementation.dispatchViewUpdates") .arg("batchId", batchId) .flush(); final long commitStartTime = SystemClock.uptimeMillis(); try { updateViewHierarchy(); mNativeViewHierarchyOptimizer.onBatchComplete(); mOperationsQueue.dispatchViewUpdates(batchId, commitStartTime, mLastCalculateLayoutTime); } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } } private void dispatchViewUpdatesIfNeeded() { // If we are in the middle of a batch update, any additional changes // will automatically be dispatched at the end of the batch. // If we are not, we have to initiate new batch update. // As all batches are executed as a single runnable on the event queue // this should always be empty, but that calling architecture is an implementation detail. if (mOperationsQueue.isEmpty()) { dispatchViewUpdates(-1); // "-1" means "no associated batch id" } } protected void updateViewHierarchy() { Systrace.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementation.updateViewHierarchy"); try { for (int i = 0; i < mShadowNodeRegistry.getRootNodeCount(); i++) { int tag = mShadowNodeRegistry.getRootTag(i); ReactShadowNode cssRoot = mShadowNodeRegistry.getNode(tag); if (mMeasuredRootNodes.contains(tag)) { SystraceMessage.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementation.notifyOnBeforeLayoutRecursive") .arg("rootTag", cssRoot.getReactTag()) .flush(); try { notifyOnBeforeLayoutRecursive(cssRoot); } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } calculateRootLayout(cssRoot); SystraceMessage.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementation.applyUpdatesRecursive") .arg("rootTag", cssRoot.getReactTag()) .flush(); try { applyUpdatesRecursive(cssRoot, 0f, 0f); } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } if (mLayoutUpdateListener != null) { mLayoutUpdateListener.onLayoutUpdated(cssRoot); } } } } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } } /** * Registers a new Animation that can then be added to a View using {@link #addAnimation}. */ public void registerAnimation(Animation animation) { mOperationsQueue.enqueueRegisterAnimation(animation); } /** * Adds an Animation previously registered with {@link #registerAnimation} to a View and starts it */ public void addAnimation(int reactTag, int animationID, Callback onSuccess) { assertViewExists(reactTag, "addAnimation"); mOperationsQueue.enqueueAddAnimation(reactTag, animationID, onSuccess); } /** * Removes an existing Animation, canceling it if it was in progress. */ public void removeAnimation(int reactTag, int animationID) { assertViewExists(reactTag, "removeAnimation"); mOperationsQueue.enqueueRemoveAnimation(animationID); } /** * LayoutAnimation API on Android is currently experimental. Therefore, it needs to be enabled * explicitly in order to avoid regression in existing application written for iOS using this API. * * Warning : This method will be removed in future version of React Native, and layout animation * will be enabled by default, so always check for its existence before invoking it. * * TODO(9139831) : remove this method once layout animation is fully stable. * * @param enabled whether layout animation is enabled or not */ public void setLayoutAnimationEnabledExperimental(boolean enabled) { mOperationsQueue.enqueueSetLayoutAnimationEnabled(enabled); } /** * Configure an animation to be used for the native layout changes, and native views * creation. The animation will only apply during the current batch operations. * * TODO(7728153) : animating view deletion is currently not supported. * TODO(7613721) : callbacks are not supported, this feature will likely be killed. * * @param config the configuration of the animation for view addition/removal/update. * @param success will be called when the animation completes, or when the animation get * interrupted. In this case, callback parameter will be false. * @param error will be called if there was an error processing the animation */ public void configureNextLayoutAnimation( ReadableMap config, Callback success, Callback error) { mOperationsQueue.enqueueConfigureLayoutAnimation(config, success, error); } public void setJSResponder(int reactTag, boolean blockNativeResponder) { ReactShadowNode node = mShadowNodeRegistry.getNode(reactTag); if (node == null) { //TODO: this should only happen when using Fabric renderer. This is a temporary approach //and it will be refactored when fabric supports JS Responder. return; } while (node.isVirtual() || node.isLayoutOnly()) { node = node.getParent(); } mOperationsQueue.enqueueSetJSResponder(node.getReactTag(), reactTag, blockNativeResponder); } public void clearJSResponder() { mOperationsQueue.enqueueClearJSResponder(); } public void dispatchViewManagerCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) { assertViewExists(reactTag, "dispatchViewManagerCommand"); mOperationsQueue.enqueueDispatchCommand(reactTag, commandId, commandArgs); } /** * Show a PopupMenu. * * @param reactTag the tag of the anchor view (the PopupMenu is displayed next to this view); this * needs to be the tag of a native view (shadow views can not be anchors) * @param items the menu items as an array of strings * @param error will be called if there is an error displaying the menu * @param success will be called with the position of the selected item as the first argument, or * no arguments if the menu is dismissed */ public void showPopupMenu(int reactTag, ReadableArray items, Callback error, Callback success) { assertViewExists(reactTag, "showPopupMenu"); mOperationsQueue.enqueueShowPopupMenu(reactTag, items, error, success); } public void dismissPopupMenu() { mOperationsQueue.enqueueDismissPopupMenu(); } public void sendAccessibilityEvent(int tag, int eventType) { mOperationsQueue.enqueueSendAccessibilityEvent(tag, eventType); } public void onHostResume() { mOperationsQueue.resumeFrameCallback(); } public void onHostPause() { mOperationsQueue.pauseFrameCallback(); } public void onHostDestroy() { } public void setViewHierarchyUpdateDebugListener( @Nullable NotThreadSafeViewHierarchyUpdateDebugListener listener) { mOperationsQueue.setViewHierarchyUpdateDebugListener(listener); } protected final void removeShadowNode(ReactShadowNode nodeToRemove) { removeShadowNodeRecursive(nodeToRemove); nodeToRemove.dispose(); } private void removeShadowNodeRecursive(ReactShadowNode nodeToRemove) { NativeViewHierarchyOptimizer.handleRemoveNode(nodeToRemove); mShadowNodeRegistry.removeNode(nodeToRemove.getReactTag()); mMeasuredRootNodes.remove(nodeToRemove.getReactTag()); for (int i = nodeToRemove.getChildCount() - 1; i >= 0; i--) { removeShadowNodeRecursive(nodeToRemove.getChildAt(i)); } nodeToRemove.removeAndDisposeAllChildren(); } private void measureLayout(int tag, int ancestorTag, int[] outputBuffer) { ReactShadowNode node = mShadowNodeRegistry.getNode(tag); ReactShadowNode ancestor = mShadowNodeRegistry.getNode(ancestorTag); if (node == null || ancestor == null) { throw new IllegalViewOperationException( "Tag " + (node == null ? tag : ancestorTag) + " does not exist"); } if (node != ancestor) { ReactShadowNode currentParent = node.getParent(); while (currentParent != ancestor) { if (currentParent == null) { throw new IllegalViewOperationException( "Tag " + ancestorTag + " is not an ancestor of tag " + tag); } currentParent = currentParent.getParent(); } } measureLayoutRelativeToVerifiedAncestor(node, ancestor, outputBuffer); } private void measureLayoutRelativeToParent(int tag, int[] outputBuffer) { ReactShadowNode node = mShadowNodeRegistry.getNode(tag); if (node == null) { throw new IllegalViewOperationException("No native view for tag " + tag + " exists!"); } ReactShadowNode parent = node.getParent(); if (parent == null) { throw new IllegalViewOperationException("View with tag " + tag + " doesn't have a parent!"); } measureLayoutRelativeToVerifiedAncestor(node, parent, outputBuffer); } private void measureLayoutRelativeToVerifiedAncestor( ReactShadowNode node, ReactShadowNode ancestor, int[] outputBuffer) { int offsetX = 0; int offsetY = 0; if (node != ancestor) { offsetX = Math.round(node.getLayoutX()); offsetY = Math.round(node.getLayoutY()); ReactShadowNode current = node.getParent(); while (current != ancestor) { Assertions.assertNotNull(current); assertNodeDoesNotNeedCustomLayoutForChildren(current); offsetX += Math.round(current.getLayoutX()); offsetY += Math.round(current.getLayoutY()); current = current.getParent(); } assertNodeDoesNotNeedCustomLayoutForChildren(ancestor); } outputBuffer[0] = offsetX; outputBuffer[1] = offsetY; outputBuffer[2] = node.getScreenWidth(); outputBuffer[3] = node.getScreenHeight(); } private void assertViewExists(int reactTag, String operationNameForExceptionMessage) { if (mShadowNodeRegistry.getNode(reactTag) == null) { throw new IllegalViewOperationException( "Unable to execute operation " + operationNameForExceptionMessage + " on view with " + "tag: " + reactTag + ", since the view does not exists"); } } private void assertNodeDoesNotNeedCustomLayoutForChildren(ReactShadowNode node) { ViewManager viewManager = Assertions.assertNotNull(mViewManagers.get(node.getViewClass())); ViewGroupManager viewGroupManager; if (viewManager instanceof ViewGroupManager) { viewGroupManager = (ViewGroupManager) viewManager; } else { throw new IllegalViewOperationException("Trying to use view " + node.getViewClass() + " as a parent, but its Manager doesn't extends ViewGroupManager"); } if (viewGroupManager != null && viewGroupManager.needsCustomLayoutForChildren()) { throw new IllegalViewOperationException( "Trying to measure a view using measureLayout/measureLayoutRelativeToParent relative to" + " an ancestor that requires custom layout for it's children (" + node.getViewClass() + "). Use measure instead."); } } private void notifyOnBeforeLayoutRecursive(ReactShadowNode cssNode) { if (!cssNode.hasUpdates()) { return; } for (int i = 0; i < cssNode.getChildCount(); i++) { notifyOnBeforeLayoutRecursive(cssNode.getChildAt(i)); } cssNode.onBeforeLayout(); } protected void calculateRootLayout(ReactShadowNode cssRoot) { SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "cssRoot.calculateLayout") .arg("rootTag", cssRoot.getReactTag()) .flush(); long startTime = SystemClock.uptimeMillis(); try { cssRoot.calculateLayout(); } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); mLastCalculateLayoutTime = SystemClock.uptimeMillis() - startTime; } } protected void applyUpdatesRecursive( ReactShadowNode cssNode, float absoluteX, float absoluteY) { if (!cssNode.hasUpdates()) { return; } if (!cssNode.isVirtualAnchor()) { for (int i = 0; i < cssNode.getChildCount(); i++) { applyUpdatesRecursive( cssNode.getChildAt(i), absoluteX + cssNode.getLayoutX(), absoluteY + cssNode.getLayoutY()); } } int tag = cssNode.getReactTag(); if (!mShadowNodeRegistry.isRootNode(tag)) { boolean frameDidChange = cssNode.dispatchUpdates( absoluteX, absoluteY, mOperationsQueue, mNativeViewHierarchyOptimizer); // Notify JS about layout event if requested // and if the position or dimensions actually changed // (consistent with iOS). if (frameDidChange && cssNode.shouldNotifyOnLayout()) { mEventDispatcher.dispatchEvent( OnLayoutEvent.obtain( tag, cssNode.getScreenX(), cssNode.getScreenY(), cssNode.getScreenWidth(), cssNode.getScreenHeight())); } } cssNode.markUpdateSeen(); } public void addUIBlock(UIBlock block) { mOperationsQueue.enqueueUIBlock(block); } public void prependUIBlock(UIBlock block) { mOperationsQueue.prependUIBlock(block); } public int resolveRootTagFromReactTag(int reactTag) { if (mShadowNodeRegistry.isRootNode(reactTag)) { return reactTag; } ReactShadowNode node = resolveShadowNode(reactTag); int rootTag = 0; if (node != null) { rootTag = node.getRootTag(); } else { FLog.w( ReactConstants.TAG, "Warning : attempted to resolve a non-existent react shadow node. reactTag=" + reactTag); } return rootTag; } /** * Enables Layout calculation for a Root node that has been measured. * * @param rootViewTag {@link int} Tag of the root node */ public void enableLayoutCalculationForRootNode(int rootViewTag) { this.mMeasuredRootNodes.add(rootViewTag); } public void setLayoutUpdateListener(LayoutUpdateListener listener) { mLayoutUpdateListener = listener; } public void removeLayoutUpdateListener() { mLayoutUpdateListener = null; } }
import java.util.InputMismatchException; import java.util.Scanner; public class Main { public static void main(String[] args) { try { Main mainObj = new Main(); CosineSeries cosine = new CosineSeries(mainObj.inputX(), mainObj.inputAccuracy()); double myCosineSum = cosine.calculateSum(); double builtInCosineSum = cosine.builtInCosine(); mainObj.printResults(myCosineSum, builtInCosineSum); } catch(InputMismatchException e) { System.out.println("Wrong input, numbers please"); } catch(NumberFormatException e) { System.out.println(e.toString()); } catch(Exception e) { System.out.println(e.toString()); } } private double inputX() { Scanner sc = new Scanner(System.in); return sc.nextDouble(); } private int inputAccuracy() { Scanner sc = new Scanner(System.in); return sc.nextInt(); } private void printResults(double myCosineSum, double builtInCosineSum) { System.out.println(String.format("My cosine: %1.3g", myCosineSum)); System.out.println(String.format("Built-in cosine: %1.3g", builtInCosineSum)); } }
package rxhttp.wrapper.parse; import java.io.IOException; import io.reactivex.annotations.NonNull; import okhttp3.Response; import okhttp3.ResponseBody; import rxhttp.wrapper.utils.IOUtil; /** * 文件下载解析器 * User: ljx * Date: 2018/10/23 * Time: 13:49 */ public class DownloadParser implements Parser<String> { private String mDestPath; /** * @param destPath 目标路径 */ public DownloadParser(@NonNull String destPath) { mDestPath = destPath; } /** * @param response Http请求执行结果 * @return 下载成功后的文件路径 * @throws IOException 网络异常等,RxJava的观察者会捕获此异常 */ @Override public String onParse(Response response) throws IOException { if (!response.isSuccessful()) throw new IOException(response.code() + " " + response.message()); ResponseBody body = response.body(); if (body == null) throw new IOException("ResponseBody is null"); boolean append = response.header("Content-Range") != null; IOUtil.write(body.byteStream(), mDestPath, append);//将输入流写出到文件 return mDestPath; } }
import net.mindview.util.Generator; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * @Author ZhangGJ * @Date 2019/10/04 */ class FibonacciSum implements Generator<Integer>, Callable<Integer> { private int count; private final int n; public FibonacciSum(int n) { this.n = n; } public Integer next() { return fib(count++); } private int fib(int n) { if (n < 2) return 1; return fib(n - 2) + fib(n - 1); } public Integer call() { int sum = 0; for (int i = 0; i < n; i++) sum += next(); return sum; } } public class E05_FibonacciSum { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>(); for (int i = 1; i <= 5; i++) results.add(exec.submit(new FibonacciSum(i))); Thread.yield(); exec.shutdown(); for (Future<Integer> fi : results) try { System.out.println(fi.get()); } catch (Exception e) { e.printStackTrace(); } } }
/** * Licensed to DigitalPebble Ltd under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * DigitalPebble licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.digitalpebble.stormcrawler.protocol.httpclient; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Locale; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.mutable.MutableBoolean; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ResponseHandler; import org.apache.http.client.config.AuthSchemes; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.apache.http.util.Args; import org.apache.http.util.ByteArrayBuffer; import org.apache.storm.Config; import org.slf4j.LoggerFactory; import com.digitalpebble.stormcrawler.Metadata; import com.digitalpebble.stormcrawler.persistence.Status; import com.digitalpebble.stormcrawler.protocol.AbstractHttpProtocol; import com.digitalpebble.stormcrawler.protocol.HttpHeaders; import com.digitalpebble.stormcrawler.protocol.ProtocolResponse; import com.digitalpebble.stormcrawler.util.ConfUtils; import com.digitalpebble.stormcrawler.util.CookieConverter; /** * Uses Apache httpclient to handle http and https **/ public class HttpProtocol extends AbstractHttpProtocol implements ResponseHandler<ProtocolResponse> { private static final org.slf4j.Logger LOG = LoggerFactory .getLogger(HttpProtocol.class); private static final PoolingHttpClientConnectionManager CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(); private int maxContent; private HttpClientBuilder builder; private RequestConfig requestConfig; @Override public void configure(final Config conf) { super.configure(conf); // allow up to 200 connections or same as the number of threads used for // fetching int maxFetchThreads = ConfUtils.getInt(conf, "fetcher.threads.number", 200); CONNECTION_MANAGER.setMaxTotal(maxFetchThreads); int maxPerRoute = ConfUtils .getInt(conf, "fetcher.threads.per.queue", 1); if (maxPerRoute < 20) { maxPerRoute = 20; } CONNECTION_MANAGER.setDefaultMaxPerRoute(maxPerRoute); this.maxContent = ConfUtils.getInt(conf, "http.content.limit", -1); String userAgent = getAgentString(conf); Collection<BasicHeader> defaultHeaders = new LinkedList<>(); String accept = ConfUtils.getString(conf, "http.accept"); if (StringUtils.isNotBlank(accept)) { defaultHeaders.add(new BasicHeader("Accept", accept)); } String basicAuthUser = ConfUtils.getString(conf, "http.basicauth.user", null); // use a basic auth? if (StringUtils.isNotBlank(basicAuthUser)) { String basicAuthPass = ConfUtils.getString(conf, "http.basicauth.password", ""); String encoding = Base64.getEncoder().encodeToString( (basicAuthUser + ":" + basicAuthPass).getBytes()); defaultHeaders.add(new BasicHeader("Authorization", "Basic " + encoding)); } String acceptLanguage = ConfUtils.getString(conf, "http.accept.language"); if (StringUtils.isNotBlank(acceptLanguage)) { defaultHeaders.add(new BasicHeader("Accept-Language", acceptLanguage)); } builder = HttpClients.custom().setUserAgent(userAgent) .setDefaultHeaders(defaultHeaders) .setConnectionManager(CONNECTION_MANAGER) .setConnectionManagerShared(true).disableRedirectHandling() .disableAutomaticRetries(); int timeout = ConfUtils.getInt(conf, "http.timeout", 10000); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setSocketTimeout(timeout).setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout) .setCookieSpec(CookieSpecs.STANDARD); String proxyHost = ConfUtils.getString(conf, "http.proxy.host", null); int proxyPort = ConfUtils.getInt(conf, "http.proxy.port", 8080); boolean useProxy = proxyHost != null && proxyHost.length() > 0; // use a proxy? if (useProxy) { String proxyUser = ConfUtils.getString(conf, "http.proxy.user", null); String proxyPass = ConfUtils.getString(conf, "http.proxy.pass", null); if (StringUtils.isNotBlank(proxyUser) && StringUtils.isNotBlank(proxyPass)) { List<String> authSchemes = new ArrayList<>(); // Can make configurable and add more in future authSchemes.add(AuthSchemes.BASIC); requestConfigBuilder.setProxyPreferredAuthSchemes(authSchemes); BasicCredentialsProvider basicAuthCreds = new BasicCredentialsProvider(); basicAuthCreds.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPass)); builder.setDefaultCredentialsProvider(basicAuthCreds); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner( proxy); builder.setRoutePlanner(routePlanner); } requestConfig = requestConfigBuilder.build(); } @Override public ProtocolResponse getProtocolOutput(String url, Metadata md) throws Exception { LOG.debug("HTTP connection manager stats {}", CONNECTION_MANAGER.getTotalStats()); HttpRequestBase request = new HttpGet(url); if (md != null) { String useHead = md.getFirstValue("http.method.head"); if ("true".equalsIgnoreCase(useHead)) { request = new HttpHead(url); } String lastModified = md.getFirstValue(HttpHeaders.LAST_MODIFIED); if (StringUtils.isNotBlank(lastModified)) { request.addHeader("If-Modified-Since", HttpHeaders.formatHttpDate(lastModified)); } String ifNoneMatch = md.getFirstValue("etag", protocolMDprefix); if (StringUtils.isNotBlank(ifNoneMatch)) { request.addHeader("If-None-Match", ifNoneMatch); } String accept = md.getFirstValue("http.accept"); if (StringUtils.isNotBlank(accept)) { request.setHeader(new BasicHeader("Accept", accept)); } String acceptLanguage = md.getFirstValue("http.accept.language"); if (StringUtils.isNotBlank(acceptLanguage)) { request.setHeader(new BasicHeader("Accept-Language", acceptLanguage)); } if (useCookies) { addCookiesToRequest(request, md); } } request.setConfig(requestConfig); // no need to release the connection explicitly as this is handled // automatically. The client itself must be closed though. try (CloseableHttpClient httpclient = builder.build()) { return httpclient.execute(request, this); } } private void addCookiesToRequest(HttpRequestBase request, Metadata md) { String[] cookieStrings = md.getValues(RESPONSE_COOKIES_HEADER, protocolMDprefix); if (cookieStrings != null && cookieStrings.length > 0) { List<Cookie> cookies; try { cookies = CookieConverter.getCookies(cookieStrings, request .getURI().toURL()); for (Cookie c : cookies) { request.addHeader("Cookie", c.getName() + "=" + c.getValue()); } } catch (MalformedURLException e) { // Bad url , nothing to do } } } @Override public ProtocolResponse handleResponse(HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode(); StringBuilder verbatim = new StringBuilder(); if (storeHTTPHeaders) { verbatim.append(statusLine.toString()).append("\r\n"); } Metadata metadata = new Metadata(); HeaderIterator iter = response.headerIterator(); while (iter.hasNext()) { Header header = iter.nextHeader(); if (storeHTTPHeaders) { verbatim.append(header.toString()).append("\r\n"); } metadata.addValue(header.getName().toLowerCase(Locale.ROOT), header.getValue()); } MutableBoolean trimmed = new MutableBoolean(); byte[] bytes = new byte[] {}; if (!Status.REDIRECTION.equals(Status.fromHTTPCode(status))) { bytes = HttpProtocol.toByteArray(response.getEntity(), maxContent, trimmed); if (trimmed.booleanValue()) { metadata.setValue(ProtocolResponse.TRIMMED_RESPONSE_KEY, "true"); LOG.warn("HTTP content trimmed to {}", bytes.length); } } if (storeHTTPHeaders) { verbatim.append("\r\n"); metadata.setValue(ProtocolResponse.RESPONSE_HEADERS_KEY, verbatim.toString()); } return new ProtocolResponse(bytes, status, metadata); } private static final byte[] toByteArray(final HttpEntity entity, int maxContent, MutableBoolean trimmed) throws IOException { if (entity == null) return new byte[] {}; final InputStream instream = entity.getContent(); if (instream == null) { return null; } Args.check(entity.getContentLength() <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory"); int reportedLength = (int) entity.getContentLength(); // set default size for buffer: 100 KB int bufferInitSize = 102400; if (reportedLength != -1) { bufferInitSize = reportedLength; } // avoid init of too large a buffer when we will trim anyway if (maxContent != -1 && bufferInitSize > maxContent) { bufferInitSize = maxContent; } final ByteArrayBuffer buffer = new ByteArrayBuffer(bufferInitSize); final byte[] tmp = new byte[4096]; int lengthRead; while ((lengthRead = instream.read(tmp)) != -1) { // check whether we need to trim if (maxContent != -1 && buffer.length() + lengthRead > maxContent) { buffer.append(tmp, 0, maxContent - buffer.length()); trimmed.setValue(true); break; } buffer.append(tmp, 0, lengthRead); } return buffer.toByteArray(); } public static void main(String args[]) throws Exception { HttpProtocol.main(new HttpProtocol(), args); } }
package com.timeyang.athena.task.exec; import org.apache.hadoop.conf.Configuration; /** * @author https://github.com/chaokunyang */ public interface TaskContext { long taskId(); Configuration hadoopConfiguration(); }
package com.firetower.auth_service; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class AuthServiceApplicationTests { @Test void contextLoads() { } }
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty 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 net.java.sip.communicator.impl.protocol.sip.net; import static net.java.sip.communicator.service.protocol.ProtocolProviderFactory.PROXY_AUTO_CONFIG; import java.net.*; import java.util.*; import net.java.sip.communicator.impl.protocol.sip.*; import net.java.sip.communicator.service.dns.*; /** * Abstract class for the determining the address for the SIP proxy. * * @author Ingo Bauersachs */ public abstract class ProxyConnection { private List<String> returnedAddresses = new LinkedList<String>(); protected String transport; protected InetSocketAddress socketAddress; protected final SipAccountIDImpl account; /** * Creates a new instance of this class. * @param account the account of this SIP protocol instance */ protected ProxyConnection(SipAccountIDImpl account) { this.account = account; } /** * Gets the address to use for the next connection attempt. * @return the address of the last lookup. */ public final InetSocketAddress getAddress() { return socketAddress; } /** * Gets the transport to use for the next connection attempt. * @return the transport of the last lookup. */ public final String getTransport() { return transport; } /** * In case we are using an outbound proxy this method returns * a suitable string for use with Router. * The method returns <tt>null</tt> otherwise. * * @return the string of our outbound proxy if we are using one and * <tt>null</tt> otherwise. */ public final String getOutboundProxyString() { if(socketAddress == null) return null; InetAddress proxyAddress = socketAddress.getAddress(); StringBuilder proxyStringBuffer = new StringBuilder(proxyAddress.getHostAddress()); if(proxyAddress instanceof Inet6Address) { proxyStringBuffer.insert(0, '['); proxyStringBuffer.append(']'); } proxyStringBuffer.append(':'); proxyStringBuffer.append(socketAddress.getPort()); proxyStringBuffer.append('/'); proxyStringBuffer.append(transport); return proxyStringBuffer.toString(); } /** * Compares an InetAddress against the active outbound proxy. The comparison * is by reference, not equals. * * @param addressToTest The addres to test. * @return True when the InetAddress is the same as the outbound proxy. */ public final boolean isSameInetAddress(InetAddress addressToTest) { // if the proxy is not yet initialized then this is not the provider // that caused this comparison if(socketAddress == null) return false; return addressToTest == socketAddress.getAddress(); } /** * Retrieves the next address to use from DNS. Duplicate results are * suppressed. * * @return True if a new address is available through {@link #getAddress()}, * false if the last address was reached. A new lookup from scratch * can be started by calling {@link #reset()}. * @throws DnssecException if there is a problem related to DNSSEC */ public final boolean getNextAddress() throws DnssecException { boolean result; String key = null; do { result = getNextAddressFromDns(); if(result && socketAddress != null) { key = getOutboundProxyString(); if(!returnedAddresses.contains(key)) { returnedAddresses.add(key); break; } } } while(result && returnedAddresses.contains(key)); return result; } /** * Implementations must use this method to get the next address, but do not * have to care about duplicate addresses. * * @return True when a further address was available. * @throws DnssecException when a DNSSEC validation failure occured. */ protected abstract boolean getNextAddressFromDns() throws DnssecException; /** * Resets the lookup to it's initial state. Overriders methods have to call * this method through a super-call. */ public void reset() { returnedAddresses.clear(); } /** * Factory method to create a proxy connection based on the account settings * of the protocol provider. * * @param pps the protocol provider that needs a SIP server connection. * @return An instance of a derived class. */ public static ProxyConnection create(ProtocolProviderServiceSipImpl pps) { if (pps.getAccountID().getAccountPropertyBoolean(PROXY_AUTO_CONFIG, true)) return new AutoProxyConnection((SipAccountIDImpl) pps.getAccountID(), pps.getDefaultTransport()); else return new ManualProxyConnection((SipAccountIDImpl) pps.getAccountID()); } }
package com.jn.kiku.dialog; import android.annotation.SuppressLint; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import com.jn.kiku.R; import com.jn.kiku.widget.imageview.SpinBlackView; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; /** * Author:Stevie.Chen Time:2019/8/29 * Class Comment:加载对话框 */ public class ProgressDialogFragment extends DialogFragment { private static final int TYPE_BLACK = 0x01; public static final int TYPE_WHITE = 0x02; private static final int DELAY_MILLISECOND = 450; private static final int SHOW_MIN_MILLISECOND = 300; private SpinBlackView mSpinBlackProgressView; private boolean startedShowing; private long mStartMillisecond; private long mStopMillisecond; private int mType = TYPE_BLACK;//类型 public static ProgressDialogFragment newInstance() { return newInstance(TYPE_BLACK); } public static ProgressDialogFragment newInstance(int type) { ProgressDialogFragment fragment = new ProgressDialogFragment(); Bundle bundle = new Bundle(); bundle.putInt(Integer.class.getSimpleName(), type); fragment.setArguments(bundle); return fragment; } // default constructor. Needed so rotation doesn't crash public ProgressDialogFragment() { super(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { mType = bundle.getInt(Integer.class.getSimpleName(), TYPE_BLACK); } View view = LayoutInflater.from(getContext()).inflate(mType == TYPE_BLACK ? R.layout.dialog_progress : R.layout.dialog_progress_white, container, false); mSpinBlackProgressView = view.findViewById(R.id.sbv_progressDialog); return view; } @SuppressLint("ResourceType") @Override public void onStart() { super.onStart(); if (getDialog().getWindow() != null) { Window window = getDialog().getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.width = WindowManager.LayoutParams.WRAP_CONTENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; //去掉背景色 lp.dimAmount = 0; lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); window.setAttributes(lp); getDialog().setCancelable(true);//点击外部区域隐藏对话框 } } @Override public void show(final FragmentManager fm, final String tag) { mStartMillisecond = System.currentTimeMillis(); startedShowing = false; mStopMillisecond = Long.MAX_VALUE; final Handler handler = new Handler(); handler.postDelayed(() -> { if (mStopMillisecond > System.currentTimeMillis()) showDialogAfterDelay(fm, tag); }, DELAY_MILLISECOND); } private void showDialogAfterDelay(FragmentManager fm, String tag) { startedShowing = true; FragmentTransaction ft = fm.beginTransaction(); ft.add(this, tag); ft.commitAllowingStateLoss(); } public void cancel() { mStopMillisecond = System.currentTimeMillis(); if (startedShowing) { if (mSpinBlackProgressView != null) { cancelWhenShowing(); } else { cancelWhenNotShowing(); } } } private void cancelWhenShowing() { if (mStopMillisecond < mStartMillisecond + DELAY_MILLISECOND + SHOW_MIN_MILLISECOND) { final Handler handler = new Handler(); handler.postDelayed(this::dismissAllowingStateLoss, SHOW_MIN_MILLISECOND); } else { dismissAllowingStateLoss(); } } private void cancelWhenNotShowing() { final Handler handler = new Handler(); handler.postDelayed(this::dismissAllowingStateLoss, DELAY_MILLISECOND); } /** * 设置加载图标 */ public ProgressDialogFragment setProgressImageResource(@DrawableRes int resId) { if (mSpinBlackProgressView != null) mSpinBlackProgressView.setImageResource(resId); return this; } }
/* * Copyright (c) 2017 Bixbit - Krzysztof Benedyczak All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.saml.metadata.srv; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.Paths; import java.util.Optional; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.Logger; import org.apache.xmlbeans.XmlException; import pl.edu.icm.unity.base.file.FileData; import pl.edu.icm.unity.base.utils.Log; import pl.edu.icm.unity.engine.api.files.FileStorageService; import pl.edu.icm.unity.engine.api.files.URIAccessService; import pl.edu.icm.unity.engine.api.files.URIHelper; import pl.edu.icm.unity.exceptions.EngineException; import xmlbeans.org.oasis.saml2.metadata.EntitiesDescriptorDocument; /** * Downloads on demand a remote metadata file and caches it on disk. * Allows for returning recently loaded file. * * @author K. Benedyczak */ public class MetadataDownloader { private static final Logger log = Log.getLogger(Log.U_SERVER_SAML, MetadataDownloader.class); private static final String CACHE_DIR = "downloadedMetadata"; private final URIAccessService uriAccessService; private final FileStorageService fileStorageService; public MetadataDownloader(URIAccessService uriAccessService, FileStorageService fileStorageService) { this.fileStorageService = fileStorageService; this.uriAccessService = uriAccessService; } /** * If url is local file, then return metadata read from it, * in other case try to download a remote file, cache it and read what is cached. * * @param url * @param customTruststore * @return * @throws EngineException * @throws IOException * @throws XmlException * @throws InterruptedException */ public EntitiesDescriptorDocument getFresh(String rawUri, String customTruststore) throws EngineException, IOException, XmlException, InterruptedException { URI uri = URIHelper.parseURI(rawUri); if (!URIHelper.isWebReady(uri)) { return EntitiesDescriptorDocument.Factory.parse(new ByteArrayInputStream(uriAccessService.readURI(uri).getContents())); } else { return loadFile(download(uri, customTruststore)); } } /** * @return null if there is no locally cached file or its handle * @throws IOException * @throws XmlException * @throws InterruptedException */ public Optional<EntitiesDescriptorDocument> getCached(String uri) throws XmlException, IOException, InterruptedException { FileData data; try { data = fileStorageService.readFileFromWorkspace(getFileName(uri)); } catch (Exception e) { return Optional.empty(); } log.debug("Get metadata file for "+ uri + " from cache"); return Optional.of(loadFile(new ByteArrayInputStream(data.getContents()))); } private EntitiesDescriptorDocument loadFile(InputStream file) throws XmlException, IOException, InterruptedException { InputStream is = new BufferedInputStream(file); String metadata = IOUtils.toString(is, Charset.defaultCharset()); log.trace("Read metadata:\n{}", metadata); EntitiesDescriptorDocument doc = EntitiesDescriptorDocument.Factory.parse(metadata); is.close(); return doc; } private InputStream download(URI uri, String customTruststore) throws IOException, EngineException { FileData data = uriAccessService.readURI(uri, customTruststore); FileData savedFile = fileStorageService.storeFileInWorkspace(data.getContents(), getFileName(uri.toString())); log.info("Downloaded metadata from " + uri.toString() + " and stored in " + savedFile.getName()); return new ByteArrayInputStream(savedFile.getContents()); } public static String getFileName(String uri) { return Paths.get(CACHE_DIR, DigestUtils.md5Hex(uri)).toString(); } }
/* * Copyright 2010 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.drools.mvel.integrationtests; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.drools.core.RuleBaseConfiguration; import org.drools.core.common.InternalAgenda; import org.drools.core.common.InternalFactHandle; import org.drools.core.impl.EnvironmentFactory; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.impl.KnowledgeBaseFactory; import org.drools.core.marshalling.impl.ClassObjectMarshallingStrategyAcceptor; import org.drools.core.marshalling.impl.IdentityPlaceholderResolverStrategy; import org.drools.mvel.compiler.Cheese; import org.drools.mvel.compiler.FactA; import org.drools.mvel.compiler.FactB; import org.drools.mvel.compiler.Order; import org.drools.mvel.compiler.OrderItem; import org.drools.mvel.compiler.Person; import org.drools.mvel.compiler.PersonInterface; import org.drools.mvel.compiler.Precondition; import org.drools.mvel.compiler.StockTick; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.builder.KieModule; import org.kie.api.definition.KiePackage; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.AgendaEventListener; import org.kie.api.event.rule.MatchCreatedEvent; import org.kie.api.marshalling.ObjectMarshallingStrategy; import org.kie.api.runtime.Environment; import org.kie.api.runtime.EnvironmentName; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.EntryPoint; import org.kie.api.runtime.rule.FactHandle; import org.mockito.ArgumentCaptor; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @RunWith(Parameterized.class) public class DynamicRulesTest { private final KieBaseTestConfiguration kieBaseTestConfiguration; public DynamicRulesTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { this.kieBaseTestConfiguration = kieBaseTestConfiguration; } @Parameterized.Parameters(name = "KieBase type={0}") public static Collection<Object[]> getParameters() { // TODO: EM failed with some tests. File JIRAs return TestParametersUtil.getKieBaseCloudConfigurations(false); } @Test(timeout=10000) public void testDynamicRuleAdditions() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration, "test_Dynamic1.drl"); KieSession workingMemory = kbase.newKieSession(); workingMemory.setGlobal("total", new Integer(0)); final List< ? > list = new ArrayList<Object>(); workingMemory.setGlobal( "list", list ); // Adding person in advance. There is no Person() object // type node in memory yet, but the rule engine is supposed // to handle that correctly final PersonInterface bob = new Person( "bob", "stilton" ); bob.setStatus( "Not evaluated" ); workingMemory.insert( bob ); final Cheese stilton = new Cheese( "stilton", 5 ); workingMemory.insert( stilton ); final Cheese cheddar = new Cheese( "cheddar", 5 ); workingMemory.insert(cheddar); workingMemory.fireAllRules(); assertEquals(1, list.size()); assertEquals("stilton", list.get(0)); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_Dynamic2.drl").getKiePackages(); kbase.addPackages(kpkgs); workingMemory.fireAllRules(); assertEquals(5, list.size()); assertEquals("stilton", list.get(0)); assertTrue("cheddar".equals(list.get(1)) || "cheddar".equals(list.get(2))); assertTrue("stilton".equals(list.get(1)) || "stilton".equals(list.get(2))); list.clear(); kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_Dynamic3.drl").getKiePackages(); kbase.addPackages(kpkgs); // Package 3 has a rule working on Person instances. // As we added person instance in advance, rule should fire now workingMemory.fireAllRules(); assertEquals("Rule from package 3 should have been fired", "match Person ok", bob.getStatus()); assertEquals(1, list.size()); assertEquals(bob, list.get(0)); kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_Dynamic4.drl").getKiePackages(); kbase.addPackages(kpkgs); workingMemory.fireAllRules(); assertEquals("Rule from package 4 should have been fired", "Who likes Stilton ok", bob.getStatus()); assertEquals( 2, list.size() ); assertEquals(bob, list.get(1)); } @Test(timeout=10000) public void testDynamicRuleRemovals() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration, "test_Dynamic1.drl", "test_Dynamic3.drl", "test_Dynamic4.drl"); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_Dynamic2.drl").getKiePackages(); kbase.addPackages(kpkgs); KieSession wm = kbase.newKieSession(); // AgendaEventListener ael = mock( AgendaEventListener.class ); // wm.addEventListener( ael ); final List< ? > list = new ArrayList<Object>(); wm.setGlobal( "list", list ); final PersonInterface bob = new Person( "bob", "stilton" ); bob.setStatus( "Not evaluated" ); FactHandle fh0 = wm.insert( bob ); final Cheese stilton1 = new Cheese( "stilton", 5 ); FactHandle fh1 = wm.insert( stilton1 ); final Cheese stilton2 = new Cheese( "stilton", 3 ); FactHandle fh2 = wm.insert( stilton2 ); final Cheese stilton3 = new Cheese( "stilton", 1 ); FactHandle fh3 = wm.insert( stilton3 ); final Cheese cheddar = new Cheese( "cheddar", 5 ); FactHandle fh4 = wm.insert( cheddar ); wm.fireAllRules(); assertEquals(15, list.size()); list.clear(); kbase.removeRule("org.drools.mvel.compiler.test", "Who likes Stilton"); wm.update(fh0, bob); wm.update(fh1, stilton1); wm.update(fh2, stilton2); wm.update(fh3, stilton3); wm.update(fh4, cheddar); wm.fireAllRules(); assertEquals(12, list.size()); list.clear(); kbase.removeRule("org.drools.mvel.compiler.test", "like cheese"); wm.update( fh0, bob); wm.update(fh1, stilton1); wm.update(fh2, stilton2); wm.update(fh3, stilton3); wm.update(fh4, cheddar); wm.fireAllRules(); assertEquals(8, list.size()); list.clear(); final Cheese muzzarela = new Cheese( "muzzarela", 5 ); wm.insert( muzzarela ); wm.fireAllRules(); assertEquals( 1, list.size() ); list.clear(); } @Test(timeout=10000) public void testDynamicRuleRemovalsUnusedWorkingMemory() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration, "test_Dynamic1.drl", "test_Dynamic2.drl", "test_Dynamic3.drl", "test_Dynamic4.drl"); KieSession workingMemory = kbase.newKieSession(); assertEquals( 2, kbase.getKiePackages().size() ); KiePackage knowledgePackage = null; for (KiePackage pkg : kbase.getKiePackages()) { if ( pkg.getName().equals( "org.drools.mvel.compiler.test" ) ) { knowledgePackage = pkg; break; } } assertEquals( 5, knowledgePackage.getRules().size() ); kbase.removeRule( "org.drools.mvel.compiler.test", "Who likes Stilton" ); assertEquals( 4, knowledgePackage.getRules().size() ); kbase.removeRule( "org.drools.mvel.compiler.test", "like cheese" ); assertEquals( 3, knowledgePackage.getRules().size() ); kbase.removeKiePackage( "org.drools.mvel.compiler.test" ); assertEquals( 1, kbase.getKiePackages().size() ); } @Ignore("Fails with standard-drl after changing to new API. See DROOLS-6060") @Test(timeout=10000) public void testDynamicFunction() throws Exception { //JBRULES-1258 serialising a package breaks function removal -- left the serialisation commented out for now Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicFunction1.drl").getKiePackages(); InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration); kbase.addPackages( kpkgs ); // kbase = SerializationHelper.serializeObject( kbase ); KieSession workingMemory = kbase.newKieSession(); final List<?> list = new ArrayList<Object>(); workingMemory.setGlobal( "list", list ); final Cheese stilton = new Cheese( "stilton", 5 ); workingMemory.insert( stilton ); workingMemory.fireAllRules(); assertEquals( new Integer( 5 ), list.get( 0 ) ); // Check a function can be removed from a package. // Once removed any efforts to use it should throw an Exception kbase.removeFunction( "org.drools.mvel.compiler.test", "addFive" ); final Cheese cheddar = new Cheese( "cheddar", 5 ); workingMemory.insert( cheddar ); try { workingMemory.fireAllRules(); fail( "Function should have been removed and NoClassDefFoundError thrown from the Consequence" ); } catch ( final Throwable e ) { } // Check a new function can be added to replace an old function Collection<KiePackage> kpkgs2 = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicFunction2.drl").getKiePackages(); kbase.addPackages( kpkgs2 ); final Cheese brie = new Cheese( "brie", 5 ); workingMemory.insert( brie ); workingMemory.fireAllRules(); assertEquals( new Integer( 6 ), list.get( 1 ) ); Collection<KiePackage> kpkgs3 = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicFunction3.drl").getKiePackages(); kbase.addPackages( kpkgs3 ); final Cheese feta = new Cheese( "feta", 5 ); workingMemory.insert( feta ); workingMemory.fireAllRules(); assertEquals( new Integer( 5 ), list.get( 2 ) ); } @Test (timeout=10000) public void testRemovePackage() throws Exception { Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_RemovePackage.drl").getKiePackages(); final String packageName = kpkgs.iterator().next().getName(); InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration); kbase.addPackages( kpkgs ); KieSession session = kbase.newKieSession(); session.insert( new Precondition( "genericcode", "genericvalue" ) ); session.fireAllRules(); InternalKnowledgeBase ruleBaseWM = (InternalKnowledgeBase) session.getKieBase(); ruleBaseWM.removeKiePackage( packageName ); kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_RemovePackage.drl").getKiePackages(); ruleBaseWM.addPackages( kpkgs ); ruleBaseWM = SerializationHelper.serializeObject( ruleBaseWM ); session = SerializationHelper.getSerialisedStatefulKnowledgeSession( session, true ); session.fireAllRules(); ruleBaseWM.removeKiePackage(packageName); ruleBaseWM.addPackages( SerializationHelper.serializeObject( kpkgs ) ); ruleBaseWM.removeKiePackage( packageName ); ruleBaseWM.addPackages(SerializationHelper.serializeObject(kpkgs)); } @Test(timeout=10000) public void testDynamicRules() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration); KieSession session = kbase.newKieSession(); final Cheese a = new Cheese( "stilton", 10 ); final Cheese b = new Cheese( "stilton", 15 ); final Cheese c = new Cheese( "stilton", 20 ); session.insert( a ); session.insert( b ); session.insert(c); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRules.drl").getKiePackages(); kbase.addPackages(kpkgs); session = SerializationHelper.getSerialisedStatefulKnowledgeSession( session, true ); session.fireAllRules(); } @Test(timeout=10000) public void testDynamicRules2() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration); KieSession session = kbase.newKieSession(); // Assert some simple facts final FactA a = new FactA( "hello", new Integer( 1 ), new Float( 3.14 ) ); final FactB b = new FactB( "hello", new Integer( 2 ), new Float( 6.28 ) ); session.insert( a ); session.insert( b ); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRules2.drl").getKiePackages(); kbase.addPackages( kpkgs ); session = SerializationHelper.getSerialisedStatefulKnowledgeSession( session, true ); session.fireAllRules(); } @Test(timeout=10000) public void testRuleBaseAddRemove() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources("test", getClass(), kieBaseTestConfiguration); //add and remove Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_Dynamic1.drl").getKiePackages(); String pkgName = kpkgs.iterator().next().getName(); kbase.addPackages( kpkgs ); kbase.removeKiePackage( pkgName ); //add and remove again kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_Dynamic1.drl").getKiePackages(); pkgName = kpkgs.iterator().next().getName(); kbase.addPackages( kpkgs ); kbase.removeKiePackage( pkgName ); } @Test(timeout=10000) public void testClassLoaderSwitchsUsingConf() throws Exception { try { // Creates first class loader and use it to load fact classes ClassLoader loader1 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/" )}, this.getClass().getClassLoader() ); Class cheeseClass = loader1.loadClass( "org.drools.mvel.compiler.Cheese" ); InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResourcesWithClassLoaderForKieBuilder("test", getClass(), loader1, kieBaseTestConfiguration, "test_Dynamic1.drl"); KieSession wm = kbase.newKieSession(); wm.insert( cheeseClass.newInstance() ); wm.fireAllRules(); // Creates second class loader and use it to load fact classes ClassLoader loader2 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/" )}, this.getClass().getClassLoader() ); cheeseClass = loader2.loadClass( "org.drools.mvel.compiler.Cheese" ); kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResourcesWithClassLoaderForKieBuilder("test", getClass(), loader2, kieBaseTestConfiguration, "test_Dynamic1.drl"); wm = kbase.newKieSession(); wm.insert(cheeseClass.newInstance()); wm.fireAllRules(); } catch ( ClassCastException cce ) { cce.printStackTrace(); fail( "No ClassCastException should be raised." ); } } @Test(timeout=10000) public void testClassLoaderSwitchsUsingContext() throws Exception { try { // Creates first class loader and use it to load fact classes ClassLoader original = Thread.currentThread().getContextClassLoader(); ClassLoader loader1 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/" )}, this.getClass().getClassLoader() ); Thread.currentThread().setContextClassLoader( loader1 ); Class cheeseClass = loader1.loadClass("org.drools.mvel.compiler.Cheese"); KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_Dynamic1.drl"); KieSession wm = kbase.newKieSession(); wm.insert( cheeseClass.newInstance() ); wm.fireAllRules(); // Creates second class loader and use it to load fact classes ClassLoader loader2 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/" )}, this.getClass().getClassLoader() ); Thread.currentThread().setContextClassLoader( loader2 ); cheeseClass = loader2.loadClass( "org.drools.mvel.compiler.Cheese" ); kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_Dynamic1.drl"); wm = kbase.newKieSession(); wm.insert( cheeseClass.newInstance() ); wm.fireAllRules(); Thread.currentThread().setContextClassLoader(original); } catch ( ClassCastException cce ) { cce.printStackTrace(); fail( "No ClassCastException should be raised." ); } } @Test(timeout=10000) public void testCollectDynamicRules() throws Exception { checkCollectWithDynamicRules( "test_CollectDynamicRules1.drl" ); } @Test(timeout=10000) public void testCollectDynamicRulesWithExistingOTN() throws Exception { checkCollectWithDynamicRules( "test_CollectDynamicRules1a.drl" ); } private void checkCollectWithDynamicRules(String originalDrl) throws java.io.IOException, ClassNotFoundException { InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, originalDrl); KieSession session = kbase.newKieSession(); List<?> list = new ArrayList<Object>(); session.setGlobal( "results", list ); session.insert( new Cheese( "stilton", 10 ) ); session.insert( new Cheese( "brie", 10 ) ); session.insert( new Cheese( "stilton", 10 ) ); session.insert( new Cheese( "muzzarela", 10 ) ); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_CollectDynamicRules2.drl").getKiePackages(); kbase.addPackages(kpkgs); session.fireAllRules(); // fire all rules is automatic assertEquals( 1, list.size() ); assertEquals( 2, ((List<?>) list.get( 0 )).size() ); } @Test(timeout=10000) public void testDynamicNotNode() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase)KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_CollectDynamicRules1.drl"); Environment env = EnvironmentFactory.newEnvironment(); env.set( EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{ new IdentityPlaceholderResolverStrategy( ClassObjectMarshallingStrategyAcceptor.DEFAULT )} ); KieSession ksession = kbase.newKieSession( null, env ); List<?> results = new ArrayList<Object>(); ksession.setGlobal( "results", results ); final Cheese a = new Cheese( "stilton", 10 ); final Cheese b = new Cheese( "stilton", 15 ); final Cheese c = new Cheese( "stilton", 20 ); ksession.insert( a ); ksession.insert( b ); ksession.insert( c ); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicNotNode.drl").getKiePackages(); kbase.addPackages( kpkgs ); ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession( ksession, false ); results = (List) ksession.getGlobal( "results" ); ksession.fireAllRules(); assertEquals( 0, results.size() ); kbase.removeKiePackage( "org.drools.mvel.compiler" ); ksession.retract( ksession.getFactHandle( b ) ); kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicNotNode.drl").getKiePackages(); kbase.addPackages( kpkgs ); ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession( ksession, false ); results = (List<?>) ksession.getGlobal( "results" ); ksession.fireAllRules(); assertEquals( 1, results.size() ); } @Test(timeout=10000) public void testDynamicRulesAddRemove() { try { InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_DynamicRulesTom.drl"); KieSession session = kbase.newKieSession(); List<?> results = new ArrayList<Object>(); session.setGlobal( "results", results ); InternalFactHandle h1 = (InternalFactHandle) session.insert( new Person( "tom", 1 ) ); InternalFactHandle h2 = (InternalFactHandle) session.insert( new Person( "fred", 2 ) ); InternalFactHandle h3 = (InternalFactHandle) session.insert( new Person( "harry", 3 ) ); InternalFactHandle h4 = (InternalFactHandle) session.insert( new Person( "fred", 4 ) ); InternalFactHandle h5 = (InternalFactHandle) session.insert( new Person( "ed", 5 ) ); InternalFactHandle h6 = (InternalFactHandle) session.insert( new Person( "tom", 6 ) ); InternalFactHandle h7 = (InternalFactHandle) session.insert( new Person( "sreeni", 7 ) ); InternalFactHandle h8 = (InternalFactHandle) session.insert( new Person( "jill", 8 ) ); InternalFactHandle h9 = (InternalFactHandle) session.insert( new Person( "ed", 9 ) ); InternalFactHandle h10 = (InternalFactHandle) session.insert( new Person( "tom", 10 ) ); session.fireAllRules(); assertEquals( 3, results.size() ); assertTrue( results.contains( h1.getObject() ) ); assertTrue( results.contains( h6.getObject() ) ); assertTrue( results.contains( h10.getObject() ) ); results.clear(); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesFred.drl").getKiePackages(); kbase.addPackages(kpkgs); session.fireAllRules(); assertEquals( 2, results.size() ); assertTrue( results.contains( h2.getObject() ) ); assertTrue( results.contains( h4.getObject() ) ); results.clear(); kbase.removeKiePackage( "tom" ); kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesEd.drl").getKiePackages(); kbase.addPackages(kpkgs); session.fireAllRules(); assertEquals( 2, results.size() ); assertTrue( results.contains( h5.getObject() ) ); assertTrue( results.contains( h9.getObject() ) ); results.clear(); ((Person) h3.getObject()).setName( "ed" ); session.update( h3, h3.getObject() ); session.fireAllRules(); assertEquals( 1, results.size() ); assertTrue( results.contains( h3.getObject() ) ); } catch ( Exception e ) { e.printStackTrace(); fail( "Should not raise any exception: " + e.getMessage() ); } } @Test(timeout=10000) public void testDynamicRuleRemovalsSubNetwork() throws Exception { Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithSubnetwork1.drl", "test_DynamicRulesWithSubnetwork.drl").getKiePackages(); InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration); kbase.addPackages( kpkgs ); kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithSubnetwork2.drl").getKiePackages(); kbase.addPackages( kpkgs ); KieSession session = kbase.newKieSession(); final List<?> list = new ArrayList<Object>(); session.setGlobal( "results", list ); Order order = new Order(); OrderItem item1 = new OrderItem( order, 1, "Adventure Guide Brazil", OrderItem.TYPE_BOOK, 24 ); order.addItem( item1 ); FactHandle item1Fh = session.insert( item1 ); OrderItem item2 = new OrderItem( order, 2, "Prehistoric Britain", OrderItem.TYPE_BOOK, 15 ); order.addItem( item2 ); FactHandle item2Fh = session.insert( item2 ); OrderItem item3 = new OrderItem( order, 3, "Holiday Music", OrderItem.TYPE_CD, 9 ); order.addItem( item3 ); FactHandle item3Fh = session.insert( item3 ); OrderItem item4 = new OrderItem( order, 4, "Very Best of Mick Jagger", OrderItem.TYPE_CD, 11 ); order.addItem( item4 ); FactHandle item4Fh = session.insert( item4 ); session.insert( order ); session.fireAllRules(); assertEquals( 11, list.size() ); kbase.removeRule( "org.drools.mvel.compiler", "Apply Discount on all books" ); list.clear(); session.update( item1Fh, item1 ); session.update( item2Fh, item2 ); session.update( item3Fh, item3 ); session.update( item4Fh, item4 ); session.fireAllRules(); assertEquals( 10, list.size() ); kbase.removeRule( "org.drools.mvel.compiler", "like book" ); list.clear(); session.update( item1Fh, item1 ); session.update( item2Fh, item2 ); session.update( item3Fh, item3 ); session.update( item4Fh, item4 ); session.fireAllRules(); assertEquals( 8, list.size() ); final OrderItem item5 = new OrderItem( order, 5, "Sinatra : Vegas", OrderItem.TYPE_CD, 5 ); FactHandle item5Fh = session.insert( item5 ); session.fireAllRules(); assertEquals( 10, list.size() ); kbase.removeKiePackage( "org.drools.mvel.compiler" ); list.clear(); session.update( item1Fh, item1 ); session.update( item2Fh, item2 ); session.update( item3Fh, item3 ); session.update( item4Fh, item4 ); session.update( item5Fh, item5 ); session.fireAllRules(); assertEquals( 0, list.size() ); } @Test(timeout=10000) public void testDynamicRuleRemovalsUnusedWorkingMemorySubNetwork() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithSubnetwork1.drl", "test_DynamicRulesWithSubnetwork2.drl", "test_DynamicRulesWithSubnetwork.drl"); assertEquals( 2, kbase.getKiePackages().size() ); assertEquals( 4, kbase.getPackagesMap().get("org.drools.mvel.compiler").getRules().size() ); kbase.removeRule( "org.drools.mvel.compiler", "Apply Discount on all books" ); assertEquals( 3, kbase.getPackagesMap().get("org.drools.mvel.compiler").getRules().size() ); kbase.removeRule( "org.drools.mvel.compiler", "like book" ); assertEquals( 2, kbase.getPackagesMap().get("org.drools.mvel.compiler").getRules().size() ); kbase.removeKiePackage( "org.drools.mvel.compiler" ); assertEquals( 1, kbase.getKiePackages().size() ); } @Test(timeout=10000) public void testRemovePackageSubNetwork() throws Exception { KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithSubnetwork.drl"); String packageName = kbase.getKiePackages().iterator().next().getName(); KieSession workingMemory = kbase.newKieSession(); List<?> results = new ArrayList<Object>(); workingMemory.setGlobal( "results", results ); Order order = new Order(); OrderItem item1 = new OrderItem( order, 1, "Adventure Guide Brazil", OrderItem.TYPE_BOOK, 24 ); OrderItem item2 = new OrderItem( order, 2, "Prehistoric Britain", OrderItem.TYPE_BOOK, 15 ); OrderItem item3 = new OrderItem( order, 3, "Holiday Music", OrderItem.TYPE_CD, 9 ); OrderItem item4 = new OrderItem( order, 4, "Very Best of Mick Jagger", OrderItem.TYPE_CD, 11 ); OrderItem item5 = new OrderItem( order, 5, "The Master and Margarita", OrderItem.TYPE_BOOK, 29 ); order.addItem( item1 ); order.addItem( item2 ); order.addItem( item3 ); order.addItem( item4 ); order.addItem( item5 ); workingMemory.insert( order ); workingMemory.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 3, ((List) results.get( 0 )).size() ); results.clear(); InternalKnowledgeBase ruleBaseWM = (InternalKnowledgeBase) workingMemory.getKieBase(); ruleBaseWM.removeKiePackage( packageName ); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithSubnetwork.drl").getKiePackages(); ruleBaseWM.addPackages(kpkgs); workingMemory.fireAllRules(); results = (List) workingMemory.getGlobal( "results" ); assertEquals( 1, results.size() ); assertEquals( 3, ((List) results.get( 0 )).size() ); results.clear(); ruleBaseWM.removeKiePackage( packageName ); ruleBaseWM.addPackages(kpkgs); workingMemory.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 3, ((List) results.get( 0 )).size() ); results.clear(); ruleBaseWM.removeKiePackage( packageName ); ruleBaseWM.addPackages(kpkgs); workingMemory.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 3, ((List) results.get( 0 )).size() ); results.clear(); } @Test(timeout=10000) public void testRuleBaseAddRemoveSubNetworks() throws Exception { try { //add and remove InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithSubnetwork.drl").getKiePackages(); KiePackage kpkg = (KiePackage) kpkgs.toArray()[0]; kbase.addPackages(kpkgs); kbase.removeKiePackage(kpkg.getName()); //add and remove again kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithSubnetwork.drl").getKiePackages(); kpkg = ( KiePackage ) kpkgs.toArray()[0]; kbase.addPackages(kpkgs); kbase.removeKiePackage(kpkg.getName()); } catch ( Exception e ) { e.printStackTrace(); fail( "Should not raise any exception" ); } } @Test (timeout=10000) public void testDynamicRuleAdditionsWithEntryPoints() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicWithEntryPoint.drl").getKiePackages(); KieSession ksession = kbase.newKieSession(); // now lets add some knowledge to the kbase kbase.addPackages( kpkgs ); List<StockTick> results = new ArrayList<StockTick>(); ksession.setGlobal( "results", results ); EntryPoint ep = ksession.getEntryPoint( "in-channel" ); ep.insert( new StockTick( 1, "RHT", 20, 10000 ) ); ep.insert( new StockTick( 2, "RHT", 21, 15000 ) ); ep.insert( new StockTick( 3, "RHT", 22, 20000 ) ); ksession.fireAllRules(); assertEquals( 3, results.size() ); } @Test(timeout=10000) public void testIsolatedClassLoaderWithEnumsPkgBuilder() throws Exception { try { // Creates first class loader and use it to load fact classes ClassLoader loader1 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/testEnum.jar" )}, this.getClass().getClassLoader() ); loader1.loadClass( "org.drools.Primitives" ); loader1.loadClass( "org.drools.TestEnum" ); // create a builder with the given classloader Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResourcesWithClassLoaderForKieBuilder("test", getClass(), loader1, kieBaseTestConfiguration, "test_EnumSerialization.drl").getKiePackages(); // adding original packages to a kbase just to make sure they are fine KieBaseConfiguration kbaseConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration( null, loader1 ); final KieModule kieModule = KieUtil.getKieModuleFromResourcesWithClassLoaderForKieBuilder("test", loader1, kieBaseTestConfiguration); InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.newKieBaseFromReleaseId(kieModule.getReleaseId(), kbaseConf); kbase.addPackages( kpkgs ); KieSession ksession = kbase.newKieSession(); List list = new ArrayList(); ksession.setGlobal( "list", list); assertEquals( 1, ksession.fireAllRules() ); assertEquals( 1, list.size() ); // now, create another classloader and make sure it has access to the classes ClassLoader loader2 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/testEnum.jar" )}, this.getClass().getClassLoader() ); loader2.loadClass( "org.drools.Primitives" ); loader2.loadClass( "org.drools.TestEnum" ); // create another kbase KieBaseConfiguration kbaseConf2 = KnowledgeBaseFactory.newKnowledgeBaseConfiguration( null, loader2 ); final KieModule kieModule2 = KieUtil.getKieModuleFromResourcesWithClassLoaderForKieBuilder("test2", loader2, kieBaseTestConfiguration); InternalKnowledgeBase kbase2 = (InternalKnowledgeBase) KieBaseUtil.newKieBaseFromReleaseId(kieModule2.getReleaseId(), kbaseConf2); kbase2.addPackages( kpkgs ); ksession = kbase2.newKieSession(); list = new ArrayList(); ksession.setGlobal( "list", list); assertEquals( 1, ksession.fireAllRules() ); assertEquals( 1, list.size() ); } catch ( ClassCastException cce ) { cce.printStackTrace(); fail( "No ClassCastException should be raised." ); } } @Test(timeout=10000) public void testIsolatedClassLoaderWithEnumsContextClassloader() throws Exception { try { // Creates first class loader and use it to load fact classes ClassLoader loader1 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/testEnum.jar" )}, this.getClass().getClassLoader() ); loader1.loadClass( "org.drools.Primitives" ); loader1.loadClass( "org.drools.TestEnum" ); // Build it using the current context ClassLoader ccl = Thread.currentThread().getContextClassLoader(); Collection<KiePackage> kpkgs = null; try { Thread.currentThread().setContextClassLoader( loader1 ); // create a builder with the given classloader kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_EnumSerialization.drl").getKiePackages(); // adding original packages to a kbase just to make sure they are fine InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration); kbase.addPackages( kpkgs ); KieSession ksession = kbase.newKieSession(); List list = new ArrayList(); ksession.setGlobal( "list", list); assertEquals( 1, ksession.fireAllRules() ); assertEquals( 1, list.size() ); } finally { Thread.currentThread().setContextClassLoader( ccl ); } // now, create another classloader and make sure it has access to the classes ClassLoader loader2 = new SubvertedClassLoader( new URL[]{getClass().getResource( "/testEnum.jar" )}, this.getClass().getClassLoader() ); loader2.loadClass( "org.drools.Primitives" ); loader2.loadClass( "org.drools.TestEnum" ); // set context classloader and use it ccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( loader2 ); // Note: This test originally serialize/deserialize kpkgs with different context classloaders. // Now exec-model doesn't support package serialization so we may remove this test. // create another kbase InternalKnowledgeBase kbase2 = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test2", kieBaseTestConfiguration); kbase2.addPackages( kpkgs ); KieSession ksession = kbase2.newKieSession(); List list = new ArrayList(); ksession.setGlobal( "list", list); assertEquals( 1, ksession.fireAllRules() ); assertEquals( 1, list.size() ); } finally { Thread.currentThread().setContextClassLoader( ccl ); } } catch ( ClassCastException cce ) { cce.printStackTrace(); fail( "No ClassCastException should be raised." ); } } @Test(timeout=10000) public void testDynamicRuleRemovalsSubNetworkAndNot() throws Exception { InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithNotSubnetwork.drl"); KieSession ksession = kbase.newKieSession(); final AgendaEventListener alistener = mock( AgendaEventListener.class ); ksession.addEventListener( alistener ); // pattern does not match, so do not activate ksession.insert( new Person( "toni" ) ); ksession.fireAllRules(); verify( alistener, never() ).matchCreated(any(org.kie.api.event.rule.MatchCreatedEvent.class)); // pattern matches, so create activation ksession.insert( new Person( "bob" ) ); ksession.fireAllRules(); verify( alistener, times( 1 ) ).matchCreated(any(org.kie.api.event.rule.MatchCreatedEvent.class)); // already active, so no new activation should be created ksession.insert( new Person( "mark" ) ); ksession.fireAllRules(); verify( alistener, times( 1 ) ).matchCreated(any(org.kie.api.event.rule.MatchCreatedEvent.class)); kbase.removeKiePackage( "org.drools.mvel.compiler" ); assertEquals( 0, kbase.getKiePackages().size() ); // lets re-compile and add it again Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_DynamicRulesWithNotSubnetwork.drl").getKiePackages(); kbase.addPackages( kpkgs ); ksession.fireAllRules(); // rule should be reactivated, since data is still in the session verify( alistener, times( 2 ) ).matchCreated(any(org.kie.api.event.rule.MatchCreatedEvent.class)); } @Test//(timeout=10000) public void testSharedLIANodeRemoval() throws Exception { // it's not a true share, but the liaNode will have two sinks, due to subnetwork. String str = "global java.util.List list;\n"; str += "rule \"test\"\n"; str += "when\n"; str += " exists(eval(true))\n"; str += "then\n"; str += " list.add(\"fired\");\n"; str += "end\n"; InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromKieModuleFromDrl("tmp", kieBaseTestConfiguration, str).getKiePackages(); // Add once ... kbase.addPackages( kpkgs ); // This one works List list = new ArrayList(); KieSession session = kbase.newKieSession(); session.setGlobal( "list", list ); session.fireAllRules(); assertEquals( 1, list.size() ); list.clear(); // ... remove ... KiePackage kpkg = ( KiePackage ) kpkgs.toArray()[0]; kbase.removeKiePackage( kpkg.getName() ); kbase.addPackages( kpkgs ); session = kbase.newKieSession(); session.setGlobal( "list", list ); session.fireAllRules(); assertEquals( 1, list.size() ); } @Test(timeout=10000) public void testDynamicRulesWithTypeDeclarations() { // Note: This test originally use "kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( kbase );" which is not possible with KieBuilder // Probably this new test is not valid for exec-model and we can remove this test String type = "package com.sample\n" + "declare type Foo\n" + " id : int\n" + "end\n"; String r1 = "package com.sample\n" + "rule R1 when\n" + " not Foo()\n" + "then\n" + " insert( new Foo(1) );\n" + "end\n"; String r2 = "package com.sample\n" + "rule R2 when\n" + " $f : Foo()\n" + "then\n" + " $f.setId( 2 );\n" + "end\n"; InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromKieModuleFromDrl("tmp", kieBaseTestConfiguration, type).getKiePackages(); kbase.addPackages(kpkgs); KieSession ksession = kbase.newKieSession(); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); ksession.fireAllRules(); verify( ael, never() ).afterMatchFired( any( AfterMatchFiredEvent.class ) ); kpkgs = KieBaseUtil.getKieBaseFromKieModuleFromDrl("tmp", kieBaseTestConfiguration, type, r1).getKiePackages(); kbase.addPackages(kpkgs); ksession.fireAllRules(); ArgumentCaptor<AfterMatchFiredEvent> capt = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); verify( ael, times(1) ).afterMatchFired( capt.capture() ); assertThat( "R1", is( capt.getValue().getMatch().getRule().getName() ) ); kpkgs = KieBaseUtil.getKieBaseFromKieModuleFromDrl("tmp", kieBaseTestConfiguration, type, r2).getKiePackages(); kbase.addPackages(kpkgs); ksession.fireAllRules(); verify( ael, times(2) ).afterMatchFired( capt.capture() ); assertThat( "R2", is( capt.getAllValues().get( 2 ).getMatch().getRule().getName() ) ); ksession.dispose(); } @Test(timeout=10000) public void testJBRULES_2206() { KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); ((RuleBaseConfiguration) config).setRuleBaseUpdateHandler( null ); final KieModule kieModule = KieUtil.getKieModuleFromResources(KieUtil.generateReleaseId("test"), kieBaseTestConfiguration); InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.newKieBaseFromReleaseId(kieModule.getReleaseId(), config); KieSession session = kbase.newKieSession(); AgendaEventListener ael = mock( AgendaEventListener.class ); session.addEventListener( ael ); for ( int i = 0; i < 5; i++ ) { session.insert( new Cheese() ); } Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_JBRULES_2206_1.drl").getKiePackages(); kbase.addPackages(kpkgs); ((InternalAgenda) session.getAgenda()).evaluateEagerList(); // two matching rules were added, so 2 activations should have been created verify( ael, times( 2 ) ).matchCreated(any(MatchCreatedEvent.class)); int fireCount = session.fireAllRules(); // both should have fired assertEquals( 2, fireCount ); kpkgs = KieBaseUtil.getKieBaseFromClasspathResources("tmp", getClass(), kieBaseTestConfiguration, "test_JBRULES_2206_2.drl").getKiePackages(); kbase.addPackages(kpkgs); ((InternalAgenda) session.getAgenda()).evaluateEagerList(); // one rule was overridden and should activate verify( ael, times( 3 ) ).matchCreated(any(MatchCreatedEvent.class)); fireCount = session.fireAllRules(); // that rule should fire again assertEquals( 1, fireCount ); session.dispose(); } public class SubvertedClassLoader extends URLClassLoader { private static final long serialVersionUID = 510l; public SubvertedClassLoader(final URL[] urls, final ClassLoader parentClassLoader) { super( urls, parentClassLoader ); } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class c = findLoadedClass( name ); if ( c == null ) { try { c = findClass( name ); } catch ( ClassNotFoundException e ) { c = super.loadClass( name, resolve ); } } return c; } } @Test public void testSegmentMerging() { String drl1 = "global java.util.List list\n" + "rule R1 when\n" + " $s : String()\n" + " $i : Integer( this == $s.length() )\n" + " $j : Integer( this == $i * 2 )\n" + "then\n" + " list.add( $j );\n" + "end\n"; String drl2 = "global java.util.List list\n" + "rule R2 when\n" + " $s : String()\n" + " $i : Integer( this == $s.length() )\n" + " $j : Integer( this == $i * 3 )\n" + "then\n" + " list.add( $j );\n" + "end\n"; InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration); Collection<KiePackage> kpkgs = KieBaseUtil.getKieBaseFromKieModuleFromDrl("tmp", kieBaseTestConfiguration, drl1).getKiePackages(); kbase.addPackages(kpkgs); KieSession ksession = kbase.newKieSession(); List<Integer> list = new ArrayList<Integer>(); ksession.setGlobal("list", list); ksession.insert("test"); ksession.insert(4); ksession.insert(8); ksession.insert(12); ksession.fireAllRules(); assertEquals(8, (int)list.get(0)); list.clear(); kpkgs = KieBaseUtil.getKieBaseFromKieModuleFromDrl("tmp", kieBaseTestConfiguration, drl2).getKiePackages(); kbase.addPackages(kpkgs); kbase.removeRule("defaultpkg", "R1"); ksession.fireAllRules(); assertEquals(12, (int)list.get(0)); } }
/* * Copyright 2019-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.rules.actions; import com.facebook.buck.core.artifact.Artifact; import com.facebook.buck.core.artifact.ArtifactDeclarationException; import com.facebook.buck.core.artifact.BuildArtifact; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.rules.analysis.action.ActionAnalysisData; import com.facebook.buck.core.rules.analysis.action.ActionAnalysisDataKey; import com.facebook.buck.core.rules.analysis.action.ActionAnalysisDataRegistry; import com.google.devtools.build.lib.events.Location; import java.nio.file.Path; /** * The registry for {@link Action}s, which creates its corresponding {@link ActionWrapperData}. * * <p>This helps to hide and enforce the relationship between {@link ActionAnalysisDataKey}, {@link * ActionAnalysisData}, {@link Action}, and {@link BuildArtifact}. * * <p>There is one registry per {@link BuildTarget}, such that all {@link Action}s registered by * this are considered to be associated with the build target. */ public interface ActionRegistry { /** * @param output the output {@link Path} relative to the package path for the current rule that * the {@link Action}s are being created for * @return a {@link Artifact} for the given path * @throws ArtifactDeclarationException if the provided output path is invalid */ default Artifact declareArtifact(Path output) throws ArtifactDeclarationException { return declareArtifact(output, Location.BUILTIN); } /** * @param output the output {@link Path} relative to the package path for the current rule that * the {@link Action}s are being created for * @param location if provided, the location within the extension file where this artifact was * declared * @return a {@link Artifact} for the given path * @throws ArtifactDeclarationException if the provided output path is invalid */ Artifact declareArtifact(Path output, Location location) throws ArtifactDeclarationException; /** * Creates the {@link ActionWrapperData} from its {@link Action} and registers the {@link * ActionWrapperData} to the {@link ActionAnalysisDataRegistry}. * * <p>This will materialize the declared {@link Artifact}s and bind them to the action. These * {@link Artifact}s that can be passed via {@link * com.google.devtools.build.lib.packages.Provider}s to be consumed. * * @param action the {@link Action} to create an {@link ActionWrapperData} for and registers it */ void registerActionAnalysisDataForAction(Action action) throws ActionCreationException; /** * @return the {@link BuildTarget} responsible for all the {@link Action}s registered to this * factory. */ BuildTarget getOwner(); /** * Verifies that all the {@link Artifact}s declared via {@link #declareArtifact(Path)} has been * bound with an {@link Action} via {@link #registerActionAnalysisDataForAction(Action)} */ void verifyAllArtifactsBound(); }
package spaceInvaders.Activities; import android.app.Activity; import android.graphics.Point; import android.os.Bundle; import android.view.Display; import spaceInvaders.SpaceInvadersJuego; public class MayorActivityRebotes extends Activity { SpaceInvadersJuego spaceInvadersJuego; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Resolución de la pantalla guardada en un Point Display display = getWindowManager().getDefaultDisplay(); Point point = new Point(); display.getSize(point); //La vista será la del juego spaceInvadersJuego = new SpaceInvadersJuego(this, point, true, true, this, getIntent().getExtras().getString("nombre")); setContentView(spaceInvadersJuego); } @Override protected void onPause(){ super.onPause(); spaceInvadersJuego.pause(); } @Override protected void onResume(){ super.onResume(); spaceInvadersJuego.resume(); } @Override protected void onStop(){ super.onStop(); //spaceInvadersJuego.stop(); } }
package com.shortthirdman.core.webservice.rest.jersey; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.message.internal.ReaderWriter; public class CustomLoggingFilter extends LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("User: ").append(requestContext.getSecurityContext().getUserPrincipal() == null ? "unknown" : requestContext.getSecurityContext().getUserPrincipal()); sb.append(" - Path: ").append(requestContext.getUriInfo().getPath()); sb.append(" - Header: ").append(requestContext.getHeaders()); sb.append(" - Entity: ").append(getEntityBody(requestContext)); System.out.println("HTTP REQUEST : " + sb.toString()); } private String getEntityBody(ContainerRequestContext requestContext) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = requestContext.getEntityStream(); final StringBuilder b = new StringBuilder(); try { ReaderWriter.writeTo(in, out); byte[] requestEntity = out.toByteArray(); if (requestEntity.length == 0) { b.append("").append("\n"); } else { b.append(new String(requestEntity)).append("\n"); } requestContext.setEntityStream(new ByteArrayInputStream(requestEntity)); } catch (IOException ex) { //Handle logging error } return b.toString(); } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("Header: ").append(responseContext.getHeaders()); sb.append(" - Entity: ").append(responseContext.getEntity()); System.out.println("HTTP RESPONSE : " + sb.toString()); } }
package com.github.openwebnet.service; import com.github.openwebnet.BuildConfig; import com.github.openwebnet.OpenWebNetApplicationTest; import com.github.openwebnet.component.ApplicationComponent; import com.github.openwebnet.component.Injector; import com.github.openwebnet.component.module.ApplicationContextModuleTest; import com.github.openwebnet.component.module.DatabaseModuleTest; import com.github.openwebnet.component.module.DomoticModule; import com.github.openwebnet.component.module.RepositoryModuleTest; import com.github.openwebnet.model.GatewayModel; import com.github.openwebnet.repository.GatewayRepository; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import dagger.Component; import rx.Observable; import rx.observers.TestSubscriber; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) @Config(application = OpenWebNetApplicationTest.class, constants = BuildConfig.class, sdk = 21) @PowerMockIgnore({"android.*"}) @PrepareForTest({Injector.class, GatewayModel.class}) public class GatewayServiceTest { @Rule public PowerMockRule rule = new PowerMockRule(); @Inject GatewayRepository gatewayRepository; @Inject GatewayService gatewayService; @Singleton @Component(modules = { ApplicationContextModuleTest.class, DatabaseModuleTest.class, RepositoryModuleTest.class, DomoticModule.class }) public interface GatewayComponentTest extends ApplicationComponent { void inject(GatewayServiceTest service); } @Before public void setupDagger() { GatewayComponentTest applicationComponentTest = DaggerGatewayServiceTest_GatewayComponentTest.builder() .applicationContextModuleTest(new ApplicationContextModuleTest()) .databaseModuleTest(new DatabaseModuleTest()) .repositoryModuleTest(new RepositoryModuleTest(true)) .domoticModule(new DomoticModule()) .build(); PowerMockito.mockStatic(Injector.class); PowerMockito.when(Injector.getApplicationComponent()).thenReturn(applicationComponentTest); ((GatewayComponentTest) Injector.getApplicationComponent()).inject(this); } @Ignore // Caused by: javassist.NotFoundException: io.reactivex.Flowable @Test public void gatewayService_add() { String GATEWAY_UUID = "gatewayUuid"; String GATEWAY_HOST = "1.1.1.1"; Integer GATEWAY_PORT = 88; String GATEWAY_PASSWORD = "PASSWORD"; GatewayModel gateway = new GatewayModel(); gateway.setUuid(GATEWAY_UUID); gateway.setHost(GATEWAY_HOST); gateway.setPort(GATEWAY_PORT); gateway.setPassword(GATEWAY_PASSWORD); PowerMockito.mockStatic(GatewayModel.class); when(GatewayModel.newGateway(GATEWAY_HOST, GATEWAY_PORT, GATEWAY_PASSWORD)).thenReturn(gateway); when(gatewayRepository.add(gateway)).thenReturn(Observable.just(GATEWAY_UUID)); TestSubscriber<String> tester = new TestSubscriber<>(); gatewayService.add(gateway).subscribe(tester); verify(gatewayRepository).add(gateway); tester.assertValue(GATEWAY_UUID); tester.assertCompleted(); tester.assertNoErrors(); } @Ignore // Caused by: javassist.NotFoundException: io.reactivex.Flowable @Test public void gatewayService_findAll() { List<GatewayModel> gateways = new ArrayList<>(); when(gatewayRepository.findAll()).thenReturn(Observable.just(gateways)); TestSubscriber<List<GatewayModel>> tester = new TestSubscriber<>(); gatewayService.findAll().subscribe(tester); verify(gatewayRepository).findAll(); tester.assertValue(gateways); tester.assertCompleted(); tester.assertNoErrors(); } @Ignore // Caused by: javassist.NotFoundException: io.reactivex.Flowable @Test public void gatewayService_findById() { String GATEWAY_UUID = "gatewayUuid"; GatewayModel gateway = new GatewayModel(); gateway.setUuid(GATEWAY_UUID); gateway.setHost("1.1.1.1"); gateway.setPort(88); when(gatewayRepository.findById(GATEWAY_UUID)).thenReturn(Observable.just(gateway)); TestSubscriber<GatewayModel> tester = new TestSubscriber<>(); gatewayService.findById(GATEWAY_UUID).subscribe(tester); verify(gatewayRepository).findById(GATEWAY_UUID); tester.assertValue(gateway); tester.assertCompleted(); tester.assertNoErrors(); } }
package uk.gov.ida.notification.eidassaml.apprule.rules; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.testing.ConfigOverride; import io.dropwizard.testing.junit.DropwizardAppRule; import org.glassfish.jersey.client.ClientProperties; import uk.gov.ida.notification.eidassaml.EidasSamlParserApplication; import uk.gov.ida.notification.eidassaml.EidasSamlParserConfiguration; import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static io.dropwizard.testing.ResourceHelpers.resourceFilePath; public class EidasSamlParserAppRule extends DropwizardAppRule<EidasSamlParserConfiguration> { private Client client; protected EidasSamlParserAppRule(ConfigOverride... configOverrides) { super( EidasSamlParserApplication.class, resourceFilePath("config.yml"), getConfigOverrides(configOverrides) ); } private static ConfigOverride[] getConfigOverrides(ConfigOverride... configOverrides) { List<ConfigOverride> configOverridesList = new ArrayList<>(Arrays.asList(configOverrides)); configOverridesList.add(ConfigOverride.config("server.applicationConnectors[0].port", "0")); configOverridesList.add(ConfigOverride.config("server.adminConnectors[0].port", "0")); configOverridesList.add(ConfigOverride.config("server.adminConnectors[0].port", "0")); configOverridesList.add(ConfigOverride.config("logging.appenders[0].type", "console")); configOverridesList.add(ConfigOverride.config("replayChecker.redisUrl", "")); return configOverridesList.toArray(new ConfigOverride[0]); } public WebTarget target(String path) throws URISyntaxException { return target(path, getLocalPort()); } public WebTarget target(String path, int port) throws URISyntaxException { if (client == null) { client = new JerseyClientBuilder(getEnvironment()) .withProperty(ClientProperties.CONNECT_TIMEOUT, 10000) .withProperty(ClientProperties.READ_TIMEOUT, 10000) .build("test client"); } return client.target(new URI("http://localhost:" + port).resolve(path)); } }
package com.asofdate.hauth.service.impl; import com.asofdate.hauth.authentication.JwtService; import com.asofdate.hauth.dto.AuthDto; import com.asofdate.hauth.service.AuthService; import com.asofdate.hauth.service.ShareDomainService; import com.asofdate.utils.factory.AuthDTOFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; /** * Created by hzwy23 on 2017/6/19. */ @Service public class AuthServiceImpl implements AuthService { private final String READ_MODE = "r"; private final String WRITE_MODE = "w"; @Autowired private ShareDomainService shareDomainService; private Integer checkMode(String mode) { if (mode.toLowerCase().equals(READ_MODE)) { return 1; } else if (mode.toLowerCase().equals(WRITE_MODE)) { return 2; } else { return -1; } } @Override public AuthDto domainAuth(HttpServletRequest request, String domainId, String mode) { String userDomainId = JwtService.getConnUser(request).getDomainID(); if (userDomainId.equals(domainId) || "vertex_root".equals(userDomainId)) { return AuthDTOFactory.getAuthDTO(true, "success"); } Integer level = shareDomainService.getAuthLevel(domainId, userDomainId); if (level == 2) { return AuthDTOFactory.getAuthDTO(true, "success"); } else if (level == 1 && checkMode(mode) == 2) { return AuthDTOFactory.getAuthDTO(false, "只有读取权限,没有写入权限"); } else if (level == 1 && checkMode(mode) == 1) { return AuthDTOFactory.getAuthDTO(true, "success"); } return AuthDTOFactory.getAuthDTO(false, "您没有被授权访问这个域"); } @Override public AuthDto basicAuth(HttpServletRequest request) { return null; } }
/* * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.sleuth.instrument.scheduling; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Configuration properties for {@link org.springframework.scheduling.annotation.Scheduled} tracing * * @author Arthur Gavlyukovskiy * @since 1.0.12 */ @ConfigurationProperties("spring.sleuth.scheduled") public class SleuthSchedulingProperties { /** * Enable tracing for {@link org.springframework.scheduling.annotation.Scheduled}. */ private boolean enabled = true; /** * Pattern for the fully qualified name of a class that should be skipped. */ private String skipPattern = "org.springframework.cloud.netflix.hystrix.stream.HystrixStreamTask"; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getSkipPattern() { return this.skipPattern; } public void setSkipPattern(String skipPattern) { this.skipPattern = skipPattern; } }
package com.hedera.services.state.submerkle; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.hedera.services.legacy.core.jproto.TxnReceipt; import com.hedera.services.utils.MiscUtils; import com.hederahashgraph.api.proto.java.TokenTransferList; import com.hederahashgraph.api.proto.java.TransactionRecord; import java.util.ArrayList; import java.util.List; import static com.hedera.services.state.submerkle.EntityId.fromGrpcScheduleId; import static com.hedera.services.state.submerkle.ExpirableTxnRecord.NO_TOKENS; import static java.util.stream.Collectors.toList; public class ExpirableTxnRecordTestHelper { public static ExpirableTxnRecord fromGprc(TransactionRecord record) { List<EntityId> tokens = NO_TOKENS; List<CurrencyAdjustments> tokenAdjustments = null; List<NftAdjustments> nftTokenAdjustments = null; int n = record.getTokenTransferListsCount(); if (n > 0) { tokens = new ArrayList<>(); tokenAdjustments = new ArrayList<>(); nftTokenAdjustments = new ArrayList<>(); for (TokenTransferList tokenTransfers : record.getTokenTransferListsList()) { tokens.add(EntityId.fromGrpcTokenId(tokenTransfers.getToken())); tokenAdjustments.add(CurrencyAdjustments.fromGrpc(tokenTransfers.getTransfersList())); nftTokenAdjustments.add(NftAdjustments.fromGrpc(tokenTransfers.getNftTransfersList())); } } return createExpiryTxnRecordFrom(record, tokens, tokenAdjustments, nftTokenAdjustments); } private static ExpirableTxnRecord createExpiryTxnRecordFrom(final TransactionRecord record, final List<EntityId> tokens, final List<CurrencyAdjustments> tokenAdjustments, final List<NftAdjustments> nftTokenAdjustments) { final var fcAssessedFees = record.getAssessedCustomFeesCount() > 0 ? record.getAssessedCustomFeesList().stream().map(FcAssessedCustomFee::fromGrpc).collect(toList()) : null; final var newTokenAssociations = record.getAutomaticTokenAssociationsList().stream().map(FcTokenAssociation::fromGrpc).collect(toList()); final var builder = ExpirableTxnRecord.newBuilder() .setReceipt(TxnReceipt.fromGrpc(record.getReceipt())) .setTxnHash(record.getTransactionHash().toByteArray()) .setTxnId(TxnId.fromGrpc(record.getTransactionID())) .setConsensusTime(RichInstant.fromGrpc(record.getConsensusTimestamp())) .setMemo(record.getMemo()) .setFee(record.getTransactionFee()) .setTransferList( record.hasTransferList() ? CurrencyAdjustments.fromGrpc(record.getTransferList()) : null) .setContractCallResult(record.hasContractCallResult() ? SolidityFnResult.fromGrpc( record.getContractCallResult()) : null) .setContractCreateResult(record.hasContractCreateResult() ? SolidityFnResult.fromGrpc( record.getContractCreateResult()) : null) .setTokens(tokens) .setTokenAdjustments(tokenAdjustments) .setNftTokenAdjustments(nftTokenAdjustments) .setScheduleRef(record.hasScheduleRef() ? fromGrpcScheduleId(record.getScheduleRef()) : null) .setAssessedCustomFees(fcAssessedFees) .setNewTokenAssociations(newTokenAssociations) .setAlias(record.getAlias()); if (record.hasParentConsensusTimestamp()) { builder.setParentConsensusTime(MiscUtils.timestampToInstant(record.getParentConsensusTimestamp())); } return builder.build(); } }
/* * eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) 2017 eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * 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 3 of the License, or * 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, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * Further, all user interfaces, including but not limited to citizen facing interfaces, * Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any * derived works should carry eGovernments Foundation logo on the top right corner. * * For the logo, please refer http://egovernments.org/html/logo/egov_logo.png. * For any further queries on attribution, including queries on brand guidelines, * please contact contact@egovernments.org * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. * */ package org.egov.wtms.integration; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import org.egov.commons.Installment; import org.egov.commons.dao.InstallmentHibDao; import org.egov.ptis.domain.model.AssessmentDetails; import org.egov.ptis.wtms.ConsumerConsumption; import org.egov.ptis.wtms.PropertyWiseConsumptions; import org.egov.ptis.wtms.WaterChargesIntegrationService; import org.egov.wtms.application.entity.NonMeteredConnBillDetails; import org.egov.wtms.application.entity.WaterConnection; import org.egov.wtms.application.entity.WaterConnectionDetails; import org.egov.wtms.application.service.ConnectionDetailService; import org.egov.wtms.application.service.WaterConnectionDetailsService; import org.egov.wtms.application.service.WaterConnectionService; import org.egov.wtms.masters.entity.enums.ConnectionStatus; import org.egov.wtms.masters.entity.enums.ConnectionType; import org.egov.wtms.utils.constants.WaterTaxConstants; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; public class WaterChargesIntegrationServiceImpl implements WaterChargesIntegrationService { @Autowired private WaterConnectionDetailsService waterConnectionDetailsService; @Autowired private WaterConnectionService waterConnectionService; @Autowired private ConnectionDetailService connectionDetailService; @Autowired private InstallmentHibDao installmentDao; @Override public PropertyWiseConsumptions getPropertyWiseConsumptionsForWaterCharges(final String propertyId) { final PropertyWiseConsumptions propertyWiseConsumptions = new PropertyWiseConsumptions(); propertyWiseConsumptions.setPropertyID(propertyId); BigDecimal currentTotal = BigDecimal.ZERO; BigDecimal arrearTotal = BigDecimal.ZERO; Installment arrInstal = null; final Installment currentInstallment = connectionDetailService .getCurrentInstallment(WaterTaxConstants.PROPERTY_MODULE_NAME, null, new Date()); final List<WaterConnection> waterConnections = waterConnectionService.findByPropertyIdentifier(propertyId); final List<ConsumerConsumption> consumerConsumptions = new ArrayList<>(); for (final WaterConnection waterConnection : waterConnections) { final WaterConnectionDetails waterConnectionDetails = waterConnectionDetailsService .findByConnection(waterConnection); if (waterConnectionDetails.getConnectionStatus().equals(ConnectionStatus.ACTIVE)) if (ConnectionType.NON_METERED.equals(waterConnectionDetails.getConnectionType())) { final ConsumerConsumption consumerConsumption = new ConsumerConsumption(); consumerConsumption.setHscno(waterConnectionDetails.getConnection().getConsumerCode()); final Map<String, BigDecimal> resultmap = connectionDetailService .getDemandCollMapForPtisIntegration(waterConnectionDetails, WaterTaxConstants.PROPERTY_MODULE_NAME); if (null != resultmap && !resultmap.isEmpty()) { final BigDecimal arrInstallment = resultmap.get(WaterTaxConstants.ARR_INSTALFROM_STR); if (null != arrInstallment && arrInstallment != BigDecimal.ZERO) arrInstal = installmentDao.findById(new Integer(arrInstallment.toString()), false); consumerConsumption.setCurrentDue(resultmap.get(WaterTaxConstants.CURR_DUE)); consumerConsumption.setArrearDue(resultmap.get(WaterTaxConstants.ARR_DUE)); if (null != arrInstal) { consumerConsumption.setArrearFromDate(new DateTime(arrInstal.getFromDate())); consumerConsumption .setArrearToDate(new DateTime(currentInstallment.getFromDate()).minusDays(1)); } consumerConsumption.setCurrentFromDate(new DateTime(currentInstallment.getFromDate())); consumerConsumption.setCurentToDate(new DateTime(currentInstallment.getToDate())); consumerConsumptions.add(consumerConsumption); currentTotal = currentTotal.add(consumerConsumption.getCurrentDue()); arrearTotal = arrearTotal.add(consumerConsumption.getArrearDue()); } } } propertyWiseConsumptions.setCurrentTotal(currentTotal); propertyWiseConsumptions.setArrearTotal(arrearTotal); propertyWiseConsumptions.setConsumerConsumptions(consumerConsumptions); return propertyWiseConsumptions; } @Override public boolean updateBillNo(final String propertyId, final String billNumber) { final List<WaterConnection> waterConnections = waterConnectionService.findByPropertyIdentifier(propertyId); HashSet<NonMeteredConnBillDetails> nonMeteredConnBillDetails = null; for (final WaterConnection waterConnection : waterConnections) { final NonMeteredConnBillDetails nonMeteredConnBillDetail = new NonMeteredConnBillDetails(); Installment installment = null; final WaterConnectionDetails waterConnectionDetails = waterConnectionDetailsService .getActiveNonHistoryConnectionDetailsByConnection(waterConnection); if (ConnectionType.NON_METERED.equals(waterConnectionDetails.getConnectionType())) { final Map<String, BigDecimal> resultmap = connectionDetailService.getDemandCollMapForBill( waterConnectionDetails, WaterTaxConstants.PROPERTY_MODULE_NAME, null); if (resultmap != null && !resultmap.isEmpty()) { nonMeteredConnBillDetails = new HashSet<>(); final BigDecimal install = resultmap.get("inst"); installment = installmentDao.findById(install.intValue(), false); nonMeteredConnBillDetail.setBillNo(billNumber); nonMeteredConnBillDetail.setWaterConnectionDetails( waterConnectionDetailsService.findBy(resultmap.get("wcdid").longValue())); nonMeteredConnBillDetail.setInstallment(installment); nonMeteredConnBillDetails.add(nonMeteredConnBillDetail); waterConnectionDetails.setNonmeteredBillDetails(nonMeteredConnBillDetails); waterConnectionDetailsService.save(waterConnectionDetails); } } } return true; } @Override public void updateConsumerIndex(final AssessmentDetails assessmentDetails) { final List<WaterConnection> waterConnections = waterConnectionService .findByPropertyIdentifier(assessmentDetails.getPropertyID()); for (final WaterConnection waterConnection : waterConnections) if (waterConnection.getConsumerCode() != null) { WaterConnectionDetails waterConnectionDetails = waterConnectionDetailsService .findByConsumerCodeAndConnectionStatus(waterConnection.getConsumerCode(), ConnectionStatus.ACTIVE); if (waterConnectionDetails == null) waterConnectionDetails = waterConnectionDetailsService.findByConsumerCodeAndConnectionStatus( waterConnection.getConsumerCode(), ConnectionStatus.INPROGRESS); if (waterConnectionDetails != null) waterConnectionDetailsService.createWaterChargeIndex(waterConnectionDetails, assessmentDetails, waterConnectionDetailsService.getTotalAmount(waterConnectionDetails)); } } }
/* * The MIT License * * Copyright 2021 Ethan Welborn - ethan.welborn@go.tarleton.edu. * * 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 edu.tarleton.welborn.medusacompiler.syntax; /** * * @author Ethan Welborn - ethan.welborn@go.tarleton.edu */ public class OptionalAssignmentTree extends AbstractSyntaxTree { private ExpressionTree expression; public OptionalAssignmentTree(ExpressionTree expression) { this.expression = expression; } public ExpressionTree getExpression() { return expression; } @Override public void printTree(int level) { super.printClassIndented("OptionalAssignmentTree", level); expression.printTree(level+1); } }
/* * 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 esquadrilha; import java.util.concurrent.ThreadLocalRandom; /** * Representação do avião * @author Karla */ public class Aviao extends Voador { public Aviao(Integer linha, Integer coluna, char direcaoFrente, Integer tempoChecagem, Integer velocidade) { super(new Posicao(linha, coluna), direcaoFrente, tempoChecagem, velocidade); } @Override public Boolean check() { if (getContadorTempoChecagem() == getTempoChecagem()) { setContadorTempoChecagem(0); return true; } return false; } /** * Voar em direção ao Pombo, método utilizado para quando o mesmo for avistado * @param posicaoPombo Posicao * @param direcaoPombo char */ public void voarAtrasPombo(Posicao posicaoPombo, char direcaoPombo) { System.out.println("AVIÃO PERSEGUINDO!\n"); //verifica a localização pela diferença entre os valores das posições em linhas e colunas Integer diferencaPosicoesLinha = getPosicaoAtual().getLinha() - posicaoPombo.getLinha() ; Integer diferencaPosicoesColuna = getPosicaoAtual().getColuna() - posicaoPombo.getColuna(); //para saber onde dobrar, caso o pombo esteja em uma linha diferente da do avião Integer sobraMetrosUtilizados = 0; //se a diferença entre as linhas das posições for menor que zero, o avião está acima do pombo, então deve ir para o sul if(diferencaPosicoesLinha < 0) { //se a diferença for menor que sua velocidade(quantas casas da matriz pode voar em cada segundo) ele voa toda a diferença para sul (chegando na linha do pombo) e armazena o que sobrou para fazer uma curva if((diferencaPosicoesLinha*-1) < getVelocidade()) { voar('S', diferencaPosicoesLinha*-1); sobraMetrosUtilizados = getVelocidade() + diferencaPosicoesLinha; } else { //se a diferença for maior ou igual a velocidade, voa com toda a sua velocidade disponível em direção a linha do pombo voar('S'); } //se a diferença for maior que zero, o avisão está abaixo do pombo, então deve ir em direção norte } else if(diferencaPosicoesLinha > 0) { //se a diferença for menor que a velocidade, anda toda a diferença para chegar até o pombo e armazena o que sobrou para fazer uma curva if(diferencaPosicoesLinha < getVelocidade()) { voar('N', diferencaPosicoesLinha); sobraMetrosUtilizados = getVelocidade() - diferencaPosicoesLinha; } else { //se a diferença for maior ou igual a velocidade, voa com toda a velocidade em direção ao pombo voar('N'); } } //verifica se o avião teve que voar para alcançar o pombo de acordo com as linhas, através da sobra de metros percorridos if(sobraMetrosUtilizados != 0) { if(diferencaPosicoesColuna < 0) //voa para leste se a diferença entre as colunas for menor que zero voar('L', sobraMetrosUtilizados); else if(diferencaPosicoesColuna > 0) //se for maior voa para oeste voar('O', sobraMetrosUtilizados); } else { if(diferencaPosicoesColuna < 0) voar('L'); else if((diferencaPosicoesColuna > 0)) voar('O'); } } /** * Voar em direção ao Pombo, método utilizado para quando o mesmo for avistado * @param posicaoPombo Posicao * @param direcaoPombo char */ public Boolean pegarPombo(Posicao posicaoPombo, char direcaoPombo) { //verifica a localização pela diferença entre os valores das posições em linhas e colunas Integer diferencaPosicoesLinha = getPosicaoAtual().getLinha() - posicaoPombo.getLinha() ; Integer diferencaPosicoesColuna = getPosicaoAtual().getColuna() - posicaoPombo.getColuna(); //para saber onde dobrar, caso o pombo esteja em uma linha diferente da do avião Integer sobraMetrosUtilizados = 0; //se a diferença entre as linhas das posições for menor que zero, o avião está acima do pombo, então deve ir para o sul if(diferencaPosicoesLinha < 0) { //se a diferença for menor que sua velocidade(quantas casas da matriz pode voar em cada segundo) ele voa toda a diferença para sul (chegando na linha do pombo) e armazena o que sobrou para fazer uma curva if((diferencaPosicoesLinha*-1) < getVelocidade()) { voar('S', diferencaPosicoesLinha*-1); sobraMetrosUtilizados = getVelocidade() + diferencaPosicoesLinha; } else { //se a diferença for maior ou igual a velocidade, voa com toda a sua velocidade disponível em direção a linha do pombo voar('S'); } //se a diferença for maior que zero, o avisão está abaixo do pombo, então deve ir em direção norte } else if(diferencaPosicoesLinha > 0) { //se a diferença for menor que a velocidade, anda toda a diferença para chegar até o pombo e armazena o que sobrou para fazer uma curva if(diferencaPosicoesLinha < getVelocidade()) { voar('N', diferencaPosicoesLinha); sobraMetrosUtilizados = getVelocidade() - diferencaPosicoesLinha; } else { //se a diferença for maior ou igual a velocidade, voa com toda a velocidade em direção ao pombo voar('N'); } } if(posicaoPombo.getLinha() == getPosicaoAtual().getLinha() && posicaoPombo.getColuna() == getPosicaoAtual().getColuna()) return true; //verifica se o avião teve que voar para alcançar o pombo de acordo com as linhas, através da sobra de metros percorridos if(sobraMetrosUtilizados != 0) { if(diferencaPosicoesColuna < 0) //voa para leste se a diferença entre as colunas for menor que zero voar('L', sobraMetrosUtilizados); else if(diferencaPosicoesColuna > 0) //se for maior voa para oeste voar('O', sobraMetrosUtilizados); } else { if(diferencaPosicoesColuna < 0) voar('L'); else if((diferencaPosicoesColuna > 0)) voar('O'); } if(posicaoPombo.getLinha() == getPosicaoAtual().getLinha() && posicaoPombo.getColuna() == getPosicaoAtual().getColuna()) return true; return false; } /** * Executar ação de voo com um valor máximo de metros a ser percorrido * @param novaDirecao char * @param qtdMetros Integer */ public void voar(char novaDirecao, Integer qtdMetros) { //cópia de qtdMetros (parte da velocidade) para realizar modificações sem alterar o valor real Integer velocidadeCopy = qtdMetros; Integer novaPosicao; if(isOposta(novaDirecao)) { int probabilidade = ThreadLocalRandom.current().nextInt(1, 100); velocidadeCopy--; if(probabilidade >= 1 && probabilidade <=50) { if(getDirecaoFrente() == 'N' || getDirecaoFrente() == 'S') { //se estiver indo para sul ou norte, define direção da curva para leste novaPosicao = getPosicaoAtual().getColuna()+1; getPosicaoAtual().setColuna(controleVoltaMatrizMaximo(novaPosicao)); } else { //e se estiver indo para leste ou oeste, define a direção da curva para norte novaPosicao = getPosicaoAtual().getLinha()-1; getPosicaoAtual().setLinha(controleVoltaMatrizMinimo(novaPosicao)); } } else { if(getDirecaoFrente() == 'N' || getDirecaoFrente() == 'S') { //se estiver indo para sul ou norte, define direção da curva para oeste novaPosicao = getPosicaoAtual().getColuna()-1; getPosicaoAtual().setColuna(controleVoltaMatrizMinimo(novaPosicao)); } else {//e se estiver indo para leste ou oeste, define a direção da curva para sul novaPosicao = getPosicaoAtual().getLinha()+1; getPosicaoAtual().setLinha(controleVoltaMatrizMaximo(novaPosicao)); } } } switch(novaDirecao) { case 'N': novaPosicao = getPosicaoAtual().getLinha()-velocidadeCopy; getPosicaoAtual().setLinha(controleVoltaMatrizMinimo(novaPosicao)); setDirecaoFrente('N'); break; case 'S': novaPosicao = getPosicaoAtual().getLinha()+velocidadeCopy; getPosicaoAtual().setLinha(controleVoltaMatrizMaximo(novaPosicao)); setDirecaoFrente('S'); break; case 'L': novaPosicao = getPosicaoAtual().getColuna()+velocidadeCopy; getPosicaoAtual().setColuna(controleVoltaMatrizMaximo(novaPosicao)); setDirecaoFrente('L'); break; default: novaPosicao = getPosicaoAtual().getColuna()-velocidadeCopy; getPosicaoAtual().setColuna(controleVoltaMatrizMinimo(novaPosicao)); setDirecaoFrente('O'); break; } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudsupport.v2beta.model; /** * A support case. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Cloud Support API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class CloudSupportCase extends com.google.api.client.json.GenericJson { /** * The issue classification applicable to this case. * The value may be {@code null}. */ @com.google.api.client.util.Key private CaseClassification classification; /** * Output only. The time this case was created. * The value may be {@code null}. */ @com.google.api.client.util.Key private String createTime; /** * The user who created the case. Note: The name and email will be obfuscated if the case was * created by Google Support. * The value may be {@code null}. */ @com.google.api.client.util.Key private Actor creator; /** * A broad description of the issue. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * The short summary of the issue reported in this case. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String displayName; /** * Whether the case is currently escalated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean escalated; /** * The resource name for the case. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * The priority of this case. If this is set, do not set severity. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String priority; /** * The severity of this case. Deprecated. Use priority instead. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String severity; /** * Output only. The current status of the support case. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String state; /** * The email addresses to receive updates on this case. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> subscriberEmailAddresses; /** * Whether this case was created for internal API testing and should not be acted on by the * support team. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean testCase; /** * The timezone of the user who created the support case. It should be in a format IANA * recognizes: https://www.iana.org/time-zones. There is no additional validation done by the API. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String timeZone; /** * Output only. The time this case was last updated. * The value may be {@code null}. */ @com.google.api.client.util.Key private String updateTime; /** * The issue classification applicable to this case. * @return value or {@code null} for none */ public CaseClassification getClassification() { return classification; } /** * The issue classification applicable to this case. * @param classification classification or {@code null} for none */ public CloudSupportCase setClassification(CaseClassification classification) { this.classification = classification; return this; } /** * Output only. The time this case was created. * @return value or {@code null} for none */ public String getCreateTime() { return createTime; } /** * Output only. The time this case was created. * @param createTime createTime or {@code null} for none */ public CloudSupportCase setCreateTime(String createTime) { this.createTime = createTime; return this; } /** * The user who created the case. Note: The name and email will be obfuscated if the case was * created by Google Support. * @return value or {@code null} for none */ public Actor getCreator() { return creator; } /** * The user who created the case. Note: The name and email will be obfuscated if the case was * created by Google Support. * @param creator creator or {@code null} for none */ public CloudSupportCase setCreator(Actor creator) { this.creator = creator; return this; } /** * A broad description of the issue. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * A broad description of the issue. * @param description description or {@code null} for none */ public CloudSupportCase setDescription(java.lang.String description) { this.description = description; return this; } /** * The short summary of the issue reported in this case. * @return value or {@code null} for none */ public java.lang.String getDisplayName() { return displayName; } /** * The short summary of the issue reported in this case. * @param displayName displayName or {@code null} for none */ public CloudSupportCase setDisplayName(java.lang.String displayName) { this.displayName = displayName; return this; } /** * Whether the case is currently escalated. * @return value or {@code null} for none */ public java.lang.Boolean getEscalated() { return escalated; } /** * Whether the case is currently escalated. * @param escalated escalated or {@code null} for none */ public CloudSupportCase setEscalated(java.lang.Boolean escalated) { this.escalated = escalated; return this; } /** * The resource name for the case. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * The resource name for the case. * @param name name or {@code null} for none */ public CloudSupportCase setName(java.lang.String name) { this.name = name; return this; } /** * The priority of this case. If this is set, do not set severity. * @return value or {@code null} for none */ public java.lang.String getPriority() { return priority; } /** * The priority of this case. If this is set, do not set severity. * @param priority priority or {@code null} for none */ public CloudSupportCase setPriority(java.lang.String priority) { this.priority = priority; return this; } /** * The severity of this case. Deprecated. Use priority instead. * @return value or {@code null} for none */ public java.lang.String getSeverity() { return severity; } /** * The severity of this case. Deprecated. Use priority instead. * @param severity severity or {@code null} for none */ public CloudSupportCase setSeverity(java.lang.String severity) { this.severity = severity; return this; } /** * Output only. The current status of the support case. * @return value or {@code null} for none */ public java.lang.String getState() { return state; } /** * Output only. The current status of the support case. * @param state state or {@code null} for none */ public CloudSupportCase setState(java.lang.String state) { this.state = state; return this; } /** * The email addresses to receive updates on this case. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSubscriberEmailAddresses() { return subscriberEmailAddresses; } /** * The email addresses to receive updates on this case. * @param subscriberEmailAddresses subscriberEmailAddresses or {@code null} for none */ public CloudSupportCase setSubscriberEmailAddresses(java.util.List<java.lang.String> subscriberEmailAddresses) { this.subscriberEmailAddresses = subscriberEmailAddresses; return this; } /** * Whether this case was created for internal API testing and should not be acted on by the * support team. * @return value or {@code null} for none */ public java.lang.Boolean getTestCase() { return testCase; } /** * Whether this case was created for internal API testing and should not be acted on by the * support team. * @param testCase testCase or {@code null} for none */ public CloudSupportCase setTestCase(java.lang.Boolean testCase) { this.testCase = testCase; return this; } /** * The timezone of the user who created the support case. It should be in a format IANA * recognizes: https://www.iana.org/time-zones. There is no additional validation done by the API. * @return value or {@code null} for none */ public java.lang.String getTimeZone() { return timeZone; } /** * The timezone of the user who created the support case. It should be in a format IANA * recognizes: https://www.iana.org/time-zones. There is no additional validation done by the API. * @param timeZone timeZone or {@code null} for none */ public CloudSupportCase setTimeZone(java.lang.String timeZone) { this.timeZone = timeZone; return this; } /** * Output only. The time this case was last updated. * @return value or {@code null} for none */ public String getUpdateTime() { return updateTime; } /** * Output only. The time this case was last updated. * @param updateTime updateTime or {@code null} for none */ public CloudSupportCase setUpdateTime(String updateTime) { this.updateTime = updateTime; return this; } @Override public CloudSupportCase set(String fieldName, Object value) { return (CloudSupportCase) super.set(fieldName, value); } @Override public CloudSupportCase clone() { return (CloudSupportCase) super.clone(); } }
package kotlin.jvm.internal; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.List; import kotlin.Metadata; import kotlin.SinceKotlin; import kotlin.jvm.JvmClassMappingKt; import kotlin.jvm.KotlinReflectionNotSupportedError; import kotlin.reflect.KCallable; import kotlin.reflect.KClass; import kotlin.reflect.KFunction; import kotlin.reflect.KType; import kotlin.reflect.KTypeParameter; import kotlin.reflect.KVisibility; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @Metadata( mv = {1, 1, 15}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000p\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010 \n\u0002\u0010\u001b\n\u0002\b\u0003\n\u0002\u0010\u001e\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\u000b\n\u0002\b\u0012\n\u0002\u0018\u0002\n\u0002\b\u0007\n\u0002\u0010\u000e\n\u0002\b\b\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0006\n\u0002\u0010\u0001\n\u0000\n\u0002\u0010\b\n\u0002\b\u0004\u0018\u00002\b\u0012\u0004\u0012\u00020\u00020\u00012\u00020\u0003B\u0011\u0012\n\u0010\u0004\u001a\u0006\u0012\u0002\b\u00030\u0005¢\u0006\u0002\u0010\u0006J\u0013\u0010B\u001a\u00020\u00122\b\u0010C\u001a\u0004\u0018\u00010\u0002H\u0096\u0002J\b\u0010D\u001a\u00020EH\u0002J\b\u0010F\u001a\u00020GH\u0016J\u0012\u0010H\u001a\u00020\u00122\b\u0010I\u001a\u0004\u0018\u00010\u0002H\u0017J\b\u0010J\u001a\u00020-H\u0016R\u001a\u0010\u0007\u001a\b\u0012\u0004\u0012\u00020\t0\b8VX\u0096\u0004¢\u0006\u0006\u001a\u0004\b\n\u0010\u000bR \u0010\f\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u00020\u00020\u000e0\r8VX\u0096\u0004¢\u0006\u0006\u001a\u0004\b\u000f\u0010\u0010R\u001a\u0010\u0011\u001a\u00020\u00128VX\u0097\u0004¢\u0006\f\u0012\u0004\b\u0013\u0010\u0014\u001a\u0004\b\u0011\u0010\u0015R\u001a\u0010\u0016\u001a\u00020\u00128VX\u0097\u0004¢\u0006\f\u0012\u0004\b\u0017\u0010\u0014\u001a\u0004\b\u0016\u0010\u0015R\u001a\u0010\u0018\u001a\u00020\u00128VX\u0097\u0004¢\u0006\f\u0012\u0004\b\u0019\u0010\u0014\u001a\u0004\b\u0018\u0010\u0015R\u001a\u0010\u001a\u001a\u00020\u00128VX\u0097\u0004¢\u0006\f\u0012\u0004\b\u001b\u0010\u0014\u001a\u0004\b\u001a\u0010\u0015R\u001a\u0010\u001c\u001a\u00020\u00128VX\u0097\u0004¢\u0006\f\u0012\u0004\b\u001d\u0010\u0014\u001a\u0004\b\u001c\u0010\u0015R\u001a\u0010\u001e\u001a\u00020\u00128VX\u0097\u0004¢\u0006\f\u0012\u0004\b\u001f\u0010\u0014\u001a\u0004\b\u001e\u0010\u0015R\u001a\u0010 \u001a\u00020\u00128VX\u0097\u0004¢\u0006\f\u0012\u0004\b!\u0010\u0014\u001a\u0004\b \u0010\u0015R\u0018\u0010\u0004\u001a\u0006\u0012\u0002\b\u00030\u0005X\u0096\u0004¢\u0006\b\n\u0000\u001a\u0004\b\"\u0010#R\u001e\u0010$\u001a\f\u0012\b\u0012\u0006\u0012\u0002\b\u00030%0\r8VX\u0096\u0004¢\u0006\u0006\u001a\u0004\b&\u0010\u0010R\u001e\u0010'\u001a\f\u0012\b\u0012\u0006\u0012\u0002\b\u00030\u00010\r8VX\u0096\u0004¢\u0006\u0006\u001a\u0004\b(\u0010\u0010R\u0016\u0010)\u001a\u0004\u0018\u00010\u00028VX\u0096\u0004¢\u0006\u0006\u001a\u0004\b*\u0010+R\u0016\u0010,\u001a\u0004\u0018\u00010-8VX\u0096\u0004¢\u0006\u0006\u001a\u0004\b.\u0010/R(\u00100\u001a\u0010\u0012\f\u0012\n\u0012\u0006\b\u0001\u0012\u00020\u00020\u00010\b8VX\u0097\u0004¢\u0006\f\u0012\u0004\b1\u0010\u0014\u001a\u0004\b2\u0010\u000bR\u0016\u00103\u001a\u0004\u0018\u00010-8VX\u0096\u0004¢\u0006\u0006\u001a\u0004\b4\u0010/R \u00105\u001a\b\u0012\u0004\u0012\u0002060\b8VX\u0097\u0004¢\u0006\f\u0012\u0004\b7\u0010\u0014\u001a\u0004\b8\u0010\u000bR \u00109\u001a\b\u0012\u0004\u0012\u00020:0\b8VX\u0097\u0004¢\u0006\f\u0012\u0004\b;\u0010\u0014\u001a\u0004\b<\u0010\u000bR\u001c\u0010=\u001a\u0004\u0018\u00010>8VX\u0097\u0004¢\u0006\f\u0012\u0004\b?\u0010\u0014\u001a\u0004\b@\u0010A¨\u0006K"}, d2 = {"Lkotlin/jvm/internal/ClassReference;", "Lkotlin/reflect/KClass;", "", "Lkotlin/jvm/internal/ClassBasedDeclarationContainer;", "jClass", "Ljava/lang/Class;", "(Ljava/lang/Class;)V", "annotations", "", "", "getAnnotations", "()Ljava/util/List;", "constructors", "", "Lkotlin/reflect/KFunction;", "getConstructors", "()Ljava/util/Collection;", "isAbstract", "", "isAbstract$annotations", "()V", "()Z", "isCompanion", "isCompanion$annotations", "isData", "isData$annotations", "isFinal", "isFinal$annotations", "isInner", "isInner$annotations", "isOpen", "isOpen$annotations", "isSealed", "isSealed$annotations", "getJClass", "()Ljava/lang/Class;", "members", "Lkotlin/reflect/KCallable;", "getMembers", "nestedClasses", "getNestedClasses", "objectInstance", "getObjectInstance", "()Ljava/lang/Object;", "qualifiedName", "", "getQualifiedName", "()Ljava/lang/String;", "sealedSubclasses", "sealedSubclasses$annotations", "getSealedSubclasses", "simpleName", "getSimpleName", "supertypes", "Lkotlin/reflect/KType;", "supertypes$annotations", "getSupertypes", "typeParameters", "Lkotlin/reflect/KTypeParameter;", "typeParameters$annotations", "getTypeParameters", "visibility", "Lkotlin/reflect/KVisibility;", "visibility$annotations", "getVisibility", "()Lkotlin/reflect/KVisibility;", "equals", "other", "error", "", "hashCode", "", "isInstance", "value", "toString", "kotlin-stdlib"} ) public final class ClassReference implements KClass<Object>, ClassBasedDeclarationContainer { @NotNull private final Class<?> jClass; @Nullable public String getSimpleName() { this.error(); throw null; } @Nullable public String getQualifiedName() { this.error(); throw null; } @NotNull public Collection<KCallable<?>> getMembers() { this.error(); throw null; } @NotNull public Collection<KFunction<Object>> getConstructors() { this.error(); throw null; } @NotNull public Collection<KClass<?>> getNestedClasses() { this.error(); throw null; } @NotNull public List<Annotation> getAnnotations() { this.error(); throw null; } @Nullable public Object getObjectInstance() { this.error(); throw null; } @SinceKotlin( version = "1.1" ) public boolean isInstance(@Nullable Object value) { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void typeParameters$annotations() { } @NotNull public List<KTypeParameter> getTypeParameters() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void supertypes$annotations() { } @NotNull public List<KType> getSupertypes() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.3" ) public static void sealedSubclasses$annotations() { } @NotNull public List<KClass<? extends Object>> getSealedSubclasses() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void visibility$annotations() { } @Nullable public KVisibility getVisibility() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void isFinal$annotations() { } public boolean isFinal() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void isOpen$annotations() { } public boolean isOpen() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void isAbstract$annotations() { } public boolean isAbstract() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void isSealed$annotations() { } public boolean isSealed() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void isData$annotations() { } public boolean isData() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void isInner$annotations() { } public boolean isInner() { this.error(); throw null; } /** @deprecated */ // $FF: synthetic method @SinceKotlin( version = "1.1" ) public static void isCompanion$annotations() { } public boolean isCompanion() { this.error(); throw null; } private final Void error() { throw (Throwable)(new KotlinReflectionNotSupportedError()); } public boolean equals(@Nullable Object other) { return other instanceof ClassReference && Intrinsics.areEqual((Object)JvmClassMappingKt.getJavaObjectType(this), (Object)JvmClassMappingKt.getJavaObjectType((KClass)other)); } public int hashCode() { return JvmClassMappingKt.getJavaObjectType(this).hashCode(); } @NotNull public String toString() { return this.getJClass().toString() + " (Kotlin reflection is not available)"; } @NotNull public Class<?> getJClass() { return this.jClass; } public ClassReference(@NotNull Class<?> jClass) { Intrinsics.checkParameterIsNotNull(jClass, "jClass"); super(); this.jClass = jClass; } }
package generator.model; public enum Nature { PROFESSIONAL_EXPERIENCE, EDUCATION, PROJECT, OTHER; }
/** * @author effine * @Date 2015年11月12日 下午11:13:31 * @email iballader#gmail.com * @site http://www.effine.cn */ package cn.effine.model; import java.io.Serializable; public class SigninHistory implements Serializable { private static final long serialVersionUID = 1L; private int id; private int uid; private String ip; private String signinTime; private int client; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getSigninTime() { return signinTime; } public void setSigninTime(String signinTime) { this.signinTime = signinTime; } public int getClient() { return client; } public void setClient(int client) { this.client = client; } }
/* * MIT License * * Copyright (c) 2017 Jan Heinrich Reimer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.heinrichreimersoftware.singleinputform.widgets; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.util.AttributeSet; public class CheckBoxCompat extends AppCompatCheckBox { public CheckBoxCompat(Context context) { super(context); } public CheckBoxCompat(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public CheckBoxCompat(Context context, AttributeSet attrs) { super(context, attrs); } @Override public int getCompoundPaddingLeft() { // Workarround for version codes < Jelly bean 4.2 // The system does not apply the same padding. Explantion: // http://stackoverflow.com/questions/4037795/android-spacing-between-checkbox-and-text/4038195#4038195 final float scale = this.getResources().getDisplayMetrics().density; return (super.getCompoundPaddingLeft() + (int) (10.0f * scale + 0.5f)); } }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.servlet; import java.io.IOException; /** * Defines an object that receives requests from the client * and sends them to any resource (such as a servlet, * HTML file, or JSP file) on the server. The servlet * container creates the <code>RequestDispatcher</code> object, * which is used as a wrapper around a server resource located * at a particular path or given by a particular name. * * <p>This interface is intended to wrap servlets, * but a servlet container can create <code>RequestDispatcher</code> * objects to wrap any type of resource. * * @author Various * * @see ServletContext#getRequestDispatcher(java.lang.String) * @see ServletContext#getNamedDispatcher(java.lang.String) * @see ServletRequest#getRequestDispatcher(java.lang.String) */ public interface RequestDispatcher { /** * The name of the request attribute under which the original * request URI is made available to the target of a * {@link #forward(ServletRequest,ServletResponse) forward} */ static final String FORWARD_REQUEST_URI = "javax.servlet.forward.request_uri"; /** * The name of the request attribute under which the original * context path is made available to the target of a * {@link #forward(ServletRequest,ServletResponse) forward} */ static final String FORWARD_CONTEXT_PATH = "javax.servlet.forward.context_path"; /** * The name of the request attribute under which the original * path info is made available to the target of a * {@link #forward(ServletRequest,ServletResponse) forward} */ static final String FORWARD_PATH_INFO = "javax.servlet.forward.path_info"; /** * The name of the request attribute under which the original * servlet path is made available to the target of a * {@link #forward(ServletRequest,ServletResponse) forward} */ static final String FORWARD_SERVLET_PATH = "javax.servlet.forward.servlet_path"; /** * The name of the request attribute under which the original * query string is made available to the target of a * {@link #forward(ServletRequest,ServletResponse) forward} */ static final String FORWARD_QUERY_STRING = "javax.servlet.forward.query_string"; /** * The name of the request attribute under which the request URI * of the target of an {@link #include(ServletRequest,ServletResponse) * include} is stored */ static final String INCLUDE_REQUEST_URI = "javax.servlet.include.request_uri"; /** * The name of the request attribute under which the context path * of the target of an {@link #include(ServletRequest,ServletResponse) * include} is stored */ static final String INCLUDE_CONTEXT_PATH = "javax.servlet.include.context_path"; /** * The name of the request attribute under which the path info * of the target of an {@link #include(ServletRequest,ServletResponse) * include} is stored */ static final String INCLUDE_PATH_INFO = "javax.servlet.include.path_info"; /** * The name of the request attribute under which the servlet path * of the target of an {@link #include(ServletRequest,ServletResponse) * include} is stored */ static final String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path"; /** * The name of the request attribute under which the query string * of the target of an {@link #include(ServletRequest,ServletResponse) * include} is stored */ static final String INCLUDE_QUERY_STRING = "javax.servlet.include.query_string"; /** * The name of the request attribute under which the exception object * is propagated during an error dispatch */ public static final String ERROR_EXCEPTION = "javax.servlet.error.exception"; /** * The name of the request attribute under which the type of the * exception object is propagated during an error dispatch */ public static final String ERROR_EXCEPTION_TYPE = "javax.servlet.error.exception_type"; /** * The name of the request attribute under which the exception message * is propagated during an error dispatch */ public static final String ERROR_MESSAGE = "javax.servlet.error.message"; /** * The name of the request attribute under which the request URI * whose processing caused the error is propagated during an error * dispatch */ public static final String ERROR_REQUEST_URI = "javax.servlet.error.request_uri"; /** * The name of the request attribute under which the name of the servlet * in which the error occurred is propagated during an error dispatch */ public static final String ERROR_SERVLET_NAME = "javax.servlet.error.servlet_name"; /** * The name of the request attribute under which the response status * is propagated during an error dispatch */ public static final String ERROR_STATUS_CODE = "javax.servlet.error.status_code"; /** * Forwards a request from * a servlet to another resource (servlet, JSP file, or * HTML file) on the server. This method allows * one servlet to do preliminary processing of * a request and another resource to generate * the response. * * <p>For a <code>RequestDispatcher</code> obtained via * <code>getRequestDispatcher()</code>, the <code>ServletRequest</code> * object has its path elements and parameters adjusted to match * the path of the target resource. * * <p><code>forward</code> should be called before the response has been * committed to the client (before response body output has been flushed). * If the response already has been committed, this method throws * an <code>IllegalStateException</code>. * Uncommitted output in the response buffer is automatically cleared * before the forward. * * <p>The request and response parameters must be either the same * objects as were passed to the calling servlet's service method or be * subclasses of the {@link ServletRequestWrapper} or * {@link ServletResponseWrapper} classes * that wrap them. * * <p>This method sets the dispatcher type of the given request to * <code>DispatcherType.FORWARD</code>. * * @param request a {@link ServletRequest} object that represents the * request the client makes of the servlet * * @param response a {@link ServletResponse} object that represents * the response the servlet returns to the client * * @throws ServletException if the target resource throws this exception * * @throws IOException if the target resource throws this exception * * @throws IllegalStateException if the response was already committed * * @see ServletRequest#getDispatcherType */ public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException; /** * * Includes the content of a resource (servlet, JSP page, * HTML file) in the response. In essence, this method enables * programmatic server-side includes. * * <p>The {@link ServletResponse} object has its path elements * and parameters remain unchanged from the caller's. The included * servlet cannot change the response status code or set headers; * any attempt to make a change is ignored. * * <p>The request and response parameters must be either the same * objects as were passed to the calling servlet's service method or be * subclasses of the {@link ServletRequestWrapper} or * {@link ServletResponseWrapper} classes that wrap them. * * <p>This method sets the dispatcher type of the given request to * <code>DispatcherType.INCLUDE</code>. * * @param request a {@link ServletRequest} object that contains the * client's request * * @param response a {@link ServletResponse} object that contains the * servlet's response * * @throws ServletException if the included resource throws this * exception * * @throws IOException if the included resource throws this exception * * @see ServletRequest#getDispatcherType */ public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException; }
/* * Copyright 2011-2018 Bas Leijdekkers * * 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.siyeh.ig.bugs; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.siyeh.HardcodedMethodConstants; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.PsiReplacementUtil; import com.siyeh.ig.psiutils.CommentTracker; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class ArrayHashCodeInspection extends BaseInspection { @Nls @NotNull @Override public String getDisplayName() { return InspectionGadgetsBundle.message("array.hash.code.display.name"); } @NotNull @Override protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "array.hash.code.problem.descriptor"); } @Override public boolean isEnabledByDefault() { return true; } @Override protected InspectionGadgetsFix buildFix(Object... infos) { final PsiArrayType type = (PsiArrayType)infos[0]; if (type.getComponentType() instanceof PsiArrayType) { return new ArrayHashCodeFix(true); } return new ArrayHashCodeFix(false); } private static class ArrayHashCodeFix extends InspectionGadgetsFix { private final boolean deepHashCode; public ArrayHashCodeFix(boolean deepHashCode) { this.deepHashCode = deepHashCode; } @Override @NotNull public String getName() { if (deepHashCode) { return InspectionGadgetsBundle.message( "arrays.deep.hash.code.quickfix"); } else { return InspectionGadgetsBundle.message( "arrays.hash.code.quickfix"); } } @NotNull @Override public String getFamilyName() { return "Replace with implicit 'hashCode'"; } @Override protected void doFix(Project project, ProblemDescriptor descriptor){ final PsiElement element = descriptor.getPsiElement(); final PsiElement parent = element.getParent(); final PsiElement grandParent = parent.getParent(); if (!(grandParent instanceof PsiMethodCallExpression)) { return; } final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier == null) { return; } @NonNls final StringBuilder newExpressionText = new StringBuilder(); if (deepHashCode) { newExpressionText.append("java.util.Arrays.deepHashCode("); } else { newExpressionText.append("java.util.Arrays.hashCode("); } CommentTracker commentTracker = new CommentTracker(); newExpressionText.append(commentTracker.text(qualifier)); newExpressionText.append(')'); PsiReplacementUtil.replaceExpressionAndShorten(methodCallExpression, newExpressionText.toString(), commentTracker); } } @Override public BaseInspectionVisitor buildVisitor() { return new ArrayHashCodeVisitor(); } private static class ArrayHashCodeVisitor extends BaseInspectionVisitor { @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final String methodName = methodExpression.getReferenceName(); if (!HardcodedMethodConstants.HASH_CODE.equals(methodName)) return; final PsiExpressionList argumentList = expression.getArgumentList(); if (!argumentList.isEmpty()) return; final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier == null) return; final PsiType type = qualifier.getType(); if (!(type instanceof PsiArrayType)) return; registerMethodCallError(expression, type); } } }
package com.univocity.cardano.wallet.builders.server; import com.univocity.cardano.wallet.common.x509.*; import com.univocity.cardano.wallet.embedded.services.*; import org.apache.commons.lang3.*; import org.slf4j.*; import java.util.*; public class EmbeddedWalletServer extends RemoteWalletServer { private static final Logger log = LoggerFactory.getLogger(EmbeddedWalletServer.class); private final CardanoNodeManager nodeManager; private final CardanoWalletManager walletManager; private int walletPort; private int nodePort; public EmbeddedWalletServer(WalletServer.WalletServerConfig config) { super(config); String networkParam = "--mainnet"; String cardanoTools = config.cardanoToolsDir.getAbsolutePath(); this.nodePort = config.nodePort; this.walletPort = config.walletPort; if (config.buildTemporaryBlockchain) { TemporaryBlockchainHelper tmp = new TemporaryBlockchainHelper(cardanoTools); nodeManager = tmp.createTemporaryShelleyNetwork(config.testnetMagic, config.nodePort, config.nodeOutputConsumer); networkParam = "--testnet " + tmp.getGenesisFile().getAbsolutePath(); } else { String blockchainPath = config.blockchainDir.getAbsolutePath(); String socketPath = config.blockchainDir.toPath().resolve("node.socket").toFile().getAbsolutePath(); if (SystemUtils.IS_OS_WINDOWS) { socketPath = "\\\\.\\pipe\\" + UUID.randomUUID().toString(); } nodeManager = new CardanoNodeManager(cardanoTools, config.nodeOutputConsumer); nodeManager.setStartupCommand( "run" + " --topology " + config.nodeTopologyFile.getAbsolutePath() + " --database-path " + blockchainPath + " --socket-path " + socketPath + " --host-addr 0.0.0.0" + " --port " + config.nodePort + " --config " + config.nodeConfigurationFile); } walletManager = new CardanoWalletManager(cardanoTools, config.walletOutputConsumer); String command = "serve " + networkParam + " --sync-tolerance 300s" + " --database " + nodeManager.getBlockchainDirPath() + " --node-socket " + nodeManager.getSocketPath() + " --port " + config.walletPort; if (config.enableHttps) { CertificateGenerator generator = CertificateGenerator.getInstance(); generator.generate(); command = command + " --tls-ca-cert " + generator.getRootCACertificatePath() + " --tls-sv-cert " + generator.getServerCertificatePath() + " --tls-sv-key " + generator.getServerKeyPath(); } walletManager.setStartupCommand(command); } public int getWalletPort() { return walletPort; } public int getNodePort() { return nodePort; } public CardanoNodeManager getNodeManager() { return nodeManager; } public CardanoWalletManager getWalletManager() { return walletManager; } public void start() { nodeManager.startProcess(); walletManager.startProcess(); } public void stop() { try { walletManager.stopProcess(); } finally { nodeManager.stopProcess(); } } public void waitForServerToStop() { try { nodeManager.waitForProcess(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
package com.liuzhihang.doc.view.service; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiMethod; import com.liuzhihang.doc.view.config.Settings; import com.liuzhihang.doc.view.dto.DocView; import com.liuzhihang.doc.view.service.impl.DubboDocViewServiceImpl; import com.liuzhihang.doc.view.service.impl.SpringDocViewServiceImpl; import com.liuzhihang.doc.view.utils.CustomPsiUtils; import com.liuzhihang.doc.view.utils.DubboPsiUtils; import com.liuzhihang.doc.view.utils.FeignPsiUtil; import com.liuzhihang.doc.view.utils.SpringPsiUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.LinkedList; import java.util.List; /** * @author liuzhihang * @date 2020/3/3 13:32 */ public interface DocViewService { @Nullable static DocViewService getInstance(@NotNull Project project, @NotNull PsiClass targetClass) { Settings settings = Settings.getInstance(project); //spring cloud 的 feign client if (FeignPsiUtil.isFeignClass(targetClass)) { return ServiceManager.getService(SpringDocViewServiceImpl.class); } // Dubbo if (DubboPsiUtils.isDubboClass(targetClass)) { return ServiceManager.getService(DubboDocViewServiceImpl.class); } // Spring if (SpringPsiUtils.isSpringClass(targetClass)) { return ServiceManager.getService(SpringDocViewServiceImpl.class); } return null; } @Nullable default List<DocView> buildDoc(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull Editor editor, @NotNull PsiClass targetClass) { // 当前方法 PsiMethod targetMethod = CustomPsiUtils.getTargetMethod(editor, psiFile); if (targetMethod != null && checkMethod(project, targetMethod)) { DocView docView = buildClassMethodDoc(project, targetClass, targetMethod); List<DocView> docViewList = new LinkedList<>(); docViewList.add(docView); return docViewList; } // 每个方法都要生成 if (targetMethod == null) { // 生成文档列表 return buildClassDoc(project, targetClass); } return null; } boolean checkMethod(@NotNull Project project, @NotNull PsiMethod targetMethod); List<DocView> buildClassDoc(Project project, @NotNull PsiClass psiClass); @NotNull DocView buildClassMethodDoc(Project project, PsiClass psiClass, @NotNull PsiMethod psiMethod); }
/* * 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.lealone.plugins.test.netty; import org.lealone.plugins.netty.NettyNetFactory; import org.lealone.plugins.test.NetTestBase; public class NettyNetClientTest extends NetTestBase { public NettyNetClientTest() { super(NettyNetFactory.NAME); } }
/* * 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.polygene.library.sql.generator.implementation.grammar.common.datatypes; import org.apache.polygene.library.sql.generator.grammar.common.datatypes.SQLDataType; import org.apache.polygene.library.sql.generator.grammar.common.datatypes.SQLTimeStamp; import org.apache.polygene.library.sql.generator.implementation.TypeableImpl; /** * This class represents {@code TIMESTAMP} data type. * * @author Stanislav Muhametsin */ public final class SQLTimeStampImpl extends TypeableImpl<SQLDataType, SQLTimeStamp> implements SQLTimeStamp { private final Integer _precision; private final Boolean _withTimeZone; public SQLTimeStampImpl( Integer precision, Boolean withTimeZone ) { super( SQLTimeStamp.class ); this._precision = precision; this._withTimeZone = withTimeZone; } @Override protected boolean doesEqual( SQLTimeStamp another ) { return bothNullOrEquals( this._precision, another.getPrecision() ) && bothNullOrEquals( this._withTimeZone, another.isWithTimeZone() ); } /** * Returns the precision for this {@code TIMESTAMP}. May be {@code null}. * * @return The precision for this {@code TIMESTAMP}. */ public Integer getPrecision() { return this._precision; } /** * Returns whether the {@code TIMESTAMP} should be with time zone. May be {@code null} if no choice specified. */ public Boolean isWithTimeZone() { return this._withTimeZone; } public static final SQLTimeStamp PLAIN_TIMESTAMP = new SQLTimeStampImpl( null, null ); public static final SQLTimeStamp PLAIN_TIMESTAMP_WITHOUT_TZ = new SQLTimeStampImpl( null, false ); public static final SQLTimeStamp PLAIN_TIMESTAMP_WITH_TZ = new SQLTimeStampImpl( null, true ); }
package old.echoerAndIM; import util.session.PeerMessageListener; public class AnInCoupler implements PeerMessageListener{ Echoer echoer; public AnInCoupler(Echoer theEchoer) { echoer = theEchoer; } public void objectReceived(Object message, String userName) { if (message instanceof ARemoteInput) processRemoteInput((ARemoteInput) message, userName); } void processRemoteInput (ARemoteInput remoteInput, String userName) { System.out.println("Remote Input:" + remoteInput.getData() + " from:" + userName); echoer.addToHistory(remoteInput.getData()); } }
package org.firstinspires.ftc.teamcode.Hardware; import com.qualcomm.robotcore.hardware.Servo; public class FoundationArms { public Servo foundationArmL; public Servo foundationArmR; public FoundationArms(Servo left, Servo right) { left.setDirection(Servo.Direction.REVERSE); right.setDirection(Servo.Direction.FORWARD); left.setPosition(0); right.setPosition(0); foundationArmL = left; foundationArmR = right; } public void down() { foundationArmL.setPosition(1); foundationArmR.setPosition(1); } public void up() { foundationArmL.setPosition(0); foundationArmR.setPosition(0); } }
/* * Copyright (c) 2019- 2019 threefish(https://gitee.com/threefish https://github.com/threefish) All Rights Reserved. * 本项目完全开源,商用完全免费。但请勿侵犯作者合法权益,如申请软著等。 * 最后修改时间:2019/10/07 18:27:07 * 源 码 地 址:https://gitee.com/threefish/NutzFw */ package com.nutzfw.modules.organize.entity; import com.nutzfw.core.common.entity.BaseEntity; import lombok.*; import org.nutz.dao.entity.annotation.*; /** * Created with IntelliJ IDEA. * * @author 黄川 huchuc@vip.qq.com * @date 2018/2/6 18:10 * 描述此类:系统用户角色关联 */ @Table("sys_user_account_role") @PK({"roleId", "userId"}) @TableIndexes(@Index(fields = {"roleId", "userId"}, name = "pks")) @Comment("用户角色关联信息") @Data @AllArgsConstructor @NoArgsConstructor @Builder @EqualsAndHashCode(callSuper = false) public class UserAccountRole extends BaseEntity { @Column("role_id") @ColDefine(width = 32, notNull = true) private String roleId; @Column("user_id") @ColDefine(width = 32, notNull = true) private String userId; }
package dbcache.cache.common; import dbcache.DbCacheService; import dbcache.cache.CacheUnit; import dbcache.cache.ValueWrapper; import dbcache.cache.impl.ConcurrentLruHashMapCache; import utils.collections.concurrent.ConcurrentHashMapV8; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 通用缓存类 * @param <R> 缓存内容类型 */ public class CommonCache<R> { /** * 默认共享缓存 */ private static final CacheUnit shareCacheUnit = new ConcurrentLruHashMapCache() {{ this.init("DEFAULT_COMMON_CACHE", 10000, Runtime.getRuntime().availableProcessors()); }}; /** * 缓存名称 */ private String name; /** * 等待锁map {key:lock} */ private final ConcurrentMap<Object, Lock> WAITING_LOCK_MAP = new ConcurrentHashMapV8<Object, Lock>(); /** * 缓存单元 */ private CacheUnit cacheUnit; /** * DbCacheService */ private DbCacheService dbCacheService; /** * 缓存查询器 */ private CacheLoader<R> cacheQuery; protected CommonCache() { } public CommonCache(CacheLoader<R> cacheQuery) { this.cacheQuery = cacheQuery; } public R get(Object... key) { String cachedKey = buildCacheKey(key); ValueWrapper cacheWrapper = getCacheUnit().get(cachedKey); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } if (this.cacheQuery == null) { return null; } Lock lock = new ReentrantLock(); Lock prevLock = WAITING_LOCK_MAP.putIfAbsent(cachedKey, lock); lock = prevLock != null ? prevLock : lock; lock.lock(); try { cacheWrapper = getCacheUnit().get(cachedKey); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } R value = this.cacheQuery.load(key); cacheWrapper = getCacheUnit().putIfAbsent(cachedKey, value); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } } finally { WAITING_LOCK_MAP.remove(cachedKey); lock.unlock(); } return null; } private String buildCacheKey(Object... key) { StringBuilder keyBuilder = new StringBuilder(); for (Object key1 : key) { keyBuilder.append(key1).append("_"); } return keyBuilder.toString(); } public R put(Object key, Object value) { ValueWrapper cacheWrapper = getCacheUnit().put(buildCacheKey(key), value); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } return null; } public R put(Object[] key, Object value) { ValueWrapper cacheWrapper = getCacheUnit().put(buildCacheKey(key), value); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } return null; } public R putIfAbsent(Object key, Object value) { this.get(key); ValueWrapper cacheWrapper = getCacheUnit().putIfAbsent(buildCacheKey(key), value); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } return null; } public R putIfAbsent(Object[] key, Object value) { this.get(key); ValueWrapper cacheWrapper = getCacheUnit().putIfAbsent(buildCacheKey(key), value); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } return null; } public R replace(Object key, Object oldValue, Object newValue) { ValueWrapper cacheWrapper = getCacheUnit().replace(buildCacheKey(key), oldValue, newValue); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } return null; } public R replace(Object[] key, Object oldValue, Object newValue) { ValueWrapper cacheWrapper = getCacheUnit().replace(buildCacheKey(key), oldValue, newValue); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } return null; } public R evict(Object... key) { ValueWrapper cacheWrapper = getCacheUnit().evict(buildCacheKey(key)); if(cacheWrapper != null) { return (R) cacheWrapper.get(); } return null; } public void clear() { getCacheUnit().clear(); } public CacheUnit getCacheUnit() { if (this.cacheUnit != null) { return this.cacheUnit; } if (this.dbCacheService != null) { this.cacheUnit = this.dbCacheService.getCacheUnit(); return this.cacheUnit; } this.cacheUnit = shareCacheUnit; return this.cacheUnit; } public void setCacheUnit(CacheUnit cacheUnit) { this.cacheUnit = cacheUnit; } public void setDbCacheService(DbCacheService dbCacheService) { this.dbCacheService = dbCacheService; } public String getName() { return name == null ? cacheUnit.getName() : name; } public void setName(String name) { this.name = name; } }
package org.fl.util.file ; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class FileConcatener { private Logger fcLog ; private long chunkSize ; public FileConcatener(Logger l) { super(); fcLog = l ; chunkSize = 96000 ; } public FileConcatener(long cs, Logger l) { super(); fcLog = l ; if (cs == 0) { chunkSize = 96000 ; } else { chunkSize = cs ; } } // Files concatenation using direct channel to channel copy public boolean concatenateFiles(Path destinationPath, ArrayList<Path> originPaths) { boolean success = true ; long tb = System.currentTimeMillis() ; File destinationFile = destinationPath.toFile() ; ArrayList<File> originFiles = new ArrayList<File>(); // Create File object and compute expected lengths long expectedLength = destinationFile.length() ; for (Path originPath : originPaths) { File origin = originPath.toFile(); expectedLength = expectedLength + origin.length() ; originFiles.add(origin) ; } try (FileChannel out = new FileOutputStream(destinationFile, true).getChannel()) { for (File originFile : originFiles) { try (FileChannel in = new FileInputStream(originFile).getChannel()) { long totalSizeToAppend = in.size() ; long sizeToAppend = totalSizeToAppend ; while (sizeToAppend > 0) { // apparently there is a limitation in the number of bytes that can be written at a time // around 2 GB at least on Windows with JVM 1.7 // So it must be done in a loop long xferedLength ; if (sizeToAppend > chunkSize) { xferedLength = in.transferTo (totalSizeToAppend-sizeToAppend, chunkSize, out); } else { xferedLength = in.transferTo (totalSizeToAppend-sizeToAppend, sizeToAppend, out); } sizeToAppend = sizeToAppend - xferedLength ; } } catch (Exception e1) { success = false ; fcLog.log(Level.SEVERE, "Exception during file concatenation: ", e1) ; } } } catch (Exception e) { success = false ; fcLog.log(Level.SEVERE, "Exception during file concatenation: ", e) ; } if (destinationFile.length() != expectedLength) { StringBuffer buff = new StringBuffer() ; buff.append("Wrong size for concatenation to ").append(destinationPath) ; buff.append("\nof files: \n") ; for (Path originPath : originPaths) { buff.append(originPath).append('\n') ; } success = false ; fcLog.severe(buff.toString()) ; } else { // remove the source files for (Path sourceFile : originPaths) { try { boolean hasBeenDeleted = Files.deleteIfExists(sourceFile) ; if (! hasBeenDeleted) { success = false ; fcLog.severe("A file could not be deleted: " + sourceFile) ; } } catch (IOException e) { success = false ; fcLog.log(Level.SEVERE, "Exception during file delete for file " + sourceFile, e) ; } } } fcLog.fine(() -> { long d = System.currentTimeMillis() - tb ; return "Concatenation duration for a file packet " + + d;}) ; return success ; } }
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kkkj.android.revgoods.http; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import okhttp3.MediaType; import okhttp3.ResponseBody; import retrofit2.Converter; import static kkkj.android.revgoods.mvpInterface.MvpModel.RESPONSE_OK; import static okhttp3.internal.Util.UTF_8; final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> { private final Gson gson; private final TypeAdapter<T> adapter; GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) { this.gson = gson; this.adapter = adapter; } @Override public T convert(ResponseBody value) throws IOException { String response = value.string(); Reader reader = null; JsonReader jsonReader= null; InputStream inputStream = null; try { //ResultResponse 只解析result字段 RevGResponse resultResponse = gson.fromJson(response, RevGResponse.class); if (resultResponse.getState() == RESPONSE_OK) { //result==0表示成功返回,继续用本来的Model类解析 MediaType contentType = value.contentType(); Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8; inputStream = new ByteArrayInputStream(response.getBytes()); reader = new InputStreamReader(inputStream, charset); jsonReader = gson.newJsonReader(reader); return adapter.read(jsonReader); } else { //ErrResponse 将msg解析为异常消息文本 throw new ResultException(resultResponse.getState(), resultResponse.getMsg()); } } finally { value.close(); if(inputStream!=null) { inputStream.close(); } if(jsonReader!=null) { jsonReader.close(); } if(reader!=null) { reader.close(); } } } }
package com.lingchaomin.falcon.alarm.service.impl; import com.lingchaomin.falcon.alarm.logic.ISmsAndMailLogic; import com.lingchaomin.falcon.alarm.service.IAlarmService; import com.lingchaomin.falcon.common.api.IActionDubboApi; import com.lingchaomin.falcon.common.entity.Action; import com.lingchaomin.falcon.common.entity.Event; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author minlingchao * @version 1.0 * @date 2017/4/10 下午3:27 * @description 告警事件处理 */ @Service public class AlarmService implements IAlarmService { @Autowired private IActionDubboApi actionDubboApi; @Autowired private ISmsAndMailLogic smsAndMailLogic; /** * 事件消费 */ public void consumeEvent(Event event, Boolean isHighPrority) { if(event.getActionId()<=0){ return; } Action action=actionDubboApi.getActionById(event.getActionId()); if(action==null){ return; } if(action.getCallback()){ handleCallback(event,action); return; } if(isHighPrority){ consumeHighEvents(event,action); }else { consumerLowEvents(event,action); } } /** * 处理低等级事件 * @param event * @param action */ private void consumerLowEvents(Event event, Action action) { if(StringUtils.isBlank(action.getUic())){ return; } if(event.getPriority()<3){ smsAndMailLogic.createUserSms(event,action); } smsAndMailLogic.createUserMail(event,action); } /** * 处理高等级事件 高优先级的不做报警合并 * @param event * @param action */ private void consumeHighEvents(Event event, Action action) { if(StringUtils.isBlank(action.getUic())){ return; } String[] uicArr=action.getUic().split("|"); String smsContent=smsAndMailLogic.generateSmsContent(event); String mailContent=smsAndMailLogic.generateMailContent(event); if(event.getPriority()<3){ smsAndMailLogic.createSms(uicArr[0],smsContent); } smsAndMailLogic.createMail(uicArr[1],smsContent,mailContent); } /** * 处理回调事件 * @param event * @param action */ private void handleCallback(Event event,Action action){ String uic=action.getUic(); String phones=StringUtils.EMPTY; String emails=StringUtils.EMPTY; if(StringUtils.isNoneBlank(uic)){ phones=uic.split("|")[0]; emails=uic.split("|")[1]; } String smsContent=smsAndMailLogic.generateSmsContent(event); String emailContent=smsAndMailLogic.generateSmsContent(event); if(action.getBeforeCallbackSms()){ String content=smsAndMailLogic.generateSmsContent(event); smsAndMailLogic.createSms(phones,smsContent); } if(action.getBeforeCallbackMail()){ String content=smsAndMailLogic.generateMailContent(event); smsAndMailLogic.createMail(emails,smsContent,emailContent); } String message=callback(event,action); if(action.getAfterCallbackSms()){ smsAndMailLogic.createSms(phones,message); } if(action.getAfterCallbackmail()){ smsAndMailLogic.createMail(emails,message,message); } } private String callback(Event event,Action action){ if(StringUtils.isBlank(action.getUrl())){ return "call back url is null"; } List<Map<String,String>> tags=new ArrayList<Map<String, String>>(); //转换标签 if(StringUtils.isNoneBlank(event.getPushedTags())){ String[] tagsArr=event.getPushedTags().split(","); for(String s:tagsArr){ Map<String,String> map=new HashMap<String, String>(); map.put(s.split("=")[0],s.split("=")[1]); tags.add(map); } } String tagsStr=StringUtils.join(tags,","); //todo 回调函数地址处理 // NameValuePair[] nameValuePairs=new NameValuePair[]{ // new NameValuePair("endpoint",event.getEndPoint()), // new NameValuePair("metric",event.getMetric()), // // } return null; } }
package module552packageJava0; import java.lang.Integer; public class Foo68 { Integer int0; Integer int1; public void foo0() { new module552packageJava0.Foo67().foo5(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } }
/** * 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.batch.protocol.models; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Defines values for JobState. */ public enum JobState { /** The job is available to have tasks scheduled. */ ACTIVE("active"), /** A user has requested that the job be disabled, but the disable operation is still in progress (for example, waiting for tasks to terminate). */ DISABLING("disabling"), /** A user has disabled the job. No tasks are running, and no new tasks will be scheduled. */ DISABLED("disabled"), /** A user has requested that the job be enabled, but the enable operation is still in progress. */ ENABLING("enabling"), /** The job is about to complete, either because a Job Manager task has completed or because the user has terminated the job, but the terminate operation is still in progress (for example, because Job Release tasks are running). */ TERMINATING("terminating"), /** All tasks have terminated, and the system will not accept any more tasks or any further changes to the job. */ COMPLETED("completed"), /** A user has requested that the job be deleted, but the delete operation is still in progress (for example, because the system is still terminating running tasks). */ DELETING("deleting"); /** The actual serialized value for a JobState instance. */ private String value; JobState(String value) { this.value = value; } /** * Parses a serialized value to a JobState instance. * * @param value the serialized value to parse. * @return the parsed JobState object, or null if unable to parse. */ @JsonCreator public static JobState fromString(String value) { JobState[] items = JobState.values(); for (JobState item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return null; } @JsonValue @Override public String toString() { return this.value; } }
package com.didi.service.impl; import com.didi.bo.UserBo; import com.didi.dao.UserDao; import com.didi.entity.User; import com.didi.enums.Gender; import com.didi.enums.IDUTIL; import com.didi.service.UserService; import com.didi.util.OrderIdGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.UUID; /** * @author thought。 * @create 2017-05-02 上午11:41 **/ @Service public class UserServiceImpl implements UserService { private Log LOG = LogFactory.getLog(this.getClass()); @Autowired private UserDao userDao; public User addNewUser(UserBo userbo) { User user = new User(); String UserId = OrderIdGenerator.getInstance().genOrderId(IDUTIL.USER); user.setId(UUID.randomUUID().toString()); user.setAddres(userbo.getAddress()); user.setAge(Integer.parseInt(userbo.getAge())); if(Gender.BOY.getValue().equals(userbo.getGender())){ user.setGender(Gender.BOY.getKey()); }else if(Gender.GIRL.getValue().equals(userbo.getGender())){ user.setGender(Gender.GIRL.getKey()); } user.setLoginName(userbo.getLoginName()); user.setName(userbo.getUserName()); user.setPhone(userbo.getPhone()); user.setUserId(UserId); user.setPassword(userbo.getPassword()); userDao.insertSelective(user); return user; } public User findUserByName(String loginName) { User user = userDao.findUserByName(loginName); return user; } public User findUserByUserId(String userId) { User user = userDao.findUserByUserId(userId); return user; } }
/* * Copyright 2019-2021 Bunjlabs * * 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 fuga.app.support; import fuga.app.ConfigurableApplicationContext; import fuga.app.events.ApplicationClosedEvent; import fuga.app.events.ApplicationInitializedEvent; import fuga.app.events.ApplicationStartedEvent; import fuga.app.events.ApplicationStoppedEvent; import fuga.event.EventBus; import fuga.util.ObjectUtils; import java.util.concurrent.atomic.AtomicBoolean; abstract class AbstractApplicationContext implements ConfigurableApplicationContext { private final Object shutdownMonitor = new Object(); private final AtomicBoolean active = new AtomicBoolean(false); private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicBoolean closed = new AtomicBoolean(false); private final EventBus eventBus; private final String id = ObjectUtils.getIdentityHexString(this); private final String applicationName = id; private long startupTime = 0; private Thread shutdownHook; AbstractApplicationContext(EventBus eventBus) { this.eventBus = eventBus; } @Override public String getId() { return id; } @Override public String getApplicationName() { return applicationName; } @Override public long getStartupTime() { return startupTime; } @Override public void init() { startupTime = System.currentTimeMillis(); registerShutdownHook(); active.set(true); eventBus.post(new ApplicationInitializedEvent(this)); } private void registerShutdownHook() { if (shutdownHook == null) { shutdownHook = new Thread(() -> { synchronized (shutdownMonitor) { doClose(); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); } } private void doClose() { stop(); if (active.get()) { eventBus.post(new ApplicationClosedEvent(this)); } } @Override public void start() { if (!started.compareAndExchange(false, true)) { eventBus.post(new ApplicationStartedEvent(this)); } } @Override public void stop() { if (started.compareAndExchange(true, false)) { eventBus.post(new ApplicationStoppedEvent(this)); } } @Override public void close() { synchronized (shutdownMonitor) { doClose(); if (shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException ex) { // ignore } } } } @Override public boolean isRunning() { return active.get() && started.get() && !closed.get(); } }
import java.util.Scanner; public class Division { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); double number1,number2; double quotient; System.out.println("Enter the first number:"); number1 = keyboard.nextDouble(); System.out.println("Enter the second number:"); number2 = keyboard.nextDouble(); if(number2 == 0) { System.out.println("It is not possible to divide a number by 0"); } else { quotient = (number1 / number2); System.out.println("The division of " + number1 + " to " + number2 + " is: " + quotient); } } }
package inside_payment.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.Date; import java.util.UUID; @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; //Which Account Bought it private UUID accountId; //Tickets bought for whom.... private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "shanghai"; to = "太原"; status = OrderStatus.PAID.getCode(); price = "0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price.equals(other.price); } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public UUID getAccountId() { return accountId; } public void setAccountId(UUID accountId) { this.accountId = accountId; } public Date getBoughtDate() { return boughtDate; } public void setBoughtDate(Date boughtDate) { this.boughtDate = boughtDate; } public Date getTravelDate() { return travelDate; } public void setTravelDate(Date travelDate) { this.travelDate = travelDate; } public void setTravelDate(int year,int month,int day){ Date date = new Date(year,month,day,0,0,0); this.travelDate = date; } public Date getTravelTime() { return travelTime; } public void setTravelTime(Date travelTime) { this.travelTime = travelTime; } public void setTravelTime(int hour,int minute){ Date date = new Date(1970,1,1,hour,minute,0); } public String getTrainNumber() { return trainNumber; } public void setTrainNumber(String trainNumber) { this.trainNumber = trainNumber; } public int getCoachNumber() { return coachNumber; } public void setCoachNumber(int coachNumber) { this.coachNumber = coachNumber; } public int getSeatClass() { return seatClass; } public void setSeatClass(int seatClass) { this.seatClass = seatClass; } public String getSeatNumber() { return seatNumber; } public void setSeatNumber(String seatNumber) { this.seatNumber = seatNumber; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getContactsName() { return contactsName; } public void setContactsName(String contactsName) { this.contactsName = contactsName; } public int getDocumentType() { return documentType; } public void setDocumentType(int documentType) { this.documentType = documentType; } public String getContactsDocumentNumber() { return contactsDocumentNumber; } public void setContactsDocumentNumber(String contactsDocumentNumber) { this.contactsDocumentNumber = contactsDocumentNumber; } }
package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class ThreadPerClient implements Runnable { private Socket socket = null; private Thread t3, t4; public ThreadPerClient(Socket s) { socket = s; } public void run() { try { while (true) { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); Calcul question = new Calcul(in.readLine()); double res = Calcul.solve(question); out.println(res); out.flush(); } } catch (IOException e) { System.err.println("La calculatrice cliente s'est déconnectée."); } } }
/* * 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.shardingsphere.infra.optimize.converter.segment.orderby.item; import org.apache.calcite.sql.SqlBasicCall; import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.shardingsphere.infra.optimize.converter.segment.SQLSegmentConverter; import org.apache.shardingsphere.infra.optimize.converter.segment.expression.impl.ColumnConverter; import org.apache.shardingsphere.sql.parser.sql.common.constant.OrderDirection; import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.order.item.ColumnOrderByItemSegment; import java.util.Objects; import java.util.Optional; /** * Column of order by item converter. */ public final class ColumnOrderByItemConverter implements SQLSegmentConverter<ColumnOrderByItemSegment, SqlNode> { @Override public Optional<SqlNode> convert(final ColumnOrderByItemSegment segment) { Optional<SqlNode> result = new ColumnConverter().convert(segment.getColumn()); if (result.isPresent() && Objects.equals(OrderDirection.DESC, segment.getOrderDirection())) { result = Optional.of(new SqlBasicCall(SqlStdOperatorTable.DESC, new SqlNode[] {result.get()}, SqlParserPos.ZERO)); } return result; } }
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package org.evosuite.runtime.sandbox; import java.io.FilePermission; import java.security.Permission; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; /** * <p> * PermissionStatistics class. * </p> * * * * <p> * FIXME: This class seem directly used by the SUT, when its methods check the * security manager. This can lead to concurrency issues when the SUT is * multi-threaded. Some re-factoring might be needed, but that would need some * discussions first regarding its use/goals * <p> * * * @author Gordon Fraser */ public class PermissionStatistics { private static PermissionStatistics instance = new PermissionStatistics(); private final Map<String, Map<String, Integer>> allowedCount; /** * Keep track of the denied exceptions. Key -> name of the permission class * Value -> a map from type (name+action) to counter of times it was thrown */ private final Map<String, Map<String, Integer>> deniedCount; private final Map<Class<?>, Integer> deniedClassCount; private final Set<String> recentAccess; private int maxThreads; private boolean hasNewExceptions = false; private String threadGroupToMonitor; // Private constructor private PermissionStatistics() { allowedCount = new ConcurrentHashMap<String, Map<String, Integer>>(); deniedCount = new ConcurrentHashMap<String, Map<String, Integer>>(); deniedClassCount = new ConcurrentHashMap<Class<?>, Integer>(); recentAccess = Collections.synchronizedSet(new HashSet<String>()); maxThreads = 1; } /** * <p> * Getter for the field <code>instance</code>. * </p> * * @return a {@link org.evosuite.runtime.sandbox.PermissionStatistics} object. */ public static PermissionStatistics getInstance() { return instance; } /** * <p> * getRecentFileReadPermissions * </p> * * @return an array of {@link java.lang.String} objects. */ public String[] getRecentFileReadPermissions() { return recentAccess.toArray(new String[0]); } /** * <p> * resetRecentStatistic * </p> */ public void resetRecentStatistic() { recentAccess.clear(); } private void rememberRecentReadFilePermissions(Permission permission) { try { FilePermission fp = (FilePermission) permission; if (!fp.getActions().equals("read")) return; recentAccess.add(fp.getName()); } catch (Exception e) { return; } } /** * <p> * permissionAllowed * </p> * * @param permission * a {@link java.security.Permission} object. */ public void permissionAllowed(Permission permission) { rememberRecentReadFilePermissions(permission); String name = permission.getClass().getName(); String type = getPermissionType(permission); if (!allowedCount.containsKey(name)) { allowedCount.put(name, new HashMap<String, Integer>()); } if (allowedCount.get(name).containsKey(type)) { allowedCount.get(name).put(type, allowedCount.get(name).get(type) + 1); } else { allowedCount.get(name).put(type, 1); } } private int getCurrentCount(Class<?> permissionClass) { if (!deniedClassCount.containsKey(permissionClass)) deniedClassCount.put(permissionClass, 0); return deniedClassCount.get(permissionClass); } private void incCurrentCount(Class<?> permissionClass) { deniedClassCount.put(permissionClass, getCurrentCount(permissionClass) + 1); } private String getPermissionType(Permission permission) { String name = permission.getName(); String actions = permission.getActions(); String type = ""; if (actions != null && !actions.isEmpty()) { type += actions + " "; } if (name != null && !name.isEmpty()) { type += name; } return type; } /** * <p> * permissionDenied * </p> * * @param permission * a {@link java.security.Permission} object. */ public void permissionDenied(Permission permission) { incCurrentCount(permission.getClass()); rememberRecentReadFilePermissions(permission); String permissionClassName = permission.getClass().getName(); String type = getPermissionType(permission); if (!deniedCount.containsKey(permissionClassName)) { deniedCount.put(permissionClassName, new HashMap<String, Integer>()); } if (deniedCount.get(permissionClassName).containsKey(type)) { deniedCount.get(permissionClassName).put(type, deniedCount.get(permissionClassName).get(type) + 1); } else { deniedCount.get(permissionClassName).put(type, 1); } hasNewExceptions = true; } /** * Retrieve the number of times a particular permission was denied * * @param permission * a {@link java.security.Permission} object. * @return a int. */ public int getPermissionDeniedCount(Permission permission) { String name = permission.getClass().getName(); String type = getPermissionType(permission); if (deniedCount.containsKey(name)) { if (deniedCount.get(name).containsKey(type)) { return deniedCount.get(name).get(type); } } return 0; } /** * <p> * getNumAllPermission * </p> * * @return a int. */ public int getNumAllPermission() { return getCurrentCount(java.security.AllPermission.class); } /** * <p> * getNumSecurityPermission * </p> * * @return a int. */ public int getNumSecurityPermission() { return getCurrentCount(java.security.SecurityPermission.class); } /** * <p> * getNumUnresolvedPermission * </p> * * @return a int. */ public int getNumUnresolvedPermission() { return getCurrentCount(java.security.UnresolvedPermission.class); } /** * <p> * getNumAWTPermission * </p> * * @return a int. */ public int getNumAWTPermission() { return getCurrentCount(java.awt.AWTPermission.class); } /** * <p> * getNumFilePermission * </p> * * @return a int. */ public int getNumFilePermission() { return getCurrentCount(java.io.FilePermission.class); } /** * <p> * getNumSerializablePermission * </p> * * @return a int. */ public int getNumSerializablePermission() { return getCurrentCount(java.io.SerializablePermission.class); } /** * <p> * getNumReflectPermission * </p> * * @return a int. */ public int getNumReflectPermission() { return getCurrentCount(java.lang.reflect.ReflectPermission.class); } /** * <p> * getNumRuntimePermission * </p> * * @return a int. */ public int getNumRuntimePermission() { return getCurrentCount(java.lang.RuntimePermission.class); } /** * <p> * getNumNetPermission * </p> * * @return a int. */ public int getNumNetPermission() { return getCurrentCount(java.net.NetPermission.class); } /** * <p> * getNumSocketPermission * </p> * * @return a int. */ public int getNumSocketPermission() { return getCurrentCount(java.net.SocketPermission.class); } /** * <p> * getNumSQLPermission * </p> * * @return a int. */ public int getNumSQLPermission() { return getCurrentCount(java.sql.SQLPermission.class); } /** * <p> * getNumPropertyPermission * </p> * * @return a int. */ public int getNumPropertyPermission() { return getCurrentCount(java.util.PropertyPermission.class); } /** * <p> * getNumLoggingPermission * </p> * * @return a int. */ public int getNumLoggingPermission() { return getCurrentCount(java.util.logging.LoggingPermission.class); } /** * <p> * getNumSSLPermission * </p> * * @return a int. */ public int getNumSSLPermission() { return getCurrentCount(javax.net.ssl.SSLPermission.class); } /** * <p> * getNumAuthPermission * </p> * * @return a int. */ public int getNumAuthPermission() { return getCurrentCount(javax.security.auth.AuthPermission.class) + getCurrentCount(javax.security.auth.PrivateCredentialPermission.class) + getCurrentCount(javax.security.auth.kerberos.DelegationPermission.class) + getCurrentCount(javax.security.auth.kerberos.ServicePermission.class); } /** * <p> * getNumAudioPermission * </p> * * @return a int. */ public int getNumAudioPermission() { return getCurrentCount(javax.sound.sampled.AudioPermission.class); } /** * <p> * getNumOtherPermission * </p> * * @return a int. */ public int getNumOtherPermission() { int sum = getNumAllPermission() + getNumSecurityPermission() + getNumUnresolvedPermission() + getNumAWTPermission() + getNumFilePermission() + getNumSerializablePermission() + getNumReflectPermission() + getNumRuntimePermission() + getNumNetPermission() + getNumSocketPermission() + getNumSQLPermission() + getNumPropertyPermission() + getNumLoggingPermission() + getNumSSLPermission() + getNumAuthPermission() + getNumAudioPermission(); int total = 0; for (int i : deniedClassCount.values()) total += i; return total - sum; } /** * <p> * hasDeniedPermissions * </p> * * @return a boolean. */ public boolean hasDeniedPermissions() { return !deniedCount.isEmpty(); } /** * <p> * printStatistics * </p> */ public void printStatistics(Logger inputLog) { forcePermissionInit(); if (hasDeniedPermissions()) { inputLog.info("* Permissions denied during test execution: "); for (String name : deniedCount.keySet()) { inputLog.info(" - " + name + ": "); /* * We don't want to print all the exceptions if they are too many */ final int MAX_TO_PRINT = 4; int counter = 0; int total = deniedCount.get(name).keySet().size(); boolean printAll = (total <= MAX_TO_PRINT); for (String type : deniedCount.get(name).keySet()) { inputLog.info(" " + type + ": " + deniedCount.get(name).get(type)); counter++; if (!printAll && counter >= (MAX_TO_PRINT - 1)) { break; } } int remaining = total - counter; if (remaining > 1) { inputLog.info(" and other " + remaining + " cases of action/name for this exception class"); } } } } /** * This is needed due to caching */ private void forcePermissionInit(){ getNumAllPermission(); getNumSecurityPermission(); getNumUnresolvedPermission(); getNumAWTPermission(); getNumFilePermission(); getNumSerializablePermission(); getNumReflectPermission(); getNumRuntimePermission(); getNumNetPermission(); getNumSocketPermission(); getNumSQLPermission(); getNumPropertyPermission(); getNumLoggingPermission(); getNumSSLPermission(); getNumAuthPermission(); getNumAudioPermission(); getNumOtherPermission(); getMaxThreads(); } /** * Check how many threads are active, and store the maximum value seen so * far. Note: this is used to check if the SUT is multi-threading, but it is * not a 100% bullet-proof solution, as this method is only called any now * and then. * * @param numThreads * a int. */ public void countThreads(int numThreads) { if(threadGroupToMonitor!=null && Thread.currentThread().getThreadGroup().getName().equals(threadGroupToMonitor)){ maxThreads = Math.max(maxThreads, numThreads); } } /** * <p> * Getter for the field <code>maxThreads</code>. * </p> * * @return a int. */ public int getMaxThreads() { return maxThreads; } public boolean getAndResetExceptionInfo() { if (hasNewExceptions) { hasNewExceptions = false; return true; } return false; } public void setThreadGroupToMonitor(String threadGroupToMonitor) { this.threadGroupToMonitor = threadGroupToMonitor; } }
/* * (C) Copyright 2000-2007 PharmaDM n.v. All rights reserved. * * This file is licensed under the terms of the GNU General Public License (GPL) version 2. * See http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt */ package com.pharmadm.util; import java.util.*; import java.io.*; public class MStreamTokenizer { protected BufferedReader reader; protected int lineno; protected String pushbacktoken; protected boolean prevcr; protected int pushbackchar; protected String chartokens; protected int commentchar; public MStreamTokenizer(InputStream stream) { this(new InputStreamReader(stream)); } public MStreamTokenizer(Reader myreader) { reader = new BufferedReader(myreader); lineno = 1; pushbacktoken = null; prevcr = false; pushbackchar = -1; chartokens = ":;,[]{}"; commentchar = '#'; } public String getToken() throws IOException { if (pushbacktoken == null) { int ch = readSignificantChar(); if (ch != -1) { StringBuffer strg = new StringBuffer(); boolean done = false; do { strg.append((char)ch); if (chartokens.indexOf((char)ch) == -1) { ch = readChar(); if (ch == ' ' || ch == 10 || ch == 13 || ch == -1 || ch == '\t') { pushBackChar(ch); done = true; } if (chartokens.indexOf((char)ch) != -1) { pushBackChar(ch); done = true; } } else { done = true; } } while (!done); return strg.toString(); } else { return null; } } else { String betw = pushbacktoken; pushbacktoken = null; return betw; } } public String readToken() throws IOException { int saveline = getLine(); String token = getToken(); if (token == null) throw new IOException("Unexpected end of file at line: "+saveline); return token; } public boolean hasMoreTokens() throws IOException { String token = getToken(); if (token == null) { return false; } else { pushBackToken(token); return true; } } public int readSignificantChar() throws IOException { int ch; do { ch = readChar(); if (ch == commentchar) { do { ch = readChar(); } while (ch != -1 && ch != 10 && ch != 13); } } while (ch == ' ' || ch == 10 || ch == 13 || ch == '\t'); return ch; } public int readChar() throws IOException { if (pushbackchar == -1) { int ch = reader.read(); if (ch == 10 && prevcr == false) lineno++; prevcr = (ch == 13); if (prevcr) lineno++; return ch; } else { int betw = pushbackchar; pushbackchar = -1; return betw; } } public String readTillEol() throws IOException { int ch; StringBuffer strg = new StringBuffer(); if (pushbacktoken == null) { ch = readSignificantChar(); if (ch == -1) return null; } else { strg.append(pushbacktoken); pushbacktoken = null; ch = readChar(); } while (ch != 10 && ch != 13 && ch != -1) { strg.append((char)ch); ch = readChar(); } pushBackChar(ch); return strg.toString(); } public int readInteger() throws IOException { int saveline = getLine(); String token = readToken(); try { return Integer.parseInt(token); } catch (NumberFormatException e) { throw new IOException("Integer value expected at line: "+saveline); } } public float readFloat() throws IOException { int saveline = getLine(); String token = readToken(); try { Float fl = new Float(token); return fl.floatValue(); } catch (NumberFormatException e) { throw new IOException("Float value expected at line: "+saveline); } } public String isNextTokenIn(String strg) throws IOException { String token = getToken(); if (token == null || strg.indexOf(token) != -1) { return token; } else { pushBackToken(token); return null; } } public boolean isNextToken(String strg) throws IOException { boolean yes = false; String token = getToken(); if (token == null) return false; if (token.equals(strg)) yes = true; else pushBackToken(token); return yes; } public boolean isNextTokenUpperCased(String strg) throws IOException { boolean yes = false; String token = getToken(); if (token == null) return false; if (token.toUpperCase().equals(strg)) yes = true; else pushBackToken(token); return yes; } public int readChar(String which) throws IOException { int saveline = getLine(); String character = getToken(); if (character == null) throw new IOException("Unexpected end of file reading character at line: "+saveline); int idx = which.indexOf(character.charAt(0)); if (idx < 0 || character.length() != 1) throw new IOException("Character '"+which+"' expected at line: "+saveline); return idx; } public void readChar(char ch) throws IOException { int saveline = getLine(); String character = getToken(); if (character == null) throw new IOException("Unexpected end of file reading character at line: "+saveline); if (!character.equals(String.valueOf(ch))) throw new IOException("Character '"+ch+"' expected at line: "+saveline); } public void pushBackChar(int ch) { pushbackchar = ch; } public void pushBackToken(String token) { pushbacktoken = token; } public String setCharTokens(String chartokens) { String result = this.chartokens; this.chartokens = chartokens; return result; } public int setCommentChar(int commentchar) { int result = this.commentchar; this.commentchar = commentchar; return result; } public String getCharTokens() { return chartokens; } public int setCommentChar() { return commentchar; } public int getLine() { return lineno; } public void close() throws IOException { reader.close(); } public String toString() { return "MStreamTokenizer ["+commentchar+"] ["+chartokens+"]"; } }
package com.simibubi.create.content.contraptions.components.actors; import com.simibubi.create.foundation.render.backend.gl.attrib.CommonAttributes; import com.simibubi.create.foundation.render.backend.gl.attrib.IAttribSpec; import com.simibubi.create.foundation.render.backend.gl.attrib.IVertexAttrib; import com.simibubi.create.foundation.render.backend.gl.attrib.VertexAttribSpec; public enum ActorVertexAttributes implements IVertexAttrib { INSTANCE_POSITION("aInstancePos", CommonAttributes.VEC3), LIGHT("aModelLight", CommonAttributes.LIGHT), OFFSET("aOffset", CommonAttributes.FLOAT), AXIS("aAxis", CommonAttributes.NORMAL), INSTANCE_ROTATION("aInstanceRot", CommonAttributes.VEC3), ROTATION_CENTER("aRotationCenter", CommonAttributes.NORMAL), ; private final String name; private final VertexAttribSpec spec; ActorVertexAttributes(String name, VertexAttribSpec spec) { this.name = name; this.spec = spec; } @Override public String attribName() { return name; } @Override public IAttribSpec attribSpec() { return spec; } @Override public int getDivisor() { return 1; } @Override public int getBufferIndex() { return 1; } }
/* * eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) 2017 eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * 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 3 of the License, or * 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, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * Further, all user interfaces, including but not limited to citizen facing interfaces, * Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any * derived works should carry eGovernments Foundation logo on the top right corner. * * For the logo, please refer http://egovernments.org/html/logo/egov_logo.png. * For any further queries on attribution, including queries on brand guidelines, * please contact contact@egovernments.org * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. * */ package org.egov.infra.microservice.contract; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.util.List; @JsonInclude(value = Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class TaskResponse { private ResponseInfo responseInfo; private List<Task> tasks; private Task task; private Pagination page; public ResponseInfo getResponseInfo() { return responseInfo; } public void setResponseInfo(ResponseInfo responseInfo) { this.responseInfo = responseInfo; } public List<Task> getTasks() { return tasks; } public void setTasks(List<Task> tasks) { this.tasks = tasks; } public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } public Pagination getPage() { return page; } public void setPage(Pagination page) { this.page = page; } }
/* * Copyright 2022 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 androidx.wear.tiles.material; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.util.Log; import androidx.annotation.NonNull; import androidx.test.core.app.ActivityScenario; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.screenshot.AndroidXScreenshotTestRule; import androidx.test.screenshot.matchers.MSSIMMatcher; import androidx.wear.tiles.LayoutElementBuilders; import androidx.wear.tiles.material.testapp.GoldenTestActivity; public class RunnerUtils { // This isn't totally ideal right now. The screenshot tests run on a phone, so emulate some // watch dimensions here. public static final int SCREEN_WIDTH = 390; public static final int SCREEN_HEIGHT = 390; private RunnerUtils() {} static void runSingleScreenshotTest(@NonNull AndroidXScreenshotTestRule rule, @NonNull LayoutElementBuilders.LayoutElement layoutElement, @NonNull String expected) { byte[] layoutElementPayload = layoutElement.toLayoutElementProto().toByteArray(); Intent startIntent = new Intent( InstrumentationRegistry.getInstrumentation().getTargetContext(), GoldenTestActivity.class); startIntent.putExtra("layout", layoutElementPayload); ActivityScenario<GoldenTestActivity> scenario = ActivityScenario.launch(startIntent); InstrumentationRegistry.getInstrumentation().waitForIdleSync(); try { // Wait 1s after launching the activity. This allows for the old white layout in the // bootstrap activity to fully go away before proceeding. Thread.sleep(1000); } catch (Exception ex) { if (ex instanceof InterruptedException) { Thread.currentThread().interrupt(); } Log.e("MaterialGoldenTest", "Error sleeping", ex); } Bitmap bitmap = Bitmap.createBitmap( InstrumentationRegistry.getInstrumentation().getUiAutomation().takeScreenshot(), 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ); rule.assertBitmapAgainstGolden(bitmap, expected, new MSSIMMatcher()); // There's a weird bug (related to b/159805732) where, when calling .close() on // ActivityScenario or calling finish() and immediately exiting the test, the test can hang // on a white screen for 45s. Closing the activity here and waiting for 1s seems to fix // this. scenario.onActivity(Activity::finish); try { Thread.sleep(1000); } catch (Exception ex) { if (ex instanceof InterruptedException) { Thread.currentThread().interrupt(); } Log.e("MaterialGoldenTest", "Error sleeping", ex); } } }
package io.github.cloudadc.iControl.model; public class Persist { public String name; public String partition; public String tmDefault; public NameReference nameReference; }
package tv.nexx.flutter.android.platform_view.command; import tv.nexx.flutter.android.estd.virtual_dispatch.DispatchTableMethod; import tv.nexx.flutter.android.platform_view.NexxPlayDispatchPayload; import tv.nexx.flutter.android.platform_view.NexxPlayMethodResult; import tv.nexx.flutter.android.platform_view.NexxPlayPlatformView; class PreviousCommand implements DispatchTableMethod<NexxPlayPlatformView, NexxPlayDispatchPayload> { private PreviousCommand() { } public static PreviousCommand create() { return new PreviousCommand(); } @Override public void dispatch(NexxPlayPlatformView receiver, NexxPlayDispatchPayload payload) { receiver.state().player().previous(); payload.result().success(NexxPlayMethodResult.from(receiver.state().id().numeric()).asMap()); } }
package com.hr.framework.repo; import java.util.List; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import com.hr.framework.po.business.crm.aclactions.AclRoles; import com.hr.framework.projections.business.crm.CRMAclRoleProjection; @RepositoryRestResource(collectionResourceRel = "crmAclRole" , path = "crmAclRole" , excerptProjection = CRMAclRoleProjection.class) public interface CRMAclRolesRepository extends PagingAndSortingRepository<AclRoles, Long> { List<AclRoles> findByRoleName(String id); }
package de.gruene.haustuer.topic; import javax.persistence.Entity; import javax.persistence.Id; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity public class Topic { @Id @Size(min = 1, max = 255) private String key; @NotNull @Size(min = 1, max = 10000) private String description; public Topic() { } public Topic(String key, String description) { this.key = key; this.description = description; } public Topic(Topic other) { this.key = other.key; this.description = other.description; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Topic topic = (Topic) o; return key.equals(topic.key); } @Override public int hashCode() { return key.hashCode(); } }
/* * 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.kafka.connect.health; import java.util.Objects; /** * Provides the current status along with identifier for Connect worker and tasks. */ public abstract class AbstractState { private final String state; private final String traceMessage; private final String workerId; /** * Construct a state for connector or task. * * @param state the status of connector or task; may not be null or empty * @param workerId the workerId associated with the connector or the task; may not be null or empty * @param traceMessage any error trace message associated with the connector or the task; may be null or empty */ public AbstractState(String state, String workerId, String traceMessage) { if (state == null || state.trim().isEmpty()) { throw new IllegalArgumentException("State must not be null or empty"); } if (workerId == null || workerId.trim().isEmpty()) { throw new IllegalArgumentException("Worker ID must not be null or empty"); } this.state = state; this.workerId = workerId; this.traceMessage = traceMessage; } /** * Provides the current state of the connector or task. * * @return state, never {@code null} or empty */ public String state() { return state; } /** * The identifier of the worker associated with the connector or the task. * * @return workerId, never {@code null} or empty. */ public String workerId() { return workerId; } /** * The error message associated with the connector or task. * * @return traceMessage, can be {@code null} or empty. */ public String traceMessage() { return traceMessage; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractState that = (AbstractState) o; return state.equals(that.state) && Objects.equals(traceMessage, that.traceMessage) && workerId.equals(that.workerId); } @Override public int hashCode() { return Objects.hash(state, traceMessage, workerId); } }
package cz.ivoa.vocloud.spark.worker; import cz.ivoa.vocloud.spark.schema.Worker; import cz.ivoa.vocloud.spark.worker.model.CopyOutputPath; import cz.ivoa.vocloud.spark.worker.model.DownloadFileRule; import cz.ivoa.vocloud.spark.worker.model.ParsedJsonConfig; import cz.ivoa.vocloud.spark.worker.model.SparkConfiguration; import org.apache.commons.io.IOUtils; import org.apache.hadoop.fs.*; import uws.UWSException; import uws.job.AbstractJob; import uws.job.Result; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.io.FileUtils; import org.zeroturnaround.zip.ZipUtil; import org.apache.hadoop.conf.Configuration; import javax.json.*; /** * @author kozajaku */ public class Job extends AbstractJob { private static final Logger LOG = Logger.getLogger(Job.class.getName()); private static final String OUTPUT_FILE_NAME = "run.out"; private static final String ERROR_FILE_NAME = "run.err"; private static final String RETURN_FILE_NAME = "run.ret"; private static final String SPARK_JOB_CONFIG_FILE_NAME = "sparkJobConfig.json"; private static final String WHOLE_CONFIG_FILE_NAME = "config.json"; private static final String DOWNLOAD_LOG_FILE_NAME = "download.log"; private static final String SUBMIT_COMMAND_FILE_NAME = "submitCommand"; private static final String PROCESS_DATA_FOLDER_NAME = ".processData"; private static final String WORKING_DIR_NAME = "workingDir"; private String configFile; private ParsedJsonConfig parsedJsonConfig; private SparkConfiguration sparkConfiguration; private File workingDir; private File jobDir; private Worker workerSettings; private Configuration hadoopConfiguration; private File outputFile; private File errorFile; private File returnFile; private File downloadLogFile; private File processDataDir; private boolean resultsPrepared = false; public Job(Map<String, String> lstParam) throws UWSException { super(lstParam); } @Override protected boolean loadAdditionalParams() throws UWSException { // check for parameter file LOG.log(Level.FINE, "Loading job parameters"); if (additionalParameters.containsKey("config")) {//especially in post application/x-www-url-encoded request configFile = additionalParameters.get("config");//could be big file - remove from map additionalParameters.remove("config"); } else { // for (Map.Entry<String, String> i: additionalParameters.entrySet()){ // System.out.println("key: |" + i.getKey() + "|"); // } if (configFile == null) { throw new UWSException(UWSException.BAD_REQUEST, "Config file has to be specified."); } } return true; } /** * Finds the Worker specification for the current Job. If the Worker settings could not * be found, throws <code>{@link UWSException}</code>. * * @return Instance of the <code>{@link Worker}</code> of the current Job. * @throws UWSException in case that this Job does not have * settings inside xml configuration file. */ private Worker getThisWorker() throws UWSException { for (Worker w : Config.settings.getWorkers().getWorker()) { if (w.getIdentifier().equals(getJobList().getName())) { return w; } } //note: this should not happen LOG.log(Level.SEVERE, "Worker with identifier {0} is not specified in settings", getJobList().getName()); throw new UWSException("Worker with identifier " + getJobList().getName() + " was not found"); } private List<String> constructSubmitCommands() { List<String> commands = new ArrayList<>(); //add spark-submit script commands.add(Config.settings.getSparkExecutable()); //append spark submit parameters commands.addAll(sparkConfiguration.commandsList()); //append spark program commands.add(workerSettings.getSubmitTarget().trim()); //append configuration file commands.add(new File(processDataDir, SPARK_JOB_CONFIG_FILE_NAME).getAbsolutePath().trim()); return commands; } private void printSubmitCommand(List<String> commands) { if (commands == null || commands.isEmpty()) { return; } Iterator<String> iter = commands.iterator(); StringBuilder builder = new StringBuilder(iter.next()); while (iter.hasNext()) { builder.append(" ").append(iter.next()); } File commandFile = new File(processDataDir, SUBMIT_COMMAND_FILE_NAME); String commString = builder.toString(); try (FileOutputStream fos = new FileOutputStream(commandFile)) { fos.write(commString.getBytes(Charset.forName("UTF-8"))); } catch (IOException ex) { LOG.log(Level.SEVERE, "Unable to create submitCommand file in working directory", ex); } } @Override @SuppressWarnings({"UseSpecificCatch", "SleepWhileInLoop"}) protected void jobWork() throws UWSException, InterruptedException { try { LOG.log(Level.INFO, "Starting job {0}", getJobId()); //save worker settings workerSettings = getThisWorker(); //try to parse json config parsedJsonConfig = new ParsedJsonConfig(configFile); sparkConfiguration = new SparkConfiguration(workerSettings, configFile); //create hadoop configuration hadoopConfiguration = new Configuration(); hadoopConfiguration.set("fs.defaultFS", Config.settings.getHadoopDefaultFs()); //free config file //create job directory jobDir = new File(Config.resultsDir + "/" + getJobId()); jobDir.mkdirs(); //create working directory workingDir = new File(jobDir, WORKING_DIR_NAME); workingDir.mkdir(); processDataDir = new File(workingDir, PROCESS_DATA_FOLDER_NAME); processDataDir.mkdir(); Process process = null; try { //print config file File config = new File(processDataDir, WHOLE_CONFIG_FILE_NAME); File sparkJobConfig = new File(processDataDir, SPARK_JOB_CONFIG_FILE_NAME); try (FileOutputStream fos = new FileOutputStream(config); FileOutputStream fosSpark = new FileOutputStream(sparkJobConfig)) { fos.write(configFile.getBytes(Charset.forName("UTF-8"))); fosSpark.write(parsedJsonConfig.getJobConfig().getBytes(Charset.forName("UTF-8"))); } catch (IOException ex) { LOG.log(Level.SEVERE, "Unable to create config files in working directory", ex); throw new UWSException("Unable to create config files in working directory"); } configFile = null; //download necessary files into HDFS downloadFiles(); // prepare output files try { outputFile = new File(processDataDir, OUTPUT_FILE_NAME); errorFile = new File(processDataDir, ERROR_FILE_NAME); returnFile = new File(processDataDir, RETURN_FILE_NAME); assert outputFile.createNewFile(); assert errorFile.createNewFile(); assert returnFile.createNewFile(); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "IO Exception when creating output files."); } //create process itself List<String> commands = constructSubmitCommands(); //print call commands printSubmitCommand(commands); //use substitution for commands ProcessBuilder pb = new ProcessBuilder(commands); pb.environment().putAll(sparkConfiguration.getEnvironment()); pb.directory(workingDir); try { pb.redirectOutput(outputFile); pb.redirectError(errorFile); process = pb.start(); //java 1.8 better solution // boolean processDone = false; // do { // processDone = process.waitFor(5, TimeUnit.SECONDS);//working since java 1.8 (better solution) // } while (!processDone && !thread.isInterrupted()); //java 1.7 solution while (true) { Thread.sleep(1000); try { process.exitValue(); //it was completed break; } catch (IllegalThreadStateException ex) { //not completed yet //will do the next loop } } if (thread.isInterrupted()) { throw new InterruptedException(); } } catch (InterruptedException ie) { //kill process if job is aborted LOG.log(Level.INFO, "Calling kill signal to process"); process.destroy(); } catch (IOException e) { LOG.log(Level.SEVERE, "error when executing job", e); throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, e, "error when executing job"); } // write return code to the file try (PrintStream ps = new PrintStream(returnFile)) { LOG.log(Level.INFO, "Process exit value: {0}", process.exitValue()); ps.println(process.exitValue()); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); throw new UWSException(ex); } copyOutput(); } catch (UWSException ex) { prepareResults(); if (thread.isInterrupted()) { throw new InterruptedException(); } throw ex; } // submit results, send error if process failed if (!thread.isInterrupted()) { prepareResults(); } else { throw new InterruptedException(); } if (process.exitValue() != 0) { throw new UWSException("process exit value:" + process.exitValue()); } } catch (Throwable ex) { //ignore interrupted and uws exception if (ex instanceof InterruptedException || ex instanceof UWSException) { //rethrow exception throw ex; } else { //catch every other exception and log it LOG.log(Level.SEVERE, "Unexpected exception", ex); throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ex, "unexpected throwable exception/error caught during job execution"); } } } private void copyOutput() throws InterruptedException, UWSException { try { for (CopyOutputPath path : parsedJsonConfig.getCopyOutputPaths()) { try (FileSystem fs = FileSystem.get(hadoopConfiguration)) { Path hdfsPath = new Path(path.getPath()); if (fs.exists(hdfsPath)) { if (fs.isDirectory(hdfsPath) && path.isMergeParts()) { try (OutputStream out = new FileOutputStream(new File(workingDir, path.getOutputName()))) { FileStatus contents[] = fs.listStatus(hdfsPath); for (FileStatus fileStatus : contents) { //ignore directories if (fileStatus.isDirectory()) { continue; } try (InputStream in = fs.open(fileStatus.getPath())) { IOUtils.copy(in, out); } } } } else { FileUtil.copy(fs, new Path(path.getPath()), new File(workingDir, path.getOutputName()), false, hadoopConfiguration); } } } } } catch (IOException ex) { LOG.log(Level.WARNING, "IOException in copyOutput function", ex); throw new UWSException(UWSException.BAD_REQUEST, ex, "exception during copying files from HDFS"); } } private void downloadFiles() throws InterruptedException { downloadLogFile = new File(processDataDir, DOWNLOAD_LOG_FILE_NAME); try (PrintStream log = new PrintStream(downloadLogFile, "UTF-8") { private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public void println(String x) { String timestamp = format.format(new Date()); super.println(timestamp + " " + x); } }) { for (DownloadFileRule rule : parsedJsonConfig.getDownloadRules()) { for (String url : rule.getUrls()) { if (thread.isInterrupted()) { throw new InterruptedException();//aborted } downloadRemoteResource(url, rule.getFolder(), log); } } } catch (FileNotFoundException ex) { LOG.log(Level.SEVERE, "Unable to create download log file"); } catch (UnsupportedEncodingException ex) { LOG.log(Level.SEVERE, "Unsupported encoding", ex); } } private void downloadRemoteResource(String urlStr, String folderPath, PrintStream log) { folderPath = folderPath.trim(); urlStr = urlStr.trim(); if (urlStr.isEmpty()) { log.println("Found empty url"); return; } //expand resource url if it starts with vocloud:// urlStr = urlStr.replaceFirst("^vocloud://", Config.settings.getVocloudServerAddress() + "/files/"); //create URL URL url; try { url = new URL(urlStr); } catch (MalformedURLException ex) { log.println("Malformed url: " + urlStr); return; } //try to create HttpUrlConnection HttpURLConnection conn; try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException ex) { log.println("Unable to connect to: " + urlStr); return; } catch (ClassCastException ex) { log.println("Resource is not http/https connection: " + urlStr); return; } //check if it is json - possible folder if ("application/json".equals(conn.getContentType())) { //possible folder StringBuilder folderJson = new StringBuilder(); //read into folderJson try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")))) { String line; while ((line = reader.readLine()) != null) { folderJson.append(line); } } catch (IOException ex) { log.println("Exception during reading folder json from: " + urlStr); conn.disconnect(); return; } conn.disconnect(); JsonObject folderDesc; try (JsonReader jsonReader = Json.createReader(new StringReader(folderJson.toString()));) { folderDesc = jsonReader.readObject(); } catch (JsonException ex) { log.println("Unable to parse folder describing json from: " + urlStr); return; } JsonArray folders; JsonArray files; try { folders = folderDesc.getJsonArray("folders"); files = folderDesc.getJsonArray("files"); } catch (JsonException ex) { log.println("Invalid format of folder json from: " + urlStr); return; } try { //call function recursively on folders and files for (JsonValue i : folders) { String folderName = ((JsonString) i).getString(); downloadRemoteResource(conc(urlStr, URLEncoder.encode(folderName, "UTF-8")), conc(folderPath, folderName), log); } for (JsonValue i : files) { String fileName = ((JsonString) i).getString(); downloadRemoteResource(conc(urlStr, URLEncoder.encode(fileName, "UTF-8")), folderPath, log); } } catch (UnsupportedEncodingException ex) { LOG.log(Level.SEVERE, "Unsupported encoding", ex); } } else { //create folder descriptor String[] split = urlStr.split("/"); String fileName = split[split.length - 1]; try { fileName = URLDecoder.decode(fileName, "UTF-8"); } catch (UnsupportedEncodingException ex) { LOG.log(Level.SEVERE, "Unsupported encoding", ex); return; } String hdfsPath = conc(folderPath, fileName); String error = downloadFile(conn, hdfsPath); if (error == null) { log.println("File " + fileName + " was successfully downloaded to " + folderPath); } else { log.println("Failed to download file " + fileName + " to folder " + folderPath + ". Reason: " + error); } conn.disconnect(); } } private String conc(String prefix, String value) { //concatenates two strings and puts slash between them if it is not already if (prefix.endsWith("/")) { return prefix + value; } //else return prefix + '/' + value; } private String downloadFile(HttpURLConnection conn, String hdfsPath) { int bufferSize = 1 << 16; try (FileSystem file = FileSystem.get(hadoopConfiguration); FSDataOutputStream fos = file.create(new Path(hdfsPath), false, bufferSize); ReadableByteChannel rbc = Channels.newChannel(conn.getInputStream()); WritableByteChannel wbc = Channels.newChannel(fos)) { ByteBuffer buffer = ByteBuffer.allocate(bufferSize); int bytesRead = rbc.read(buffer); while (bytesRead != -1) { buffer.flip(); wbc.write(buffer); buffer.clear(); bytesRead = rbc.read(buffer); } return null; } catch (IOException ex) { LOG.log(Level.WARNING, "File download failed", ex); return ex.getMessage(); } } @Override public synchronized void abort() throws UWSException { // we still want results even when job is aborted prepareResults(); super.abort(); configFile = null; } @Override public void clearResources() { try { // delete working dir recursively FileUtils.deleteDirectory(jobDir); } catch (IOException ex) { LOG.log(Level.WARNING, "Cannot delete job directory {0}", jobDir.toString()); } super.clearResources(); } private synchronized void prepareResults() throws UWSException { if (jobDir == null || workingDir == null) { return; } if (resultsPrepared) { return; } File zip = new File(jobDir, "results.zip"); //delete empty folders ZipUtil.pack(workingDir, zip); addResult(new Result("Results", "zip", Config.resultsLink + "/" + this.getJobId() + "/results.zip")); resultsPrepared = true; } }
package lsm.base; import java.util.Comparator; import com.google.common.collect.ComparisonChain; /** * InternalKey的比较器 * @author bird * */ public class InternalKeyComparator implements Comparator<InternalKey>{ @Override public int compare(InternalKey left, InternalKey right) { // 先比较bytebuf字节数据,再比较序列号大小 return ComparisonChain.start().compare(left.getUserKey(), right.getUserKey()) .compare(left.getSeq(), right.getSeq()).result(); } }
/** * NOTE: This class is auto generated by the swagger code generator program (2.3.1). * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ package io.swagger.api; import io.swagger.model.ErrorResponseDefault; import io.swagger.model.InlineResponseDefault; import io.swagger.model.Profile; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-08-03T19:26:46.543Z") @Api(value = "user", description = "the user API") public interface UserApi { @ApiOperation(value = "", nickname = "updateUser", notes = "Update User", response = Profile.class, tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "User Updated", response = Profile.class), @ApiResponse(code = 404, message = "User profile not found"), @ApiResponse(code = 200, message = "Unknown Error", response = ErrorResponseDefault.class) }) @RequestMapping(value = "/user-java/{userID}", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PATCH) ResponseEntity<Profile> updateUser(@ApiParam(value = "User's unique ID",required=true) @PathVariable("userID") String userID,@ApiParam(value = "Details of the profile" ,required=true ) @Valid @RequestBody Profile profile); @ApiOperation(value = "", nickname = "userPOST", notes = "Declares and creates a new profile", response = Profile.class, tags={ }) @ApiResponses(value = { @ApiResponse(code = 201, message = "Creation successful", response = Profile.class), @ApiResponse(code = 200, message = "An error occurred", response = InlineResponseDefault.class) }) @RequestMapping(value = "/user-java/{userID}", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST) ResponseEntity<Profile> userPOST(@ApiParam(value = "User's unique ID",required=true) @PathVariable("userID") String userID,@ApiParam(value = "Details of the profile" ,required=true ) @Valid @RequestBody Profile profile); }
/* (c) Copyright 2018 Paul Nguyen. All Rights Reserved */ package starbucks ; /** * Authentication Proxy for App Controller */ public class Device implements IApp, IPinAuthObserver { private static Device theDevice = null; private boolean fourPin = false ; private boolean sixPin = true ; private String pin = "" ; private IApp app ; private KeyPad kp ; private Passcode pc ; private PinScreen ps ; private Spacer sp ; private boolean authenticated = false ; private PinEntryMachine pm ; public static final int screen_frame_header = 3 ; public static final int portrait_screen_width = 15 ; public static final int portrait_screen_length = 10 ; public static final int landscape_screen_width = 32 ; public static final int landscape_screen_length = 6 ; public enum ORIENTATION_MODE { PORTRAIT, LANDSCAPE } private ORIENTATION_MODE device_orientation_state ; public ORIENTATION_MODE getDeviceOrientation() { return this.device_orientation_state ; } public void setPortraitOrientation() { this.device_orientation_state = ORIENTATION_MODE.PORTRAIT ; } public void setLandscapeOrientation() { this.device_orientation_state = ORIENTATION_MODE.LANDSCAPE ; } private Device() { } /** Debug Device State */ public static void debug() { Device d = Device.getInstance() ; System.err.println( "============================================" ) ; System.err.println( "--------- D E V I C E S T A T E ----------" ) ; System.err.println( "============================================" ) ; System.err.println( "Pin Option = " + d.getPinOption() ) ; System.err.println( "Stored Pin = " + d.getPin() ) ; System.err.println( "Authenticated = " + d.isAuthenticated() ) ; System.err.println( "Orientation = " + d.getDeviceOrientation() ) ; System.err.println( "============================================" ) ; } /** * Get Current Auth State * @return Auth T/F */ public String isAuthenticated() { return Boolean.toString( authenticated ) ; } /** * Return the current Pin Option: * 0 = User Chosed No Pin * 4 = User Chosed 4-digit Pin * 6 = User Chosed 6-digit Pin * @return Pin Option */ public int getPinOption() { if ( fourPin ) return 4 ; else if ( sixPin ) return 6 ; else return 0 ; } /** * Get Current Pin * @return Pin */ public String getPin() { return pin ; } /** * Set Pin * @param p New Pin */ private void setPin( String p ) { pin = p ; int len = p.length() ; switch ( len ) { case 0: fourPin = false ; sixPin = false ; case 4: fourPin = true ; sixPin = false ; break ; case 6: fourPin = false ; sixPin = true ; break ; default: fourPin = false ; sixPin = false ; } } /** * Device Reset Pin */ private void clearPin() { this.pin = "" ; } /** * Get Singleton Instance * @return Reference to Current Device Config (Create if none exists) */ public synchronized static Device getInstance() { if (theDevice == null) { return getNewInstance( "1234" ) ; } else return theDevice; } /** * Get New Instance * @return Reference to Device (Create New Singleton) */ public synchronized static Device getNewInstance() { return getNewInstance( "1234" ) ; } public synchronized static Device getNewInstance( String pin ) { theDevice = new Device() ; theDevice.setPin( pin ) ; theDevice.startUp() ; debug() ; return theDevice ; } /** * Device Starup Process. * Starts Up with Default 4-Pin Option */ public void startUp() { kp = new KeyPad() ; pc = new Passcode() ; sp = new Spacer() ; ps = new PinScreen() ; pm = new PinEntryMachine() ; // setup the composite pattern ps.addSubComponent( pc ) ; ps.addSubComponent( sp ) ; ps.addSubComponent( kp ) ; // setup the observer pattern ((IKeyPadSubject)kp).attach( pc ) ; ((IKeyPadSubject)kp).attach( pm ) ; ((IPinAuthSubject)pm).registerObserver(this) ; // get app controller reference app = new AppController() ; // startup in portrait this.device_orientation_state = ORIENTATION_MODE.PORTRAIT ; } /** * Switch to Landscape View */ public void landscape() { if ( authenticated ) app.landscape() ; } /** * Switch to Portait View */ public void portrait() { if ( authenticated ) app.portrait() ; } /** * User Touch at X,Y Coordinates * @param x X Coordinate * @param y Y Coordinate */ public void touch(int x, int y) { if ( authenticated ) app.touch(x, y) ; else ps.touch(x, y) ; } /** * Display Screen Contents to Terminal */ public void display() { System.out.println( screenContents() ) ; } /** * Get Class Name of Screen * @return Class Name of Current Screen */ public String screen() { if ( authenticated ) return app.screen() ; else return ps.name() ; } /** * Get Screen Contents as a String * @return Screen Contents of Current Screen */ public String screenContents() { if ( authenticated ) { return app.screenContents() ; } else { String out = "" ; out = "----------------\n" ; out += " " + ps.name() + " \n" ; out += "----------------\n\n\n" ; out += ps.display() ; out += "\n\n\n----------------\n" ; return out ; } } /** * Select a Menu Command * @param c Menu Option (A, B, C, E, or E) */ public void execute( String c ) { if ( authenticated ) app.execute( c ) ; } /** * Navigate to Previous Screen */ public void prev() { if ( authenticated ) app.prev() ; } /** * Navigate to Next Screen */ public void next() { if ( authenticated ) app.next() ; } /** * Receive Authenticated Event from Authenticator */ public void authEvent() { this.authenticated = true ; } }
package com.ms.silverking.cloud.dht.net; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Set; import com.ms.silverking.cloud.dht.RetrievalOptions; import com.ms.silverking.cloud.dht.RetrievalType; import com.ms.silverking.cloud.dht.SecondaryTarget; import com.ms.silverking.cloud.dht.VersionConstraint; import com.ms.silverking.cloud.dht.WaitMode; import com.ms.silverking.cloud.dht.common.DHTConstants; import com.ms.silverking.cloud.dht.common.DHTKey; import com.ms.silverking.cloud.dht.common.EnumValues; import com.ms.silverking.cloud.dht.common.InternalRetrievalOptions; import com.ms.silverking.cloud.dht.common.MessageType; import com.ms.silverking.cloud.dht.common.OptionsHelper; import com.ms.silverking.cloud.dht.net.protocol.KeyedMessageFormat; import com.ms.silverking.cloud.dht.net.protocol.RetrievalMessageFormat; import com.ms.silverking.cloud.dht.net.protocol.RetrievalResponseMessageFormat; import com.ms.silverking.id.UUIDBase; import com.ms.silverking.numeric.NumConversion; public class ProtoRetrievalMessageGroup extends ProtoKeyedMessageGroup { private static final int optionBufferIndex = 1; public ProtoRetrievalMessageGroup(UUIDBase uuid, long context, InternalRetrievalOptions retrievalOptions, byte[] originator, int size, int deadlineRelativeMillis, ForwardingMode forward) { super(MessageType.RETRIEVE, uuid, context, ByteBuffer.allocate(RetrievalMessageFormat.getOptionsBufferLength(retrievalOptions.getRetrievalOptions())), size, RetrievalMessageFormat.size - KeyedMessageFormat.baseBytesPerKeyEntry, originator, deadlineRelativeMillis, forward); Set<SecondaryTarget> secondaryTargets; byte[] userOptions; // FUTURE - merge with ProtoValueMessagGroup code? bufferList.add(optionsByteBuffer); // begin retrievalType, waitMode encoding // see getRetrievalOptions() for decoding optionsByteBuffer.put((byte) ((retrievalOptions.getRetrievalType().ordinal() << 4) | retrievalOptions .getWaitMode().ordinal())); // end retrievalType, waitMode encoding optionsByteBuffer.put((byte) (((retrievalOptions.getVerifyIntegrity() ? 1 : 0) << 1) | (retrievalOptions.getRetrievalOptions().getUpdateSecondariesOnMiss() ? 1 : 0)) ); VersionConstraint vc = retrievalOptions.getVersionConstraint(); optionsByteBuffer.putLong(vc.getMin()); optionsByteBuffer.putLong(vc.getMax()); optionsByteBuffer.put((byte) vc.getMode().ordinal()); optionsByteBuffer.putLong(vc.getMaxCreationTime()); secondaryTargets = retrievalOptions.getRetrievalOptions().getSecondaryTargets(); if (secondaryTargets == null) { optionsByteBuffer.putShort((short)0); } else { byte[] serializedST; serializedST = SecondaryTargetSerializer.serialize(secondaryTargets); optionsByteBuffer.putShort((short)serializedST.length); optionsByteBuffer.put(serializedST); } userOptions = retrievalOptions.getUserOptions(); if (userOptions == null) { optionsByteBuffer.putInt(0); } else { optionsByteBuffer.putInt(userOptions.length); optionsByteBuffer.put(userOptions); } } /* public ProtoRetrievalMessageGroup(UUIDBase uuid, long context, RetrievalOptions retrievalOptions, byte[] originator, List<? extends DHTKey> destEntries, int deadlineRelativeMillis) { this(uuid, context, retrievalOptions, originator, destEntries.size(), deadlineRelativeMillis, ForwardingMode.DO_NOT_FORWARD); for (DHTKey key : destEntries) { addKey(key); } } */ public ProtoRetrievalMessageGroup(UUIDBase uuid, long context, InternalRetrievalOptions retrievalOptions, byte[] originator, Collection<DHTKey> keys, int deadlineRelativeMillis) { this(uuid, context, retrievalOptions, originator, keys.size(), deadlineRelativeMillis, ForwardingMode.DO_NOT_FORWARD); for (DHTKey key : keys) { addKey(key); } } public static InternalRetrievalOptions getRetrievalOptions(MessageGroup mg) { int retrievalWaitByte; RetrievalType retrievalType; WaitMode waitMode; int miscOptionsByte; VersionConstraint vc; ByteBuffer optionBuffer; boolean verifyIntegrity; boolean updateSecondariesOnMiss; optionBuffer = mg.getBuffers()[optionBufferIndex]; retrievalWaitByte = optionBuffer.get(RetrievalResponseMessageFormat.retrievalTypeWaitModeOffset); // begin retrievalType, waitMode decoding // see ProtoRetrievalMessageGroup() for encoding retrievalType = EnumValues.retrievalType[retrievalWaitByte >> 4]; waitMode = EnumValues.waitMode[retrievalWaitByte & 0x0f]; // end retrievalType, waitMode decoding miscOptionsByte = optionBuffer.get(RetrievalResponseMessageFormat.miscOptionsOffset); verifyIntegrity = (miscOptionsByte & 0x2) != 0; updateSecondariesOnMiss = (miscOptionsByte & 0x1) != 0; vc = new VersionConstraint(optionBuffer.getLong(RetrievalResponseMessageFormat.vcMinOffset), optionBuffer.getLong(RetrievalResponseMessageFormat.vcMaxOffset), EnumValues.versionConstraint_Mode[optionBuffer.get(RetrievalResponseMessageFormat.vcModeOffset)], optionBuffer.getLong(RetrievalResponseMessageFormat.vcMaxStorageTimeOffset)); return new InternalRetrievalOptions(OptionsHelper.newRetrievalOptions(retrievalType, waitMode, vc, updateSecondariesOnMiss, getSecondaryTargets(mg), getUserOptions(mg)), verifyIntegrity); } public static int getSTLength(MessageGroup mg) { return mg.getBuffers()[optionBufferIndex].getShort(RetrievalMessageFormat.stDataOffset); } private static Set<SecondaryTarget> getSecondaryTargets(MessageGroup mg) { int stLength; byte[] stDef; stLength = getSTLength(mg); if (stLength == 0) { return DHTConstants.noSecondaryTargets; } else { stDef = new byte[stLength]; System.arraycopy(mg.getBuffers()[optionBufferIndex].array(), RetrievalMessageFormat.stDataOffset + NumConversion.BYTES_PER_SHORT, stDef, 0, stLength); return SecondaryTargetSerializer.deserialize(stDef); } } public static int getUOStart(MessageGroup mg) { return RetrievalMessageFormat.stDataOffset + NumConversion.BYTES_PER_SHORT + getSTLength(mg); } public static int getUOLength(MessageGroup mg) { int start = getUOStart(mg); return mg.getBuffers()[optionBufferIndex].getInt(start); } private static byte[] getUserOptions(MessageGroup mg) { int uoLength; byte[] uo; int uoStartPos; uoStartPos = getUOStart(mg); uoLength = getUOLength(mg); if (uoLength == 0) { return RetrievalOptions.noUserOptions; } else { uo = new byte[uoLength]; System.arraycopy(mg.getBuffers()[optionBufferIndex].array(), uoStartPos + NumConversion.BYTES_PER_INT, uo, 0, uoLength); return uo; } } protected MessageGroup toMessageGroup(boolean flip) { MessageGroup mg; mg = super.toMessageGroup(flip); return mg; } }
package ru.ajana.work.pattern.behavior.chain.sample; /** * Абстрактный логгер. * * @author Andrey Kharintsev on 26.12.2018 */ public abstract class Logger { public static int ERR = 3; public static int NOTICE = 5; public static int DEBUG = 7; protected int mask; // The next element in the chain of responsibility protected Logger next; public Logger setNext(Logger log) { next = log; return log; } public void message(String msg, int priority) { if (priority <= mask) { writeMessage(msg); } if (next != null) { next.message(msg, priority); } } abstract protected void writeMessage(String msg); }
/** * Hierarchy check: * - A class that has (declares or inherits) any abstract methods must * be abstract (8.1.1.1). (Method addAll(Collection) from Set not * implemented) */ public abstract class Foo implements Runnable{ public Foo(){} }
package com.huaweicloud.sdk.kafka.v2.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.huaweicloud.sdk.kafka.v2.model.ResetPasswordReq; import java.util.function.Consumer; import java.util.Objects; /** * Request Object */ public class ResetPasswordRequest { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="instance_id") private String instanceId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="body") private ResetPasswordReq body; public ResetPasswordRequest withInstanceId(String instanceId) { this.instanceId = instanceId; return this; } /** * 实例ID。 * @return instanceId */ public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public ResetPasswordRequest withBody(ResetPasswordReq body) { this.body = body; return this; } public ResetPasswordRequest withBody(Consumer<ResetPasswordReq> bodySetter) { if(this.body == null ){ this.body = new ResetPasswordReq(); bodySetter.accept(this.body); } return this; } /** * Get body * @return body */ public ResetPasswordReq getBody() { return body; } public void setBody(ResetPasswordReq body) { this.body = body; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResetPasswordRequest resetPasswordRequest = (ResetPasswordRequest) o; return Objects.equals(this.instanceId, resetPasswordRequest.instanceId) && Objects.equals(this.body, resetPasswordRequest.body); } @Override public int hashCode() { return Objects.hash(instanceId, body); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ResetPasswordRequest {\n"); sb.append(" instanceId: ").append(toIndentedString(instanceId)).append("\n"); sb.append(" body: ").append(toIndentedString(body)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.hong.coolweather.util; import android.text.TextUtils; import com.google.gson.Gson; import com.hong.coolweather.db.City; import com.hong.coolweather.db.County; import com.hong.coolweather.db.Province; import com.hong.coolweather.gson.AQI; import com.hong.coolweather.gson.WeatherBean; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Utility { /** * 解析和处理服务器返回的省级数据 */ public static boolean handleProvinceResponse(String response) { if (!TextUtils.isEmpty(response)) { try { JSONArray allProvinces = new JSONArray(response); for (int i = 0; i < allProvinces.length(); i++) { JSONObject provincesJSONObject = allProvinces.getJSONObject(i); Province province = new Province(); province.setProvinceName(provincesJSONObject.getString("name")); province.setProvinceCode(provincesJSONObject.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 解析和处理服务器返回的市级数据 */ public static boolean handleCityResponse(String response, int provincedId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allcities = new JSONArray(response); for (int i = 0; i < allcities.length(); i++) { JSONObject provincesJSONObject = allcities.getJSONObject(i); City city = new City(); city.setCityName(provincesJSONObject.getString("name")); city.setCityCode(provincesJSONObject.getInt("id")); city.setProvinceId(provincedId); city.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 解析和处理服务器返回的县级数据 */ public static boolean handleCountyResponse(String response, int cityId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCounties = new JSONArray(response); for (int i = 0; i < allCounties.length(); i++) { JSONObject provincesJSONObject = allCounties.getJSONObject(i); County county = new County(); county.setCountyName(provincesJSONObject.getString("name")); county.setWeatherId(provincesJSONObject.getString("weather_id")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 将返回的JSON数据解析成Weather实体类 */ public static WeatherBean handleWeatherResponse(String response) { try { JSONObject object = new JSONObject(response); JSONArray jsonArray = object.getJSONArray("HeWeather6"); String weatherContent = jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent, WeatherBean.class); } catch (JSONException e) { e.printStackTrace(); } return null; } /** * 解析AQI空气质量 * @param responseText * @return */ public static AQI handleAQIResponse(String responseText) { return new Gson().fromJson(responseText, AQI.class); } }
/* * 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.druid.indexing.common.task; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.druid.indexer.TaskStatus; import org.apache.druid.indexing.common.Counters; import org.apache.druid.indexing.common.TestUtils; import org.apache.druid.indexing.common.actions.LocalTaskActionClient; import org.apache.druid.indexing.common.actions.TaskActionClient; import org.apache.druid.indexing.common.actions.TaskActionToolbox; import org.apache.druid.indexing.common.actions.TaskAuditLogConfig; import org.apache.druid.indexing.common.config.TaskStorageConfig; import org.apache.druid.indexing.overlord.HeapMemoryTaskStorage; import org.apache.druid.indexing.overlord.TaskLockbox; import org.apache.druid.indexing.overlord.TaskStorage; import org.apache.druid.metadata.EntryExistsException; import org.apache.druid.metadata.IndexerSQLMetadataStorageCoordinator; import org.apache.druid.metadata.TestDerbyConnector; import org.apache.druid.segment.IndexIO; import org.apache.druid.segment.IndexMergerV9; import org.apache.druid.server.metrics.NoopServiceEmitter; import org.junit.Rule; public abstract class IngestionTestBase { @Rule public final TestDerbyConnector.DerbyConnectorRule derbyConnectorRule = new TestDerbyConnector.DerbyConnectorRule(); private final TestUtils testUtils = new TestUtils(); private final ObjectMapper objectMapper = testUtils.getTestObjectMapper(); private final TaskStorage taskStorage = new HeapMemoryTaskStorage(new TaskStorageConfig(null)); private final TaskLockbox lockbox = new TaskLockbox(taskStorage); public IngestionTestBase() { } public TaskActionClient createActionClient(Task task) { return new LocalTaskActionClient(task, taskStorage, createTaskActionToolbox(), new TaskAuditLogConfig(false)); } public void prepareTaskForLocking(Task task) throws EntryExistsException { lockbox.add(task); taskStorage.insert(task, TaskStatus.running(task.getId())); } public ObjectMapper getObjectMapper() { return objectMapper; } public TaskStorage getTaskStorage() { return taskStorage; } public TaskLockbox getLockbox() { return lockbox; } public TaskActionToolbox createTaskActionToolbox() { final IndexerSQLMetadataStorageCoordinator storageCoordinator = new IndexerSQLMetadataStorageCoordinator( objectMapper, derbyConnectorRule.metadataTablesConfigSupplier().get(), derbyConnectorRule.getConnector() ); storageCoordinator.start(); return new TaskActionToolbox( lockbox, taskStorage, storageCoordinator, new NoopServiceEmitter(), null, new Counters() ); } public IndexIO getIndexIO() { return testUtils.getTestIndexIO(); } public IndexMergerV9 getIndexMerger() { return testUtils.getTestIndexMergerV9(); } }
package vazkii.quark.world.world; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkGeneratorFlat; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator; import vazkii.quark.world.feature.MonsterBoxes; import java.util.Random; public class MonsterBoxGenerator implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { if(!MonsterBoxes.dimensions.canSpawnHere(world) || chunkGenerator instanceof ChunkGeneratorFlat) return; float chance = MonsterBoxes.chunkChance; while(world.rand.nextFloat() <= chance) { int x = chunkX * 16 + 8 + random.nextInt(16); int y = MonsterBoxes.minY + random.nextInt(MonsterBoxes.maxY - MonsterBoxes.minY + 1); int z = chunkZ * 16 + 8 + random.nextInt(16); BlockPos pos = new BlockPos(x, y, z); if(world.isAirBlock(pos)) { BlockPos testPos = pos; IBlockState testState; do { testPos = testPos.down(); testState = world.getBlockState(testPos); } while(testState.getMaterial() != Material.ROCK && testPos.getY() >= MonsterBoxes.minY); BlockPos placePos = testPos.up(); if(testPos.getY() >= MonsterBoxes.minY && world.isAirBlock(placePos)) world.setBlockState(placePos, MonsterBoxes.monster_box.getDefaultState()); } chance -=MonsterBoxes.chunkChance; } } }
package com.pepper.common.utils.file; import java.io.File; import java.io.IOException; import org.apache.commons.io.FilenameUtils; import org.springframework.web.multipart.MultipartFile; import com.pepper.common.constant.Constants; import com.pepper.common.exception.file.FileNameLengthLimitExceededException; import com.pepper.common.exception.file.FileSizeLimitExceededException; import com.pepper.common.exception.file.InvalidExtensionException; import com.pepper.common.utils.DateUtils; import com.pepper.common.utils.Md5Utils; import com.pepper.common.utils.StringUtils; import com.pepper.framework.config.OpsConfig; /** * 文件上传工具类 * * @author pepper */ public class FileUploadUtils { /** * 默认大小 50M */ public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; /** * 默认的文件名最大长度 100 */ public static final int DEFAULT_FILE_NAME_LENGTH = 100; /** * 默认上传的地址 */ private static String defaultBaseDir = OpsConfig.getProfile(); private static int counter = 0; public static void setDefaultBaseDir(String defaultBaseDir) { FileUploadUtils.defaultBaseDir = defaultBaseDir; } public static String getDefaultBaseDir() { return defaultBaseDir; } /** * 以默认配置进行文件上传 * * @param file 上传的文件 * @return 文件名称 * @throws Exception */ public static final String upload(MultipartFile file) throws IOException { try { return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 根据文件路径上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static final String upload(String baseDir, MultipartFile file) throws IOException { try { return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 文件上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @param extension 上传文件类型 * @return 返回上传成功的文件名 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws FileNameLengthLimitExceededException 文件名太长 * @throws IOException 比如读写文件出错时 * @throws InvalidExtensionException 文件校验异常 */ public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException { int fileNamelength = file.getOriginalFilename().length(); if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); } //assertAllowed(file, allowedExtension); String fileName = extractFilename(file); File desc = getAbsoluteFile(baseDir, fileName); file.transferTo(desc); String pathFileName = getPathFileName(baseDir, fileName); return pathFileName; } /** * 编码文件名 */ public static final String extractFilename(MultipartFile file) { String fileName = file.getOriginalFilename(); String extension = getExtension(file); fileName = DateUtils.datePath() + "/" + encodingFilename(fileName) + "." + extension; return fileName; } private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName); if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } if (!desc.exists()) { desc.createNewFile(); } return desc; } private static final String getPathFileName(String uploadDir, String fileName) throws IOException { int dirLastIndex = OpsConfig.getProfile().length() + 1; String currentDir = StringUtils.substring(uploadDir, dirLastIndex); String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; return pathFileName; } /** * 编码文件名 */ private static final String encodingFilename(String fileName) { fileName = fileName.replace("_", " "); fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++); return fileName; } /** * 文件大小校验 * * @param file 上传的文件 * @return * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws InvalidExtensionException */ public static final void assertAllowed(MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, InvalidExtensionException { long size = file.getSize(); if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) { throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024); } String fileName = file.getOriginalFilename(); String extension = getExtension(file); if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) { if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) { throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) { throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) { throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName); } else { throw new InvalidExtensionException(allowedExtension, extension, fileName); } } } /** * 判断MIME类型是否是允许的MIME类型 * * @param extension * @param allowedExtension * @return */ public static final boolean isAllowedExtension(String extension, String[] allowedExtension) { for (String str : allowedExtension) { if (str.equalsIgnoreCase(extension)) { return true; } } return false; } /** * 获取文件名的后缀 * * @param file 表单文件 * @return 后缀名 */ public static final String getExtension(MultipartFile file) { String extension = FilenameUtils.getExtension(file.getOriginalFilename()); if (StringUtils.isEmpty(extension)) { extension = MimeTypeUtils.getExtension(file.getContentType()); } return extension; } }
package com.example.jiegeweather.gson; import com.google.gson.annotations.SerializedName; public class Suggestion { @SerializedName("comf") public Comfort comfort; @SerializedName("cw") public CarWash carWash; public Sport sport; public class Comfort{ @SerializedName("txt") public String info; } public class CarWash{ @SerializedName("txt") public String info; } public class Sport{ @SerializedName("txt") public String info; } }
/* * CSS Splitter Maven Plugin * http://css-splitter-maven-plugin.projects.gabrys.biz/ * * Copyright (c) 2015 Adam Gabrys * * This file is licensed under the BSD 3-Clause (the "License"). * You may not use this file except in compliance with the License. * You may obtain: * - a copy of the License at project page * - a template of the License at https://opensource.org/licenses/BSD-3-Clause */ package biz.gabrys.maven.plugins.css.splitter.split; import biz.gabrys.maven.plugins.css.splitter.css.type.NodeRule; class SplitResult { private final NodeRule before; private final NodeRule after; SplitResult(final NodeRule before, final NodeRule after) { this.before = before; this.after = after; } NodeRule getBefore() { return before; } NodeRule getAfter() { return after; } }
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.cache; import com.google.common.annotations.GwtCompatible; /** * Calculates the weights of cache entries. * * @author Charles Fry * @since 11.0 */ @GwtCompatible public interface Weigher<K, V> { /** * Returns the weight of a cache entry. There is no unit for entry weights; rather they are simply * relative to each other. * * @return the weight of the entry; must be non-negative */ int weigh(K key, V value); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.eagle.service.security.hbase; import org.apache.eagle.log.entity.ListQueryAPIResponseEntity; import org.apache.eagle.security.entity.HbaseResourceSensitivityAPIEntity; import org.apache.eagle.service.generic.ListQueryResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class HbaseSensitivityResourceService { private static Logger LOG = LoggerFactory.getLogger(HbaseSensitivityResourceService.class); public Map<String, Map<String, String>> getAllHbaseSensitivityMap(){ ListQueryResource resource = new ListQueryResource(); /* parameters are: query, startTime, endTime, pageSzie, startRowkey, treeAgg, timeSeries, intervalmin, top, filterIfMissing, * parallel, metricName*/ ListQueryAPIResponseEntity ret = resource.listQuery("HbaseResourceSensitivityService[]{*}", null, null, Integer.MAX_VALUE, null, false, false, 0L, 0, false, 0, null); List<HbaseResourceSensitivityAPIEntity> list = (List<HbaseResourceSensitivityAPIEntity>) ret.getObj(); if( list == null ) return Collections.emptyMap(); Map<String, Map<String, String>> res = new HashMap<String, Map<String, String>>(); for(HbaseResourceSensitivityAPIEntity entity : list){ String site = entity.getTags().get("site"); if(entity.getTags().containsKey("hbaseResource")) { if(res.get(site) == null){ res.put(site, new HashMap<String, String>()); } Map<String, String> resSensitivityMap = res.get(site); resSensitivityMap.put(entity.getTags().get("hbaseResource"), entity.getSensitivityType()); } else { if(LOG.isDebugEnabled()) { LOG.debug("An invalid sensitivity entity is detected" + entity); } } } return res; } public Map<String, String> getHbaseSensitivityMap(String site){ ListQueryResource resource = new ListQueryResource(); String queryFormat = "HbaseResourceSensitivityService[@site=\"%s\"]{*}"; ListQueryAPIResponseEntity ret = resource.listQuery(String.format(queryFormat, site), null, null, Integer.MAX_VALUE, null, false, false, 0L, 0, false, 0, null); List<HbaseResourceSensitivityAPIEntity> list = (List<HbaseResourceSensitivityAPIEntity>) ret.getObj(); if( list == null ) return Collections.emptyMap(); Map<String, String> resSensitivityMap = new HashMap<String, String>(); for(HbaseResourceSensitivityAPIEntity entity : list){ if(entity.getTags().containsKey("hbaseResource")) { resSensitivityMap.put(entity.getTags().get("hbaseResource"), entity.getSensitivityType()); } } return resSensitivityMap; } }
package com.bandwidth.webrtc; import org.webrtc.SdpObserver; import org.webrtc.SessionDescription; public class SdpAdapter implements SdpObserver { @Override public void onCreateSuccess(SessionDescription sessionDescription) { } @Override public void onSetSuccess() { } @Override public void onCreateFailure(String s) { } @Override public void onSetFailure(String s) { } }
package org.intermine.web.util; /* * Copyright (C) 2002-2021 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * Util class for URL processing. * @author Jakub Kulaviak **/ public final class URLUtil { private URLUtil() { } /** * Encodes URL. Parses url and encodes parameter names and * parameter values to be safe URL. * * @param url url * @return encoded url */ public static String encodeURL(String url) { String[] paths = url.split("\\?"); String ret = paths[0] + "?"; if (paths.length == 2) { ret += encodeParameters(paths[1]); } return ret; } private static String encodeParameters(String queryString) { String ret = ""; String[] pars = queryString.split("&"); for (int i = 0; i < pars.length; i++) { String par = pars[i]; String[] parts = par.split("="); if (parts.length > 1) { ret += encodeString(parts[0]); } if (parts.length == 2) { ret += "=" + encodeString(parts[1]); } if (i != pars.length - 1) { ret += "&"; } } return ret; } /** * Encodes string to be URL safe. For encoding URL use encodeURL * method. * * @param s string to be encoded * @return encoded string */ public static String encodeString(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("string encoding failed", e); } } }
/* * Copyright 2008 Marc Boorshtein * * 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 net.sourceforge.myvd.test.acl; import java.util.ArrayList; import java.util.HashMap; import net.sourceforge.myvd.chain.SearchInterceptorChain; import net.sourceforge.myvd.core.InsertChain; import net.sourceforge.myvd.inserts.Insert; import net.sourceforge.myvd.inserts.accessControl.AccessControlItem; import net.sourceforge.myvd.router.Router; import net.sourceforge.myvd.server.Server; import net.sourceforge.myvd.test.util.OpenLDAPUtils; import net.sourceforge.myvd.test.util.StartOpenLDAP; import net.sourceforge.myvd.types.DistinguishedName; import net.sourceforge.myvd.types.Password; import net.sourceforge.myvd.types.SessionVariables; import com.novell.ldap.util.DN; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.BeforeClass; import org.junit.AfterClass; import static org.junit.Assert.*; public class TestValidateSubjects { private static StartOpenLDAP openldapServer; private static Server server; private static InsertChain globalChain; private static Router router; @BeforeClass public static void setUp() throws Exception { OpenLDAPUtils.killAllOpenLDAPS(); openldapServer = new StartOpenLDAP(); openldapServer.startServer(System.getenv("PROJ_DIR") + "/test/ACITest",10983,"cn=admin,dc=domain,dc=com","manager"); server = new Server(System.getenv("PROJ_DIR") + "/test/TestServer/testACI.props"); server.startServer(); globalChain = server.getGlobalChain(); router = server.getRouter(); } @Test public void testPublic() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#public:"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testSubtreePass() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#subtree:ou=users,dc=domain,dc=com"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testSubtreeFail() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#subtree:ou=apps,dc=domain,dc=com"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testThisPass() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#this:"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,new DN("uid=testuser,ou=users,dc=domain,dc=com"))) { fail("subject check failed"); } } @Test public void testThisFail() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#this:"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (aci.checkSubject(chain,new DN("uid=testuser1,ou=users,dc=domain,dc=com"))) { fail("subject check failed"); } } @Test public void testDNPass() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#dn:uid=testuser,ou=users,dc=domain,dc=com"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testDNFail() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#dn:uid=testuser1,ou=users,dc=domain,dc=com"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testStaticGroupPass() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#group:cn=staticgroup1,ou=groups,dc=domain,dc=com"); HashMap<Object,Object> session = new HashMap<Object,Object>(); session.put(SessionVariables.BOUND_INTERCEPTORS,new ArrayList<String>()); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,session,new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,null)) { fail("subject check failed"); } chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser2,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,session,new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testStaticGroupFail() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#group:cn=staticgroup1,ou=groups,dc=domain,dc=com"); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser1,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,new HashMap<Object,Object>(),new HashMap<Object,Object>(),this.router); if (aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testDynGroupPass() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#dynamic-group:cn=dynamicgroup1,ou=groups,dc=domain,dc=com"); HashMap<Object,Object> session = new HashMap<Object,Object>(); session.put(SessionVariables.BOUND_INTERCEPTORS,new ArrayList<String>()); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,session,new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,null)) { fail("subject check failed"); } chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser1,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,session,new HashMap<Object,Object>(),this.router); if (! aci.checkSubject(chain,null)) { fail("subject check failed"); } } @Test public void testDynGroupFail() throws Exception { AccessControlItem aci = new AccessControlItem(0,"cn=test,ou=myorg,dc=domain,dc=com#entry#grant:r,w,o#[all]#dynamic-group:cn=dynamicgroup1,ou=groups,dc=domain,dc=com"); HashMap<Object,Object> session = new HashMap<Object,Object>(); session.put(SessionVariables.BOUND_INTERCEPTORS,new ArrayList<String>()); SearchInterceptorChain chain = new SearchInterceptorChain(new DistinguishedName("uid=testuser2,ou=users,dc=domain,dc=com"),new Password(""),0,this.globalChain,session,new HashMap<Object,Object>(),this.router); if (aci.checkSubject(chain,null)) { fail("subject check failed"); } } @AfterClass public static void tearDown() throws Exception { openldapServer.stopServer(); server.stopServer(); } }
package cn.iocoder.yudao.module.pay.service.order; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderExtensionDO; import java.util.Collection; import java.util.List; import java.util.Map; /** * 支付订单 Service 接口 * * @author aquan */ public interface PayOrderExtensionService { /** * 获得支付订单 * * @param id 编号 * @return 支付订单 */ PayOrderExtensionDO getOrderExtension(Long id); /** * 获得支付订单 * 列表 * * @param ids 编号 * @return 支付订单 * 列表 */ List<PayOrderExtensionDO> getOrderExtensionList(Collection<Long> ids); /** * 根据订单成功的 扩展订单ID 查询所有的扩展订单转 成 map 返回 * * @param successExtensionIdList 订单 ID 集合 * @return 订单扩展 map 集合 */ default Map<Long, PayOrderExtensionDO> getOrderExtensionMap(Collection<Long> successExtensionIdList) { List<PayOrderExtensionDO> list = getOrderExtensionList(successExtensionIdList); return CollectionUtils.convertMap(list, PayOrderExtensionDO::getId); } }
package tp_project.GoReplay; import java.sql.Date; import java.time.Instant; import tp_project.GoGame.GoBoard; import tp_project.GoGameDBObject.DBGoGames; import tp_project.GoGameDBObject.DBGoManager; import tp_project.GoGameDBObject.DBGoStatus; import tp_project.Server.Game; import tp_project.Server.GameManager; public class GoReplayGame implements Game { private GoReplayPlayer player; private boolean is_running; private GameManager manager; public GoReplayGame(GoReplayPlayer p1, GameManager manager) { player = p1; this.manager = manager; } @Override public void run() { is_running = true; manager.gameStated(); for (int i = 0; (!player.isReady()) && i < 10 * 3; i++) { //Wait for players max 3 secound player.update(); try { Thread.sleep(100); } catch (InterruptedException e) {} } player.yourMove(); while (is_running) { if (!player.update()) { end(); } try { Thread.sleep(100); } catch (InterruptedException e) { } } player.gameEnded(); manager.gameEnded(); } public DBGoGames getGames(Date date) { return DBGoManager.getInstance().getGames(Instant.ofEpochMilli(date.getTime())); } public void end() { is_running = false; } public DBGoStatus getStatus(Integer game_id) { return DBGoManager.getInstance().getStatus(game_id); } public GoBoard getBoard(Integer game_id, Integer round) { return DBGoManager.getInstance().getBoard(game_id, round); } }
/* Copyright 2012-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.snaker.designer.io.reader.impl; import java.util.List; import org.snaker.designer.config.Component; import org.snaker.designer.config.ConfigManager; import org.snaker.designer.config.Property; import org.snaker.designer.io.reader.AbstractXmlReader; import org.snaker.designer.model.BaseElement; import org.snaker.designer.model.Simple; import org.snaker.designer.utils.BeanUtil; import org.snaker.designer.utils.ClassUtils; import org.w3c.dom.Element; /** * 简单类型的xml读取 * @author yuqs * @version 1.0 */ public class SimpleReader extends AbstractXmlReader { @Override protected BaseElement newModel(Element element) { String nodeName = element.getNodeName(); Component component = ConfigManager.getComponentByName(nodeName); Object model = ClassUtils.newInstance(component.getClazz()); if(model == null) return new Simple(nodeName); return (BaseElement)model; } @Override protected void parseNode(BaseElement model, Element element) { Component component = ConfigManager.getComponentByModel(model); List<Property> props = component.getProperties(); try { for(Property prop : props) { if(BeanUtil.hasPropertyName(model, prop.getName())) { BeanUtil.setPropertyValue(model, prop.getName(), element.getAttribute(prop.getName())); } else { if(model instanceof Simple) { ((Simple)model).setAttribute(prop.getName(), element.getAttribute(prop.getName())); } } } } catch(Exception e) { e.printStackTrace(); } } }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package xyz.redtorch.gateway.ctp.x64v6v3v16t1v.api; public class CThostFtdcReqGenUserCaptchaField { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected CThostFtdcReqGenUserCaptchaField(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(CThostFtdcReqGenUserCaptchaField obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; jctpv6v3v16t1x64apiJNI.delete_CThostFtdcReqGenUserCaptchaField(swigCPtr); } swigCPtr = 0; } } public void setTradingDay(String value) { jctpv6v3v16t1x64apiJNI.CThostFtdcReqGenUserCaptchaField_TradingDay_set(swigCPtr, this, value); } public String getTradingDay() { return jctpv6v3v16t1x64apiJNI.CThostFtdcReqGenUserCaptchaField_TradingDay_get(swigCPtr, this); } public void setBrokerID(String value) { jctpv6v3v16t1x64apiJNI.CThostFtdcReqGenUserCaptchaField_BrokerID_set(swigCPtr, this, value); } public String getBrokerID() { return jctpv6v3v16t1x64apiJNI.CThostFtdcReqGenUserCaptchaField_BrokerID_get(swigCPtr, this); } public void setUserID(String value) { jctpv6v3v16t1x64apiJNI.CThostFtdcReqGenUserCaptchaField_UserID_set(swigCPtr, this, value); } public String getUserID() { return jctpv6v3v16t1x64apiJNI.CThostFtdcReqGenUserCaptchaField_UserID_get(swigCPtr, this); } public CThostFtdcReqGenUserCaptchaField() { this(jctpv6v3v16t1x64apiJNI.new_CThostFtdcReqGenUserCaptchaField(), true); } }
// Copyright 2015 The Bazel Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.syntax; import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.cmdline.Label; import java.util.IllegalFormatException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test properties of the evaluator's datatypes and utility functions * without actually creating any parse trees. */ @RunWith(JUnit4.class) public class PrinterTest { @Test public void testPrinter() throws Exception { // Note that prettyPrintValue and printValue only differ on behaviour of // labels and strings at toplevel. assertThat(Starlark.str(createObjWithStr())).isEqualTo("<str marker>"); assertThat(Starlark.repr(createObjWithStr())).isEqualTo("<repr marker>"); assertThat(Starlark.str("foo\nbar")).isEqualTo("foo\nbar"); assertThat(Starlark.repr("foo\nbar")).isEqualTo("\"foo\\nbar\""); assertThat(Starlark.str("'")).isEqualTo("'"); assertThat(Starlark.repr("'")).isEqualTo("\"'\""); assertThat(Starlark.str("\"")).isEqualTo("\""); assertThat(Starlark.repr("\"")).isEqualTo("\"\\\"\""); assertThat(Starlark.str(3)).isEqualTo("3"); assertThat(Starlark.repr(3)).isEqualTo("3"); assertThat(Starlark.repr(Starlark.NONE)).isEqualTo("None"); assertThat(Starlark.str(Label.parseAbsolute("//x", ImmutableMap.of()))).isEqualTo("//x:x"); assertThat(Starlark.repr(Label.parseAbsolute("//x", ImmutableMap.of()))) .isEqualTo("Label(\"//x:x\")"); List<?> list = StarlarkList.of(null, "foo", "bar"); List<?> tuple = Tuple.of("foo", "bar"); assertThat(Starlark.str(Tuple.of(1, list, 3))).isEqualTo("(1, [\"foo\", \"bar\"], 3)"); assertThat(Starlark.repr(Tuple.of(1, list, 3))).isEqualTo("(1, [\"foo\", \"bar\"], 3)"); assertThat(Starlark.str(StarlarkList.of(null, 1, tuple, 3))) .isEqualTo("[1, (\"foo\", \"bar\"), 3]"); assertThat(Starlark.repr(StarlarkList.of(null, 1, tuple, 3))) .isEqualTo("[1, (\"foo\", \"bar\"), 3]"); Map<Object, Object> dict = ImmutableMap.<Object, Object>of(1, tuple, 2, list, "foo", StarlarkList.of(null)); assertThat(Starlark.str(dict)) .isEqualTo("{1: (\"foo\", \"bar\"), 2: [\"foo\", \"bar\"], \"foo\": []}"); assertThat(Starlark.repr(dict)) .isEqualTo("{1: (\"foo\", \"bar\"), 2: [\"foo\", \"bar\"], \"foo\": []}"); } private void checkFormatPositionalFails(String errorMessage, String format, Object... arguments) { IllegalFormatException e = assertThrows(IllegalFormatException.class, () -> Starlark.format(format, arguments)); assertThat(e).hasMessageThat().isEqualTo(errorMessage); } @Test public void testOutputOrderOfMap() throws Exception { Map<Object, Object> map = new LinkedHashMap<>(); map.put(5, 5); map.put(3, 3); map.put("foo", 42); map.put(7, "bar"); assertThat(Starlark.str(map)).isEqualTo("{5: 5, 3: 3, \"foo\": 42, 7: \"bar\"}"); } @Test public void testFormatPositional() throws Exception { assertThat(Starlark.formatWithList("%s %d", Tuple.of("foo", 3))).isEqualTo("foo 3"); assertThat(Starlark.format("%s %d", "foo", 3)).isEqualTo("foo 3"); assertThat(Starlark.format("%s %s %s", 1, null, 3)).isEqualTo("1 null 3"); // Note: formatToString doesn't perform scalar x -> (x) conversion; // The %-operator is responsible for that. assertThat(Starlark.formatWithList("", Tuple.of())).isEmpty(); assertThat(Starlark.format("%s", "foo")).isEqualTo("foo"); assertThat(Starlark.format("%s", 3.14159)).isEqualTo("3.14159"); checkFormatPositionalFails("not all arguments converted during string formatting", "%s", 1, 2, 3); assertThat(Starlark.format("%%%s", "foo")).isEqualTo("%foo"); checkFormatPositionalFails("not all arguments converted during string formatting", "%%s", "foo"); checkFormatPositionalFails("unsupported format character \" \" at index 1 in \"% %s\"", "% %s", "foo"); assertThat(Starlark.format("%s", StarlarkList.of(null, 1, 2, 3))).isEqualTo("[1, 2, 3]"); assertThat(Starlark.format("%s", Tuple.of(1, 2, 3))).isEqualTo("(1, 2, 3)"); assertThat(Starlark.format("%s", StarlarkList.of(null))).isEqualTo("[]"); assertThat(Starlark.format("%s", Tuple.of())).isEqualTo("()"); assertThat(Starlark.format("%% %d %r %s", 1, "2", "3")).isEqualTo("% 1 \"2\" 3"); checkFormatPositionalFails( "invalid argument \"1\" for format pattern %d", "%d", "1"); checkFormatPositionalFails("unsupported format character \".\" at index 1 in \"%.3g\"", "%.3g"); checkFormatPositionalFails("unsupported format character \".\" at index 1 in \"%.3g\"", "%.3g", 1, 2); checkFormatPositionalFails("unsupported format character \".\" at index 1 in \"%.s\"", "%.s"); } @Test public void testPrettyPrinter() throws Exception { assertThat(Printer.getPrettyPrinter().repr(ImmutableList.of(1, 2, 3)).toString()) .isEqualTo( "[\n" + " 1,\n" + " 2,\n" + " 3\n" + "]"); assertThat(Printer.getPrettyPrinter().repr(ImmutableList.<String>of()).toString()) .isEqualTo("[]"); assertThat(Printer.getPrettyPrinter().repr(ImmutableList.of("foo")).toString()) .isEqualTo("[\n \"foo\"\n]"); assertThat( Printer.getPrettyPrinter() .repr(ImmutableMap.<Object, Object>of("foo", "bar", "baz", ImmutableList.of(1, 2))) .toString()) .isEqualTo( "{\n" + " \"foo\": \"bar\",\n" + " \"baz\": [\n" + " 1,\n" + " 2\n" + " ]\n" + "}"); assertThat( Printer.getPrettyPrinter() .repr(ImmutableMap.<Object, Object>of( "foo", "bar", "empty", ImmutableList.of(), "a", "b")) .toString()) .isEqualTo( "{\n" + " \"foo\": \"bar\",\n" + " \"empty\": [],\n" + " \"a\": \"b\"\n" + "}"); } private Printer makeSimplifiedFormatPrinter() { return new Printer.BasePrinter(new StringBuilder(), /*simplifiedFormatStrings=*/ true); } @Test public void testSimplifiedDisallowsPlaceholdersBesidesPercentS() { assertThat(makeSimplifiedFormatPrinter().format("Allowed: %%").toString()) .isEqualTo("Allowed: %"); assertThat(makeSimplifiedFormatPrinter().format("Allowed: %s", "abc").toString()) .isEqualTo("Allowed: abc"); assertThrows( IllegalFormatException.class, () -> makeSimplifiedFormatPrinter().format("Disallowed: %r", "abc")); assertThrows( IllegalFormatException.class, () -> makeSimplifiedFormatPrinter().format("Disallowed: %d", 5)); } private StarlarkValue createObjWithStr() { return new StarlarkValue() { @Override public void repr(Printer printer) { printer.append("<repr marker>"); } @Override public void str(Printer printer) { printer.append("<str marker>"); } }; } }
package com.example.mario.whiteboard; import android.graphics.Color; import android.graphics.PointF; import android.graphics.PorterDuff; import android.view.View; import android.content.Context; import android.util.AttributeSet; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.view.MotionEvent; import android.widget.EditText; import org.json.JSONArray; import org.json.JSONObject; public class PaintView extends View { private Bitmap bitmap; private static Canvas canvas; private Path penPath; private Paint penPaint; private Paint canvasPaint; private ChatClient client; private int X, Y, oldX, oldY; String name; public PaintView(Context context, AttributeSet attributeSet) { super(context, attributeSet); setupPainting(); } public void sendClear(){ client.send("C"); } public void setClient(String name){ client = new ChatClient(this); client.startConnection(name); } public void clearCanvas() { this.canvas.drawColor(0, PorterDuff.Mode.CLEAR); invalidate(); } /* public void paintPoint(Integer x, Integer y) { this.canvas.drawPoint(x, y, this.otherPaint); invalidate(); }*/ protected void setupPainting() { this.bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); this.canvas = new Canvas(bitmap); this.penPath = new Path(); this.penPaint = new Paint(); this.penPaint.setColor(-16728065); this.penPaint.setAntiAlias(true); this.penPaint.setStrokeWidth(15); this.penPaint.setStyle(Paint.Style.STROKE); this.penPaint.setStrokeJoin(Paint.Join.ROUND); this.penPaint.setStrokeCap(Paint.Cap.ROUND); this.canvasPaint = new Paint(Paint.DITHER_FLAG); } @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { super.onSizeChanged(width, height, oldWidth, oldHeight); this.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); this.canvas = new Canvas(bitmap); } @Override protected void onDraw(Canvas cvs) { cvs.drawBitmap(bitmap, 0, 0, canvasPaint); cvs.drawPath(penPath, penPaint); } @Override public boolean onTouchEvent(MotionEvent event) { PointF touchPoint = new PointF(); touchPoint.set(event.getX(), event.getY()); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: oldX = Math.round(touchPoint.x); oldY = Math.round(touchPoint.y); this.penPath.moveTo(oldX, oldY); break; case MotionEvent.ACTION_MOVE: this.penPath.lineTo(touchPoint.x, touchPoint.y); X = Math.round(touchPoint.x); Y = Math.round(touchPoint.y); String color = "N"; System.out.println(penPaint.getColor()); switch (penPaint.getColor()) { case -12799119: color = "G"; break; case -38476: color = "M"; break; case -16777216: color = "N"; break; case -16728065: color = "B"; break; case -1824728: color = "R"; break; default: color = "N"; case Color.WHITE: color = "E"; break; } Line l = new Line(color, true); l.addPoint(oldX, oldY); l.addPoint(X,Y); this.client.send(l.LineToString()); oldX=X; oldY=Y; break; case MotionEvent.ACTION_UP: this.canvas.drawPath(penPath, penPaint); this.penPath.reset(); break; default: return false; } invalidate(); return true; } public void changeColor(int newColor){ this.penPaint.setColor(newColor); } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public void setEraser(){ this.penPaint.setColor(Color.WHITE); } public void canvasThicknessChange(int thickness){ this.penPaint.setStrokeWidth(thickness); } public String getName() { return name; } public void drawLine(String line_s) { Line l = new Line(line_s, false); int x1, y1, x2, y2; int color = 0; switch (l.getColor()){ case "N": color = -16777216; break; case "G": color = -12799119; break; case "B": color = -16728065; break; case "M": color = -38476; break; case "R": color = -1824728; break; case"E": color = Color.WHITE; } penPaint.setColor(color); x1 = l.getPoints().get(0).a; y1 = l.getPoints().get(0).b; x2 = l.getPoints().get(1).a; y2 = l.getPoints().get(1).b; canvas.drawLine(x1, y1, x2, y2, penPaint); super.invalidate(); } }
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.domain.IpAddrLbsInfo; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.security.data.info.ipaddrinfo.query response. * * @author auto create * @since 1.0, 2019-01-07 20:51:15 */ public class AlipaySecurityDataInfoIpaddrinfoQueryResponse extends AlipayResponse { private static final long serialVersionUID = 8247547448884365589L; /** * ip_addr_lbs_info:IP地址归属地对象。其中province为IP地址归属地的省,city为IP地址归属地的城市 */ @ApiField("ip_addr_lbs_info") private IpAddrLbsInfo ipAddrLbsInfo; public void setIpAddrLbsInfo(IpAddrLbsInfo ipAddrLbsInfo) { this.ipAddrLbsInfo = ipAddrLbsInfo; } public IpAddrLbsInfo getIpAddrLbsInfo( ) { return this.ipAddrLbsInfo; } }
package com.ddphin.rabbitmq.entity; import com.alibaba.fastjson.JSONObject; import lombok.Data; import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.util.Assert; /** * CorrelationDataMQ * * @Date 2019/8/20 下午7:49 * @Author ddphin */ @Data public class CorrelationDataMQ extends CorrelationData { private String id; private String data; private String clazz; private Integer retry; private String exchange; private String routingKey; private Integer millis; public CorrelationDataMQ() {} public CorrelationDataMQ(String exchange, String routingKey, Integer millis, final Object message, String id) { Assert.notNull(id, "id 消息体不能为NULL"); Assert.notNull(message, "message 消息体不能为NULL"); Assert.notNull(exchange, "exchange 不能为NULL"); Assert.notNull(routingKey, "routingKey 不能为NULL"); this.id = id; this.data = JSONObject.toJSONString(message); this.clazz = message.getClass().getName(); this.retry = 0; this.exchange = exchange; this.routingKey = routingKey; this.millis = millis; } public CorrelationDataMQ retry() { ++this.retry; return this; } }
/** * Copyright 2016 Yahoo Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.bookkeeper.mledger.impl; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.locks.StampedLock; import org.apache.bookkeeper.mledger.ManagedCursor; import org.apache.bookkeeper.mledger.Position; import org.apache.bookkeeper.mledger.util.Pair; import com.google.common.collect.Lists; /** * Contains all the cursors for a ManagedLedger. * * The goal is to always know the slowest consumer and hence decide which is the oldest ledger we need to keep. * * This data structure maintains a list and a map of cursors. The map is used to relate a cursor name with an entry in * the linked-list. The list is a sorted double linked-list of cursors. * * When a cursor is markDeleted, this list is updated and the cursor is moved in its new position. * * To minimize the moving around, the order is maintained using the ledgerId, but not the entryId, since we only care * about ledgers to be deleted. * */ class ManagedCursorContainer implements Iterable<ManagedCursor> { private static class Item { final ManagedCursor cursor; PositionImpl position; int idx; Item(ManagedCursor cursor, int idx) { this.cursor = cursor; this.position = (PositionImpl) cursor.getMarkDeletedPosition(); this.idx = idx; } } private final ArrayList<Item> heap = Lists.newArrayList(); // Maps a cursor to its position in the heap private final ConcurrentMap<String, Item> cursors = new ConcurrentSkipListMap<String, Item>(); private final StampedLock rwLock = new StampedLock(); public void add(ManagedCursor cursor) { long stamp = rwLock.writeLock(); try { // Append a new entry at the end of the list Item item = new Item(cursor, heap.size()); cursors.put(cursor.getName(), item); heap.add(item); siftUp(item); } finally { rwLock.unlockWrite(stamp); } } public ManagedCursor get(String name) { long stamp = rwLock.readLock(); try { Item item = cursors.get(name); return item != null ? item.cursor : null; } finally { rwLock.unlockRead(stamp); } } public void removeCursor(String name) { long stamp = rwLock.writeLock(); try { Item item = cursors.remove(name); // Move the item to the right end of the heap to be removed Item lastItem = heap.get(heap.size() - 1); swap(item, lastItem); heap.remove(item.idx); // Update the heap siftDown(lastItem); } finally { rwLock.unlockWrite(stamp); } } /** * Signal that a cursor position has been updated and that the container must re-order the cursor list. * * @param cursor * @return a pair of positions, representing the previous slowest consumer and the new slowest consumer (after the * update). */ public Pair<PositionImpl, PositionImpl> cursorUpdated(ManagedCursor cursor, Position newPosition) { checkNotNull(cursor); long stamp = rwLock.writeLock(); try { Item item = cursors.get(cursor.getName()); if (item == null) { return null; } PositionImpl previousSlowestConsumer = heap.get(0).position; // When the cursor moves forward, we need to push it toward the // bottom of the tree and push it up if a reset was done item.position = (PositionImpl) newPosition; if (item.idx == 0 || getParent(item).position.compareTo(item.position) <= 0) { siftDown(item); } else { siftUp(item); } PositionImpl newSlowestConsumer = heap.get(0).position; return Pair.create(previousSlowestConsumer, newSlowestConsumer); } finally { rwLock.unlockWrite(stamp); } } /** * Get the slowest reader position, meaning older acknowledged position between all the cursors. * * @return the slowest reader position */ public PositionImpl getSlowestReaderPosition() { long stamp = rwLock.readLock(); try { return heap.isEmpty() ? null : heap.get(0).position; } finally { rwLock.unlockRead(stamp); } } public ManagedCursor getSlowestReader() { long stamp = rwLock.readLock(); try { return heap.isEmpty() ? null : heap.get(0).cursor; } finally { rwLock.unlockRead(stamp); } } public boolean isEmpty() { long stamp = rwLock.tryOptimisticRead(); boolean isEmpty = heap.isEmpty(); if (!rwLock.validate(stamp)) { // Fallback to read lock stamp = rwLock.readLock(); try { isEmpty = heap.isEmpty(); } finally { rwLock.unlockRead(stamp); } } return isEmpty; } @Override public String toString() { long stamp = rwLock.readLock(); try { StringBuilder sb = new StringBuilder(); sb.append('['); boolean first = true; for (Item item : cursors.values()) { if (!first) { sb.append(", "); } first = false; sb.append(item.cursor); } sb.append(']'); return sb.toString(); } finally { rwLock.unlockRead(stamp); } } @Override public Iterator<ManagedCursor> iterator() { final Iterator<Map.Entry<String, Item>> it = cursors.entrySet().iterator(); return new Iterator<ManagedCursor>() { @Override public boolean hasNext() { return it.hasNext(); } @Override public ManagedCursor next() { return it.next().getValue().cursor; } @Override public void remove() { throw new IllegalArgumentException("Cannot remove ManagedCursor form container"); } }; } // ////////////////////// /** * Push the item up towards the the root of the tree (lowest reading position) */ private void siftUp(Item item) { Item parent = getParent(item); while (item.idx > 0 && parent.position.compareTo(item.position) > 0) { swap(item, parent); parent = getParent(item); } } /** * Push the item down towards the bottom of the tree (highest reading position) */ private void siftDown(final Item item) { while (true) { Item j = null; Item right = getRight(item); if (right != null && right.position.compareTo(item.position) < 0) { Item left = getLeft(item); if (left.position.compareTo(right.position) < 0) { j = left; } else { j = right; } } else { Item left = getLeft(item); if (left != null && left.position.compareTo(item.position) < 0) { j = left; } } if (j != null) { swap(item, j); } else { break; } } } /** * Swap two items in the heap */ private void swap(Item item1, Item item2) { int idx1 = item1.idx; int idx2 = item2.idx; heap.set(idx2, item1); heap.set(idx1, item2); // Update the indexes too item1.idx = idx2; item2.idx = idx1; } private Item getParent(Item item) { return heap.get((item.idx - 1) / 2); } private Item getLeft(Item item) { int i = item.idx * 2 + 1; return i < heap.size() ? heap.get(i) : null; } private Item getRight(Item item) { int i = item.idx * 2 + 2; return i < heap.size() ? heap.get(i) : null; } }
package com.zahid.template; public class TransferMoney extends Task{ @Override protected void doExecute() { System.out.println("transfer money"); } }
package top.imyzt.itcase.day19; import java.io.File; import cn.hutool.core.lang.Console; /** * 将制定目录下的所有jpg图片绝对路径打印到控制台 * @author imyzt * @email imyzt01@gmail.com * @date 2018年4月25日 下午4:48:45 */ public class Demo04_FileCase { public static void main(String[] args) { File dir = new File("D:\\"); dir(dir); } private static void dir(File dir) { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { if (!file.isHidden()) { dir(file); } }else if (file.isFile()) { String name = file.getName(); if (name.endsWith(".jpg")) { Console.log(file.getAbsolutePath()); } } } } }
/* * Copyright 2016-2020 Crown Copyright * * 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 uk.gov.gchq.gaffer.store.operation.handler; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.gov.gchq.gaffer.commonutil.CollectionUtil; import uk.gov.gchq.gaffer.named.operation.NamedOperation; import uk.gov.gchq.gaffer.operation.Operation; import uk.gov.gchq.gaffer.operation.OperationException; import uk.gov.gchq.gaffer.operation.Operations; import uk.gov.gchq.gaffer.operation.impl.If; import uk.gov.gchq.gaffer.operation.impl.ScoreOperationChain; import uk.gov.gchq.gaffer.operation.impl.While; import uk.gov.gchq.gaffer.store.Context; import uk.gov.gchq.gaffer.store.Store; import uk.gov.gchq.gaffer.store.operation.resolver.DefaultScoreResolver; import uk.gov.gchq.gaffer.store.operation.resolver.IfScoreResolver; import uk.gov.gchq.gaffer.store.operation.resolver.ScoreResolver; import uk.gov.gchq.gaffer.store.operation.resolver.WhileScoreResolver; import uk.gov.gchq.gaffer.store.operation.resolver.named.NamedOperationScoreResolver; import uk.gov.gchq.gaffer.user.User; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Operation Handler for ScoreOperationChain */ public class ScoreOperationChainHandler implements OutputOperationHandler<ScoreOperationChain, Integer> { private static final Logger LOGGER = LoggerFactory.getLogger(ScoreOperationChainHandler.class); private final LinkedHashMap<Class<? extends Operation>, Integer> opScores = new LinkedHashMap<>(); private final Map<String, Integer> authScores = new HashMap<>(); private final Map<Class<? extends Operation>, ScoreResolver> scoreResolvers = new HashMap<>(); private final ScoreResolver<Operation> defaultScoreResolver = new DefaultScoreResolver( Collections.unmodifiableMap(opScores), Collections.unmodifiableMap(scoreResolvers) ); private static final Map<Class<? extends Operation>, ScoreResolver> DEFAULT_SCORE_RESOLVERS = addDefaultScoreResolvers(); /** * Returns the OperationChainLimiter score for the OperationChain provided. * * @param operation the {@link uk.gov.gchq.gaffer.operation.Operation} to be executed * @param context the operation chain context, containing the user who executed the operation * @param store the {@link Store} the operation should be run on * @return an Integer containing the score * @throws OperationException thrown if the property keys have not been set */ @Override public Integer doOperation(final ScoreOperationChain operation, final Context context, final Store store) throws OperationException { return getChainScore(operation.getOperationChain(), context.getUser()); } public int getChainScore(final Operations<?> operations, final User user) { return defaultScoreResolver.getScore((Operation) operations, defaultScoreResolver); } /** * Iterates through each of the users operation authorisations listed in the config file and returns the highest score * associated with those auths. * <p> * Defaults to 0. * </p> * * @param opAuths a set of operation authorisations * @return maxUserScore the highest score associated with any of the supplied user auths */ public int getMaxUserAuthScore(final Set<String> opAuths) { Integer maxUserScore = 0; for (final String opAuth : opAuths) { Integer authScore = authScores.get(opAuth); if (null != authScore) { if (authScore > maxUserScore) { maxUserScore = authScore; } } } LOGGER.debug("Returning users max operation chain limit score of {}", maxUserScore); return maxUserScore; } @JsonIgnore public Map<Class<? extends Operation>, Integer> getOpScores() { return Collections.unmodifiableMap(opScores); } @JsonIgnore public void setOpScores(final Map<Class<? extends Operation>, Integer> opScores) { this.opScores.clear(); if (null != opScores) { this.opScores.putAll(opScores); } validateOpScores(); } @JsonGetter("opScores") public Map<String, Integer> getOpScoresAsStrings() { final Map<String, Integer> opScoresAsNames = new LinkedHashMap<>(opScores.size()); CollectionUtil.toMapWithStringKeys(opScores, opScoresAsNames); return Collections.unmodifiableMap(opScoresAsNames); } @JsonSetter("opScores") public void setOpScoresFromStrings(final Map<String, Integer> opScores) throws ClassNotFoundException { this.opScores.clear(); CollectionUtil.toMapWithClassKeys(opScores, this.opScores); validateOpScores(); } public Map<String, Integer> getAuthScores() { return Collections.unmodifiableMap(authScores); } public void setAuthScores(final Map<String, Integer> authScores) { this.authScores.clear(); if (null != authScores) { this.authScores.putAll(authScores); } } public Map<Class<? extends Operation>, ScoreResolver> getScoreResolvers() { return Collections.unmodifiableMap(scoreResolvers); } public void setScoreResolvers(final Map<Class<? extends Operation>, ScoreResolver> resolvers) { this.scoreResolvers.clear(); scoreResolvers.putAll(DEFAULT_SCORE_RESOLVERS); if (null != resolvers) { this.scoreResolvers.putAll(resolvers); } } public void validateOpScores() { final List<Class<? extends Operation>> ops = new ArrayList<>(opScores.keySet()); int i = 0; for (final Class<? extends Operation> op : ops) { for (int j = 0; j < i; j++) { if (op.isAssignableFrom(ops.get(j))) { throw new IllegalArgumentException( "Operation scores are configured incorrectly. " + " The operation " + op.getSimpleName() + " is a parent operation of " + ops.get(j).getSimpleName() + " so the score of " + ops.get(j).getSimpleName() + " can never be accessed." ); } } i++; } } /** * Adds Gaffer's native {@link ScoreResolver} implementations to the list of available <code>ScoreResolver</code>s. * Any new implementations should be added to the map in this method, along with their respective class. * * @return a map of Operation class to ScoreResolver implementation */ private static Map<Class<? extends Operation>, ScoreResolver> addDefaultScoreResolvers() { final Map<Class<? extends Operation>, ScoreResolver> defaultResolvers = new HashMap<>(); defaultResolvers.put(NamedOperation.class, new NamedOperationScoreResolver()); defaultResolvers.put(If.class, new IfScoreResolver()); defaultResolvers.put(While.class, new WhileScoreResolver()); return Collections.unmodifiableMap(defaultResolvers); } public static Map<Class<? extends Operation>, ScoreResolver> getDefaultScoreResolvers() { return Collections.unmodifiableMap(DEFAULT_SCORE_RESOLVERS); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/ad_group_service.proto package com.google.ads.googleads.v9.services; public interface GetAdGroupRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v9.services.GetAdGroupRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. The resource name of the ad group to fetch. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Required. The resource name of the ad group to fetch. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); }
/* * Copyright 2014-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.core.impl; import org.onlab.metrics.MetricsService; import org.onlab.util.SharedExecutors; import org.onlab.util.SharedScheduledExecutors; import org.onlab.util.Tools; import org.onosproject.app.ApplicationIdStore; import org.onosproject.app.ApplicationService; import org.onosproject.cfg.ComponentConfigService; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.core.IdBlockStore; import org.onosproject.core.IdGenerator; import org.onosproject.core.Version; import org.onosproject.core.VersionService; import org.onosproject.event.EventDeliveryService; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Dictionary; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.net.OsgiPropertyConstants.CALCULATE_PERFORMANCE_CHECK; import static org.onosproject.net.OsgiPropertyConstants.CALCULATE_PERFORMANCE_CHECK_DEFAULT; import static org.onosproject.net.OsgiPropertyConstants.MAX_EVENT_TIME_LIMIT; import static org.onosproject.net.OsgiPropertyConstants.MAX_EVENT_TIME_LIMIT_DEFAULT; import static org.onosproject.net.OsgiPropertyConstants.SHARED_THREAD_POOL_SIZE; import static org.onosproject.net.OsgiPropertyConstants.SHARED_THREAD_POOL_SIZE_DEFAULT; import static org.onosproject.security.AppGuard.checkPermission; import static org.onosproject.security.AppPermission.Type.APP_READ; import static org.onosproject.security.AppPermission.Type.APP_WRITE; /** * Core service implementation. */ @Component( immediate = true, service = CoreService.class, property = { SHARED_THREAD_POOL_SIZE + ":Integer=" + SHARED_THREAD_POOL_SIZE_DEFAULT, MAX_EVENT_TIME_LIMIT + ":Integer=" + MAX_EVENT_TIME_LIMIT_DEFAULT, CALCULATE_PERFORMANCE_CHECK + ":Boolean=" + CALCULATE_PERFORMANCE_CHECK_DEFAULT } ) public class CoreManager implements CoreService { private final Logger log = LoggerFactory.getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY) protected VersionService versionService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected ApplicationIdStore applicationIdStore; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected IdBlockStore idBlockStore; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected ApplicationService appService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected ComponentConfigService cfgService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected EventDeliveryService eventDeliveryService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected MetricsService metricsService; /** Configure shared pool maximum size. */ private int sharedThreadPoolSize = SHARED_THREAD_POOL_SIZE_DEFAULT; /** Maximum number of millis an event sink has to process an event. */ private int maxEventTimeLimit = MAX_EVENT_TIME_LIMIT_DEFAULT; /** Enable queue performance check on shared pool. */ private boolean calculatePoolPerformance = CALCULATE_PERFORMANCE_CHECK_DEFAULT; @Activate protected void activate() { registerApplication(CORE_APP_NAME); cfgService.registerProperties(getClass()); } @Deactivate protected void deactivate() { cfgService.unregisterProperties(getClass(), false); SharedExecutors.shutdown(); SharedScheduledExecutors.shutdown(); } @Override public Version version() { checkPermission(APP_READ); return versionService.version(); } @Override public Set<ApplicationId> getAppIds() { checkPermission(APP_READ); return applicationIdStore.getAppIds(); } @Override public ApplicationId getAppId(Short id) { checkPermission(APP_READ); return applicationIdStore.getAppId(id); } @Override public ApplicationId getAppId(String name) { checkPermission(APP_READ); return applicationIdStore.getAppId(name); } @Override public ApplicationId registerApplication(String name) { checkPermission(APP_WRITE); checkNotNull(name, "Application ID cannot be null"); return applicationIdStore.registerApplication(name); } @Override public ApplicationId registerApplication(String name, Runnable preDeactivate) { checkPermission(APP_WRITE); ApplicationId id = registerApplication(name); appService.registerDeactivateHook(id, preDeactivate); return id; } @Override public IdGenerator getIdGenerator(String topic) { checkPermission(APP_READ); IdBlockAllocator allocator = new StoreBasedIdBlockAllocator(topic, idBlockStore); return new BlockAllocatorBasedIdGenerator(allocator); } @Modified protected void modified(ComponentContext context) { Dictionary<?, ?> properties = context.getProperties(); Integer poolSize = Tools.getIntegerProperty(properties, SHARED_THREAD_POOL_SIZE); if (poolSize != null && poolSize > 1) { sharedThreadPoolSize = poolSize; SharedExecutors.setPoolSize(sharedThreadPoolSize); } else if (poolSize != null) { log.warn("sharedThreadPoolSize must be greater than 1"); } Integer timeLimit = Tools.getIntegerProperty(properties, MAX_EVENT_TIME_LIMIT); if (timeLimit != null && timeLimit >= 0) { maxEventTimeLimit = timeLimit; eventDeliveryService.setDispatchTimeLimit(maxEventTimeLimit); } else if (timeLimit != null) { log.warn("maxEventTimeLimit must be greater than or equal to 0"); } Boolean performanceCheck = Tools.isPropertyEnabled(properties, CALCULATE_PERFORMANCE_CHECK); if (performanceCheck != null) { calculatePoolPerformance = performanceCheck; SharedExecutors.setMetricsService(calculatePoolPerformance ? metricsService : null); } log.info("Settings: sharedThreadPoolSize={}, maxEventTimeLimit={}, calculatePoolPerformance={}", sharedThreadPoolSize, maxEventTimeLimit, calculatePoolPerformance); } }
/* * 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.druid.query.aggregation.datasketches.quantiles; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import org.apache.datasketches.quantiles.DoublesSketch; import org.apache.druid.java.util.common.IAE; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.AggregatorUtil; import org.apache.druid.query.aggregation.PostAggregator; import org.apache.druid.query.cache.CacheKeyBuilder; import org.apache.druid.segment.ColumnInspector; import org.apache.druid.segment.column.ColumnType; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Set; public class DoublesSketchToHistogramPostAggregator implements PostAggregator { static final int DEFAULT_NUM_BINS = 10; private final String name; private final PostAggregator field; private final double[] splitPoints; private final Integer numBins; @JsonCreator public DoublesSketchToHistogramPostAggregator( @JsonProperty("name") final String name, @JsonProperty("field") final PostAggregator field, @JsonProperty("splitPoints") @Nullable final double[] splitPoints, @JsonProperty("numBins") @Nullable final Integer numBins) { this.name = Preconditions.checkNotNull(name, "name is null"); this.field = Preconditions.checkNotNull(field, "field is null"); this.splitPoints = splitPoints; this.numBins = numBins; if (splitPoints != null && numBins != null) { throw new IAE("Cannot accept both 'splitPoints' and 'numBins'"); } } @Override public Object compute(final Map<String, Object> combinedAggregators) { final DoublesSketch sketch = (DoublesSketch) field.compute(combinedAggregators); final int numBins = splitPoints != null ? splitPoints.length + 1 : (this.numBins != null ? this.numBins.intValue() : DEFAULT_NUM_BINS); if (numBins < 2) { throw new IAE("at least 2 bins expected"); } if (sketch.isEmpty()) { final double[] histogram = new double[numBins]; Arrays.fill(histogram, Double.NaN); return histogram; } final double[] histogram = sketch.getPMF(splitPoints != null ? splitPoints : equallySpacedPoints(numBins, sketch.getMinValue(), sketch.getMaxValue())); for (int i = 0; i < histogram.length; i++) { histogram[i] *= sketch.getN(); // scale fractions to counts } return histogram; } // retuns num-1 points that split the interval [min, max] into num equally-spaced intervals // num must be at least 2 private static double[] equallySpacedPoints(final int num, final double min, final double max) { final double[] points = new double[num - 1]; final double delta = (max - min) / num; for (int i = 0; i < num - 1; i++) { points[i] = min + delta * (i + 1); } return points; } @Override @JsonProperty public String getName() { return name; } /** * actual type is {@link DoublesSketch} * @param signature */ @Override public ColumnType getType(ColumnInspector signature) { return ColumnType.DOUBLE_ARRAY; } @JsonProperty public PostAggregator getField() { return field; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) public double[] getSplitPoints() { return splitPoints; } @JsonProperty @JsonInclude(JsonInclude.Include.NON_NULL) public Integer getNumBins() { return numBins; } @Override public Comparator<double[]> getComparator() { throw new IAE("Comparing histograms is not supported"); } @Override public Set<String> getDependentFields() { return field.getDependentFields(); } @Override public String toString() { return getClass().getSimpleName() + "{" + "name='" + name + '\'' + ", field=" + field + ", splitPoints=" + Arrays.toString(splitPoints) + ", numBins=" + numBins + "}"; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final DoublesSketchToHistogramPostAggregator that = (DoublesSketchToHistogramPostAggregator) o; if (!name.equals(that.name)) { return false; } if (!Arrays.equals(splitPoints, that.splitPoints)) { return false; } if (!field.equals(that.field)) { return false; } if (numBins == null && that.numBins == null) { return true; } if (numBins != null && numBins.equals(that.numBins)) { return true; } return false; } @Override public int hashCode() { int hashCode = name.hashCode() * 31 + field.hashCode(); hashCode = hashCode * 31 + Arrays.hashCode(splitPoints); if (numBins != null) { hashCode = hashCode * 31 + numBins.hashCode(); } return hashCode; } @Override public byte[] getCacheKey() { final CacheKeyBuilder builder = new CacheKeyBuilder( AggregatorUtil.QUANTILES_DOUBLES_SKETCH_TO_HISTOGRAM_CACHE_TYPE_ID).appendCacheable(field); if (splitPoints != null) { for (final double value : splitPoints) { builder.appendDouble(value); } } if (numBins != null) { builder.appendInt(numBins); } return builder.build(); } @Override public PostAggregator decorate(final Map<String, AggregatorFactory> map) { return this; } }
package org.ksam.model.planData; import java.util.List; import java.util.Map; import org.ksam.model.adaptation.AlertType; public class PlanAlert { private String systemId; private AlertType alertType; private Map<String, List<String>> affectedVarsAlternativeMons; public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public AlertType getAlertType() { return alertType; } public void setAlertType(AlertType alertType) { this.alertType = alertType; } public Map<String, List<String>> getAffectedVarsAlternativeMons() { return affectedVarsAlternativeMons; } public void setAffectedVarsAlternativeMons(Map<String, List<String>> affectedVarsAlternativeMons) { this.affectedVarsAlternativeMons = affectedVarsAlternativeMons; } }
package org.egov.waterconnection.repository; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.validation.Valid; import org.apache.commons.lang3.StringUtils; import org.egov.common.contract.request.RequestInfo; import org.egov.common.contract.request.Role; import org.egov.common.contract.request.User; import org.egov.tracer.model.CustomException; import org.egov.waterconnection.config.WSConfiguration; import org.egov.waterconnection.constants.WCConstants; import org.egov.waterconnection.producer.WaterConnectionProducer; import org.egov.waterconnection.repository.builder.WsQueryBuilder; import org.egov.waterconnection.repository.rowmapper.BillingCycleRowMapper; import org.egov.waterconnection.repository.rowmapper.FeedbackRowMapper; import org.egov.waterconnection.repository.rowmapper.OpenWaterRowMapper; import org.egov.waterconnection.repository.rowmapper.WaterRowMapper; import org.egov.waterconnection.web.models.BillingCycle; import org.egov.waterconnection.web.models.Feedback; import org.egov.waterconnection.web.models.FeedbackSearchCriteria; import org.egov.waterconnection.web.models.SearchCriteria; import org.egov.waterconnection.web.models.WaterConnection; import org.egov.waterconnection.web.models.WaterConnectionRequest; import org.egov.waterconnection.web.models.WaterConnectionResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SingleColumnRowMapper; import org.springframework.stereotype.Repository; import org.springframework.util.CollectionUtils; import lombok.extern.slf4j.Slf4j; @Slf4j @Repository public class WaterDaoImpl implements WaterDao { @Autowired private WaterConnectionProducer waterConnectionProducer; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private WsQueryBuilder wsQueryBuilder; @Autowired private WaterRowMapper waterRowMapper; @Autowired private OpenWaterRowMapper openWaterRowMapper; @Autowired private WSConfiguration wsConfiguration; @Value("${egov.waterservice.createwaterconnection.topic}") private String createWaterConnection; @Value("${egov.waterservice.updatewaterconnection.topic}") private String updateWaterConnection; @Autowired private BillingCycleRowMapper billingCycleRowMapper; @Autowired private FeedbackRowMapper feedbackRowMapper; @Override public void saveWaterConnection(WaterConnectionRequest waterConnectionRequest) { waterConnectionProducer.push(createWaterConnection, waterConnectionRequest); } @Override public WaterConnectionResponse getWaterConnectionList(SearchCriteria criteria, RequestInfo requestInfo) { List<WaterConnection> waterConnectionList = new ArrayList<>(); List<Object> preparedStatement = new ArrayList<>(); Map<String, Long> collectionDataCount = null; List<Map<String, Object>> countData = null; Boolean flag = null; Set<String> consumerCodeSet = null; if(criteria.getFromDate() != null && criteria.getToDate() != null) { StringBuilder demandDetailsQuery = new StringBuilder(wsQueryBuilder.DEMAND_DETAILS); demandDetailsQuery.append(" and d.taxperiodto between " + criteria.getFromDate() + " AND " + criteria.getToDate()); List<String> consumerCodeList = jdbcTemplate.queryForList(demandDetailsQuery.toString(), String.class); if(!CollectionUtils.isEmpty(consumerCodeList)) { consumerCodeSet = consumerCodeList.stream().collect(Collectors.toSet()); } criteria.setConnectionNumberSet(consumerCodeSet); } String query = wsQueryBuilder.getSearchQueryString(criteria, preparedStatement, requestInfo); if (query == null) return null; if(criteria.getIsCollectionCount() != null && criteria.getIsCollectionCount()) { List<Object> preparedStmntforCollectionDataCount = new ArrayList<>(); StringBuilder collectionDataCountQuery = new StringBuilder(wsQueryBuilder.COLLECTION_DATA_COUNT); criteria.setIsCollectionDataCount(Boolean.TRUE); collectionDataCountQuery = wsQueryBuilder.applyFilters(collectionDataCountQuery, preparedStmntforCollectionDataCount, criteria); collectionDataCountQuery.append(" ORDER BY wc.appCreatedDate DESC"); countData = jdbcTemplate.queryForList(collectionDataCountQuery.toString(), preparedStmntforCollectionDataCount.toArray()); if(criteria.getIsBillPaid() != null) flag = criteria.getIsBillPaid(); } Boolean isOpenSearch = isSearchOpen(requestInfo.getUserInfo()); WaterConnectionResponse connectionResponse = new WaterConnectionResponse(); if (isOpenSearch) { waterConnectionList = jdbcTemplate.query(query, preparedStatement.toArray(), openWaterRowMapper); connectionResponse = WaterConnectionResponse.builder().waterConnection(waterConnectionList) .totalCount(openWaterRowMapper.getFull_count()).build(); } else { waterConnectionList = jdbcTemplate.query(query, preparedStatement.toArray(), waterRowMapper); Map<String, Object> counter = new HashMap(); if (criteria.getIsPropertyCount()!= null && criteria.getIsPropertyCount()) { List<Object> preparedStmnt = new ArrayList<>(); StringBuilder propertyQuery = new StringBuilder(wsQueryBuilder.PROPERTY_COUNT); propertyQuery = wsQueryBuilder.applyFilters(propertyQuery, preparedStmnt, criteria); propertyQuery.append("GROUP BY additionaldetails->>'propertyType'"); List<Map<String, Object>> data = jdbcTemplate.queryForList(propertyQuery.toString(), preparedStmnt.toArray()); for (Map<String, Object> map : data) { if(map.get("propertytype")!=null) { counter.put(map.get("propertytype").toString(), map.get("count").toString()) ; } } } collectionDataCount = getCollectionDataCounter(countData, flag); connectionResponse = WaterConnectionResponse.builder().waterConnection(waterConnectionList) .totalCount(waterRowMapper.getFull_count()).collectionDataCount(collectionDataCount).propertyCount(counter).build(); } return connectionResponse; } @Override public void updateWaterConnection(WaterConnectionRequest waterConnectionRequest, boolean isStateUpdatable) { if (isStateUpdatable) { waterConnectionProducer.push(updateWaterConnection, waterConnectionRequest); } else { waterConnectionProducer.push(wsConfiguration.getWorkFlowUpdateTopic(), waterConnectionRequest); } } /** * push object to create meter reading * * @param waterConnectionRequest */ public void postForMeterReading(WaterConnectionRequest waterConnectionRequest) { log.info("Posting request to kafka topic - " + wsConfiguration.getCreateMeterReading()); waterConnectionProducer.push(wsConfiguration.getCreateMeterReading(), waterConnectionRequest); } /** * push object for edit notification * * @param waterConnectionRequest */ public void pushForEditNotification(WaterConnectionRequest waterConnectionRequest) { if (!WCConstants.EDIT_NOTIFICATION_STATE .contains(waterConnectionRequest.getWaterConnection().getProcessInstance().getAction())) { waterConnectionProducer.push(wsConfiguration.getEditNotificationTopic(), waterConnectionRequest); } } /** * Enrich file store Id's * * @param waterConnectionRequest */ public void enrichFileStoreIds(WaterConnectionRequest waterConnectionRequest) { waterConnectionProducer.push(wsConfiguration.getFileStoreIdsTopic(), waterConnectionRequest); } /** * Save file store Id's * * @param waterConnectionRequest */ public void saveFileStoreIds(WaterConnectionRequest waterConnectionRequest) { waterConnectionProducer.push(wsConfiguration.getSaveFileStoreIdsTopic(), waterConnectionRequest); } public Boolean isSearchOpen(User userInfo) { return userInfo.getType().equalsIgnoreCase("SYSTEM") && userInfo.getRoles().stream().map(Role::getCode).collect(Collectors.toSet()).contains("ANONYMOUS"); } public BillingCycle getBillingCycle(String paymentId) { String query = WsQueryBuilder.GET_BILLING_CYCLE; List<Object> prepareStatementList = new ArrayList<Object>(); prepareStatementList.add(paymentId); List<BillingCycle> billingCycleList = jdbcTemplate.query(query, prepareStatementList.toArray(), billingCycleRowMapper); return billingCycleList.get(0); } public List<Feedback> getFeebback(FeedbackSearchCriteria feedbackSearchCriteria) { List<Object> preparedStamentValues = new ArrayList<Object>(); String query = wsQueryBuilder.getFeedback(feedbackSearchCriteria, preparedStamentValues); List<Feedback> feedBackList = jdbcTemplate.query(query, preparedStamentValues.toArray(), feedbackRowMapper); return feedBackList; } public Map<String, Long> getCollectionDataCounter(List<Map<String, Object>> countDataMap, Boolean flag) { Map<String, Long> collectionDataCountMap = new HashMap<>(); Long paidCount = 0L; Long pendingCount = 0L; if(!CollectionUtils.isEmpty(countDataMap)) { for(Map<String, Object> wc : countDataMap) { BigDecimal collectionPendingAmount = (BigDecimal)wc.get("pendingamount"); if(collectionPendingAmount != null ) { if(collectionPendingAmount.compareTo(BigDecimal.ZERO) <= 0) { ++paidCount; } else { ++pendingCount; } }else { ++paidCount; } } if(flag != null) { if(flag) collectionDataCountMap.put("collectionPaid", paidCount); else if(!flag) collectionDataCountMap.put("collectionPending", pendingCount); }else { collectionDataCountMap.put("collectionPaid", paidCount); collectionDataCountMap.put("collectionPending", pendingCount); } } return collectionDataCountMap; } public Integer getTotalDemandAmount(@Valid SearchCriteria criteria) { StringBuilder query = new StringBuilder(wsQueryBuilder.NEWDEMAND); query.append(" and dmd.taxperiodto between " + criteria.getFromDate() + " and " + criteria.getToDate()) .append(" and dmd.tenantId = '").append(criteria.getTenantId()).append("'"); return jdbcTemplate.queryForObject(query.toString(), Integer.class); } public Integer getActualCollectionAmount(@Valid SearchCriteria criteria) { StringBuilder query = new StringBuilder(wsQueryBuilder.ACTUALCOLLECTION); query.append(" and py.transactionDate >= ").append(criteria.getFromDate()).append(" and py.transactionDate <= ") .append(criteria.getToDate()).append(" and py.tenantId = '").append(criteria.getTenantId()).append("'"); return jdbcTemplate.queryForObject(query.toString(), Integer.class); } public Integer getPendingCollectionAmount(@Valid SearchCriteria criteria) { StringBuilder query = new StringBuilder(wsQueryBuilder.PENDINGCOLLECTION); query.append(" and dmd.taxperiodto between " + criteria.getFromDate() + " and " + criteria.getToDate()) .append(" and dmd.tenantId = '").append(criteria.getTenantId()).append("'"); log.info("Active pending collection query : " + query); return jdbcTemplate.queryForObject(query.toString(), Integer.class); } @Override public List<String> getWCListFuzzySearch(SearchCriteria criteria) { List<Object> preparedStatementList = new ArrayList<>(); String query = wsQueryBuilder.getIds(criteria, preparedStatementList); try { return jdbcTemplate.query(query, preparedStatementList.toArray(), new SingleColumnRowMapper<>()); }catch (Exception e) { log.error("error while getting ids from db: "+e.getMessage()); throw new CustomException("EG_WC_QUERY_EXCEPTION", "error while getting ids from db"); } } }
package com.jacob68.packageInstaller.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.util.ArrayList; import org.junit.Test; import com.jacob68.packageInstaller.DependencyResolver; import com.jacob68.packageInstaller.Node; import com.jacob68.packageInstaller.Result; /** * Test class that runs JUnit tests on the {@linkplain DependencyResolver} class * methods. * * @author Jacobus LaFazia */ public class PackageInstallerTest { /** * Runs list size tests on the convertPackagesToNodes() method for all valid * test arrays. */ @Test public void inputOutputListSizesOnConvertPackagesShouldMatch() { System.out.print("\nSTART--Convert Packages List Sizes Test--"); for (int i = 0; i < 4; i++) { // Get input package list String[] input; switch (i) { case 0: input = TestHelper.getValidSimpleSmall(); System.out.print("\n------Test: Simple Small------"); break; case 1: input = TestHelper.getValidSimpleLarge(); System.out.print("\n------Test: Simple Large------"); break; case 2: input = TestHelper.getValidSmall(); System.out.print("\n------Test: Small------"); break; default: input = TestHelper.getValidLarge(); System.out.print("\n------Test: Large------"); break; } // Print out the input System.out.print("\nInput: " + TestHelper.convertArrayToString(input)); // Convert package list to node list ArrayList<Node> nodes = DependencyResolver .convertPackagesToNodes(input); // Print out the nodes list System.out.print("\nOutput: " + TestHelper.convertNodeListToString(nodes, true)); // Print pass or fail if (input.length == nodes.size()) { System.out.print("\n PASSED"); } else { System.out.print("\n FAIL"); System.out.print("\nEND\n"); } assertEquals("Input list size (" + input.length + ") must equal output list size (" + nodes.size() + ")", input.length, nodes.size()); } System.out.print("\nEND\n"); } /** * Runs list size tests on the computeDependencies() method for all valid * test arrays. */ @Test public void inputOutputListSizesOnComputeDependenciesShouldMatch() { System.out.print("\nSTART--Compute Dependencies List Sizes Test--"); for (int i = 0; i < 4; i++) { // Get input package list String[] input; switch (i) { case 0: input = TestHelper.getValidSimpleSmall(); System.out.print("\n------Test: Simple Small------"); break; case 1: input = TestHelper.getValidSimpleLarge(); System.out.print("\n------Test: Simple Large------"); break; case 2: input = TestHelper.getValidSmall(); System.out.print("\n------Test: Small------"); break; default: input = TestHelper.getValidLarge(); System.out.print("\n------Test: Large------"); break; } // Print out the input System.out.print("\nInput: " + TestHelper.convertArrayToString(input)); // Compute dependency list Result result = DependencyResolver.resolveDependencies(input); // Print out the results String msg = result.getErrorMessage(); ArrayList<Node> resolved = result.getResolvedNodes(); if (msg != null) { // Failed System.out.print("\nOutput: ERROR-" + msg); System.out.print("\n FAIL"); System.out.print("\nEND\n"); fail("Error: " + msg); } else { // Print out the output msg = TestHelper.convertNodeListToString(resolved, false); System.out.print("\nOutput: " + msg); // Print pass or fail if (input.length == resolved.size()) { System.out.print("\n PASSED"); } else { System.out.print("\n FAIL"); System.out.print("\nEND\n"); } } assertEquals( "Input list size (" + input.length + ") must equal output list size (" + resolved.size() + ")", input.length, resolved.size()); } System.out.print("\nEND\n"); } /** * Runs tests on all valid test package lists to ensure they evaluate to * valid. */ @Test public void packageListsShouldBeValid() { System.out.print("\nSTART--Valid Package Lists Test--"); for (int i = 0; i < 4; i++) { // Get input package list String[] input; switch (i) { case 0: input = TestHelper.getValidSimpleSmall(); System.out.print("\n------Test: Simple Small------"); break; case 1: input = TestHelper.getValidSimpleLarge(); System.out.print("\n------Test: Simple Large------"); break; case 2: input = TestHelper.getValidSmall(); System.out.print("\n------Test: Small------"); break; default: input = TestHelper.getValidLarge(); System.out.print("\n------Test: Large------"); break; } // Print out the input System.out.print("\nInput: " + TestHelper.convertArrayToString(input)); // Compute dependency list Result result = DependencyResolver.resolveDependencies(input); // Print out the results String msg = result.getErrorMessage(); ArrayList<Node> resolved = result.getResolvedNodes(); if (msg != null) { // Failed System.out.print("\nOutput: ERROR-" + msg); System.out.print("\n FAIL"); System.out.print("\nEND\n"); } else { // Print out the output msg = TestHelper.convertNodeListToString(resolved, false); System.out.print("\nOutput: " + msg); System.out.print("\n PASSED"); } assertNotNull("Package list " + input.toString() + " should generate a Non-Null dependency list", resolved); } System.out.print("\nEND\n"); } /** * Runs tests on all cyclic test package lists to ensure the circular * dependency is detected. */ @Test public void packageListsShouldBeCyclic() { System.out.print("\nSTART--Cyclic Package Lists Test--"); for (int i = 0; i < 4; i++) { // Get input package list String[] input; switch (i) { case 0: input = TestHelper.getCyclicSimpleSmall(); System.out.print("\n------Test: Simple Small------"); break; case 1: input = TestHelper.getCyclicSimpleLarge(); System.out.print("\n------Test: Simple Large------"); break; case 2: input = TestHelper.getCyclicSmall(); System.out.print("\n------Test: Small------"); break; default: input = TestHelper.getCyclicLarge(); System.out.print("\n------Test: Large------"); break; } // Print out the input System.out.print("\nInput: " + TestHelper.convertArrayToString(input)); // Compute dependency list Result result = DependencyResolver.resolveDependencies(input); // Print out the results String msg = result.getErrorMessage(); ArrayList<Node> resolved = result.getResolvedNodes(); if (msg != null) { // Passed (by failing) System.out.print("\nOutput: " + msg); System.out.print("\n PASSED"); } else { // Print out the output msg = TestHelper.convertNodeListToString(resolved, false); System.out.print("\nOutput: " + msg); System.out.print("\n FAIL"); System.out.print("\nEND\n"); } assertNull("Package list " + input.toString() + " is cyclic and should generate a Null dependency list", resolved); } System.out.print("\nEND\n"); } }
package org.alexkov.bookservice; import lombok.Data; import lombok.Value; /** * Created by alexk on 21.01.2018. */ @Data public class Book { final Long id; final String author; final String title; }
/** * Copyright © 2015 - 2017 EntDIY JavaEE Development Framework * * Site: https://www.entdiy.com, E-Mail: xautlx@hotmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.entdiy.core.entity; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.GenericGenerator; import org.hibernate.envers.AuditOverride; import org.hibernate.envers.AuditOverrides; import javax.persistence.*; /** * 框架提供一个基础的UUID方式的实体对象定义参考 * 具体可根据项目考虑选用其他主键如自增、序列等方式,只需修改相关泛型参数类型和主键定义注解即可 * 各属性定义可先简单定义MetaData注解即可,具体细节的控制属性含义可查看具体代码注释说明 */ @Getter @Access(AccessType.FIELD) @JsonInclude(Include.NON_EMPTY) @MappedSuperclass @AuditOverrides({@AuditOverride(forClass = BaseUuidEntity.class)}) public abstract class BaseUuidEntity extends BaseEntity<String> { @Id @Column(length = 40) @GeneratedValue(generator = "hibernate-uuid") //HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF RFC 4122 compliant UUID values; consider using org.hibernate.id.UUIDGenerator instead @GenericGenerator(name = "hibernate-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonProperty private String id; public void setId(String id) { //容错处理id以空字符提交参数时修改为null避免hibernate主键无效修改 if (StringUtils.isBlank(id)) { this.id = null; } else { this.id = id; } } }